After building an object array and posting it to a jsp page I'm having trouble figuring out how to parse the data.
var arr = [];
for(var i=1; i <= $('#tableData tr').length; i++){
var el = $("#tableData tr:nth-child("+i+")");
var obj = {
id: el.find("td:nth-child(3)").text(),
doc: el.find("td:nth-child(5)").text(),
desc: el.find("td:nth-child(4)").text(),
};
arr.push(obj);
}
$.ajax('controllers/savePrintOutDetail.jsp', {
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(arr),
success: function(response){
},
error: function(){
alert('error');
}
})
I am aware I can retrieve the post data using getReader() but from there I don't know how to parse the array.
I was able to parse the data using org.json
<%# page import="org.json.JSONObject"%>
<%# page import="org.json.JSONArray"%>
<%
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) { /*report an error*/ }
JSONArray array = new JSONArray(jb.toString());
for(int i=0;i<array.length();i++){
JSONObject jsonObj = new JSONObject(array.get(i).toString());
jsonObj.get("id") // etc
}
%>
Related
hello guys please i have an issue with ajax i have this function that fetch data from jsp but when i add a new data to the database and call the function again it duplicates the data unless i refresh the page which i don't want users to do
<script>
search1();
function search1(){
$.ajax({
type:"GET",
url:"drop.jsp",
dataType:'JSON',
data:{"title":'title'},
success:function(data){
console.log(data);
for(var i = 0; i< data.length; i++){
$('#title').append($("<option/>",
{
text: data[i].area,
}));
}
},
error(err){
alert("error")
}
});
}
</script>
it fetch's data as i want but when i call that same function with another function it duplicate the dropdown data the second function is below
<script>
function title2(){
$.ajax({
type:"POST",
url:"drop.jsp",
data:{"title1":$("#title1").val()},
success:function(msg){
var obj = JSON.parse(msg);
search1();
},
error(err){
alertify.error('Error');
}
})
}
</script>
and the jsp code is
String title = request.getParameter("title");
String marital = request.getParameter("marital");
String minis = request.getParameter("minis");
String occu = request.getParameter("occu");
String job = request.getParameter("job");
String bs = request.getParameter("bs");
String class1 = request.getParameter("class1");
String course = request.getParameter("course");
JSONArray list =new JSONArray();
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/cop","root","root");
Statement st = con.createStatement();
if(title != null){
String sql = "Select * from title";
ResultSet rs = st.executeQuery(sql);
while(rs.next()){
JSONObject obj = new JSONObject();
String area = rs.getString("title");
obj.put("area", area);
list.add(obj);
}
out.println(list.toJSONString());
out.flush();
}
and the output is in the image
the output
I used to do a post request using native C#'s library
var httpWebRequest = (HttpWebRequest)WebRequest.Create(djangoApi + user);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"wallet_id\":\""+wallet+"\"," +
"\"token\":\"foo\"}";
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
but that doesn't work on mobile. So, I need to use UnityWebRequest
Following the example, https://docs.unity3d.com/Manual/UnityWebRequest-SendingForm.html, my functions look almost identical. Here is the coroutine function
IEnumerator SendPostCoroutine()
{
WWWForm form = new WWWForm();
form.AddField("user_id", "0x241477cE189fa014292d99e0807cB449b878");
form.AddField("token", "foo");
using (UnityWebRequest www = UnityWebRequest.Post(djangoApi + user, form))
{
Debug.Log(www.downloadHandler.text);
yield return www.SendWebRequest();
if (www.isNetworkError)
{
Debug.Log(www.error);
}
else
{
Debug.Log("POST successful!");
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<string, string> dict in www.GetResponseHeaders())
{
sb.Append(dict.Key).Append(": \t[").Append(dict.Value).Append("]\n");
}
// Print Headers
Debug.Log(sb.ToString());
string response = Encoding.UTF8.GetString(www.downloadHandler.data);
Debug.Log(response);
Debug.Log(www.downloadHandler.text);
}
}
}
When I do
string response = Encoding.UTF8.GetString(www.downloadHandler.data);
Debug.Log(response);
Debug.Log(www.downloadHandler.text);
neither prints out the body of the object I want. Instead, all I get is
<!DOCTYPE html>
<html lang="en">
What can I do to get the values within the json?
I just used
IEnumerator Post(string url, string bodyJsonString)
{
var request = new UnityWebRequest(url, "POST");
byte[] bodyRaw = Encoding.UTF8.GetBytes(bodyJsonString);
request.uploadHandler = (UploadHandler) new UploadHandlerRaw(bodyRaw);
request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
yield return request.Send();
Debug.Log("Status Code: " + request.responseCode);
}
taken from https://forum.unity.com/threads/posting-json-through-unitywebrequest.476254/. That way, I can post my raw json
I have the following MVC post.
It post file contents to API.
[HttpPost]
public ActionResult FileUpload_Post()
{
if (Request.Files.Count > 0)
{
var file = Request.Files[0];
using (HttpClient client = new HttpClient())
{
using (var content = new MultipartFormDataContent())
{
byte[] fileBytes = new byte[file.InputStream.Length + 1]; file.InputStream.Read(fileBytes, 0, fileBytes.Length);
var fileContent = new ByteArrayContent(fileBytes);
fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = file.FileName };
content.Add(fileContent);
var result = client.PostAsync(requestUri, content).Result;
if (result.StatusCode == System.Net.HttpStatusCode.Created)
{
ViewBag.Message= "Created";
}
else
{
ViewBag.Message= "Failed";
}
}
}
}
return View();
}
What if i want to pass additional custom object (preferably json format) along with file contents?
CustomObject obj = new CustomObject;
obj.FirstName = "A";
object.LastName = "B";
Note: Following is Api method that will receive above request.
[HttpPost]
public HttpResponseMessage Upload()
{
if(!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
if (System.Web.HttpContext.Current.Request.Files.Count > 0)
{
var file = System.Web.HttpContext.Current.Request.Files[0];
....
// save the file
....
return new HttpResponseMessage(HttpStatusCode.Created);
}
else
{
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
}
First you need to serialize the CustomObject into json. e.g. using Json.NET
var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
Then you could add the jsonString to the MultipartFormDataContent like:
var jsonContent = new StringContent(jsonString);
content.Add(jsonContent, "CustomObject");
In the Upload API method, get the posted json content by
var jsonString = System.Web.HttpContext.Current.Request.Form["CustomObject"];
If the API project has a reference to class CustomObject, you could deserialize the jsonString with:
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<CustomObject>(jsonString);
If not, you could also deserialize it to a dynamic object:
var obj = Newtonsoft.Json.Linq.JObject.Parse(jsonString);
I have seen & tried a lot of codes to increase the JSON limit like in
1. web.config
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="2147483647"/>
</webServices>
</scripting>
</system.web.extensions>
2.JSonControllerFactory
public sealed class CustomJsonValueProviderFactory : ValueProviderFactory
{
private static void AddToBackingStore(Dictionary<string, object> backingStore, string prefix, object value)
{
IDictionary<string, object> d = value as IDictionary<string, object>;
if (d != null)
{
foreach (KeyValuePair<string, object> entry in d)
{
AddToBackingStore(backingStore, MakePropertyKey(prefix, entry.Key), entry.Value);
}
return;
}
IList l = value as IList;
if (l != null)
{
for (int i = 0; i < l.Count; i++)
{
AddToBackingStore(backingStore, MakeArrayKey(prefix, i), l[i]);
}
return;
}
// primitive
backingStore[prefix] = value;
}
Down here in GetDeserializedObject() i am getting bodytext as empty and unable to set the max property.
private static object GetDeserializedObject(ControllerContext controllerContext)
{
if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
{
// not JSON request
return null;
}
StreamReader reader = new StreamReader(controllerContext.HttpContext.Request.InputStream);
string bodyText = reader.ReadToEnd();
if (String.IsNullOrEmpty(bodyText))
{
// no JSON data
return null;
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = int.MaxValue; //increase MaxJsonLength. This could be read in from the web.config if you prefer
object jsonData = serializer.DeserializeObject(bodyText);
return jsonData;
}
}
script [down data: jQuery("#geomaster").serialize() contains data. If it is below 100 points the data is saving successfully. if it crosses 100 points, not hitting the controller SaveGeodata method(i mean not posting to controller)].
jQuery.ajax({
type: "GET",
url: "SaveGeodata",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: jQuery("#geomaster").serialize(),
success: function (data) {
alert("Geofence Created Successfully");
},
error: function (msg) {
alert("Error");
}
});
Is there any way where i can attach the maxJsonSize property in script itself.
Any other possible means which could help in posting max data to controller is really thankful.
I'm new to windows phone 8 development.
Could you please help me how to send the xml data to the server through http post calls in windows phone 8?
Thanks
This is a sample code I used in my project. Modify according to your needs
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("url to submit to");
req.Method = "POST";
//Add a Header something like this
//req.Headers["SOAPAction"] = "http://asp.net/ApplicationServices/v200/AuthenticationService/Login";
req.ContentType = "text/xml; charset=utf-8";
//req.UserAgent = "PHP-SOAP/5.2.6";
string xmlData = #"<?xml version=""1.0"" encoding=""UTF-8""?>Your xml data";
// Convert the string into a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(xmlData);
req.Headers[HttpRequestHeader.ContentLength] = byteArray.Length.ToString();
req.BeginGetRequestStream(ar =>
{
using (var requestStream = req.EndGetRequestStream(ar))
{
// Write the body of your request here
requestStream.Write(byteArray, 0, xmlData.Length);
}
req.BeginGetResponse(a =>
{
try
{
var response = req.EndGetResponse(a);
var responseStream = response.GetResponseStream();
using (var streamRead = new StreamReader(responseStream))
{
// Parse the response message here
string responseString = streamRead.ReadToEnd();
//If response is also XML document, parse it like this
XDocument xdoc = XDocument.Parse(responseString);
string result = xdoc.Root.Value;
if (result == "true")
{
//Do something here
}
else
Dispatcher.BeginInvoke(() =>
{
//result failed
MessageBox.Show("Some error msg");
});
}
}
catch (Exception ex)
{
Dispatcher.BeginInvoke(() =>
{
//if any unexpected exception occurs, show the exception message
MessageBox.Show(ex.Message);
});
}
}, null);
}, null);