jQuery ajax is not working when send post request - javascript

i try to use ajxt to send post request to my restful service
here is my ajax code
var lat = marker.getPosition().lat();
var lng = marker.getPosition().lng();
//xmlhttp.open("GET","http://192.168.1.100:8080/MapDemo/service/add?name=hieugie333&longitude=123&latitude=321",true);
//xmlhttp.send();
//document.getElementById("message").innerHTML=xmlhttp.responseText;
var JSONObject= {"name":name, "longitude":lng,"latitude":lat };
var jsonData = JSON.parse( JSONObject );
var request = $.ajax({
url: "http://192.168.1.100:8080/MapDemo/service/add",
type: "POST",
contentType: "application/json; charset=utf-8",
data: jsonData,
dataType: "json"
});
can anyone help me in this case ?

var JSONObject= {"name":name, "longitude":lng,"latitude":lat };
That is a JavaScript object, not a JSON text.
var jsonData = JSON.parse( JSONObject );
That will error (or return null) because you aren't passing it a string containing a JSON text.
Your later code is expecting a string containing a JSON text though.
You want JSON.stringify not JSON.parse.

You need to change your "JSON.parse" to "JSON.stringify". You called the opposite function that you should have.

Related

Get Object XmlDocument value

I'm executing an ajax call to a external api (this cannot be modified) to upload an store a file into a folder. This request must return a path (ex. "C:\Doctos\File.pdf" but after a console.log is returning something like this:
#document < string xmlns="http://tempuri.org/">"C:\Doctos\File.pdf"
So my question is, what can I do to get only the text that I want without any change in the api (because I'm not able to do it).
Here is the ajax call that I'm using.
PD. This ajax call is using the provided structure for the dev team that developed the api so things like dataType also cannot be modified
var data = new FormData();
var files = $('#fileUpload').get(0).files;
if (files.length > 0) {
data.append("UploadedFile", files[0]);
}
$.ajax({
type: 'POST',
url: 'api/v1/moreurl/UploadFile',
contentType: false,
processData: false,
data: data,
success: function (data) {
var res = data;
//Returns above example
console.log(res);
//Returns something like <p>[object XMLDocument]</p>
$('#MyInput').attr('src', res);
}
});
I would use regular expressions to get the desired string from received data. Put this after success line.
var regex = />\"(.*)\"/;
var matched = regex.exec(data);
var result = matched[1];
console.log(result);
The regex matches the last quoted string in your example.
You can get the data in the xml with jQuery
$.ajax({
type: 'POST',
url: 'api/v1/moreurl/UploadFile',
contentType: false,
processData: false,
data: data,
success: function (data) {
// Get the contents of the xml
var file = $(data).find('string').text();
$('#MyInput').attr('src', file);
}
});

AJAX isn't treating json as json

My AJAX call isn't treating the data from server as JSON, even if i set the datatype in json:
function Getmateriasfromserver(callback){
var status_aux;
//Requisição HTTP, por dados provindos do url dado. Caso os dados recebidos sejam os esperados, entra no caso do SUCCESS
return $.ajax({
url: 'materiasphp/materias.php',
dateType: 'json',
success: function(data)
{
status_aux = data;
callback(status_aux);
var test = JSON.stringify(data);
console.log(data);
console.log(test[1]);
}
Console print test[1] = "["
You also have a typo in your code. dateType: should be dataType:
return $.ajax({
url: 'materiasphp/materias.php',
dataType: 'json',
...
var test = JSON.stringify(data);
Should probably be
var test = JSON.parse(data);
// or just
var test = data;
Because if you stringify it, then you are accessing letters in the string with bracket notation.
var test="cat":
console.log(test[0]);
Is c, the first letter in the string
JSON is a text based data format.
JSON.stringify(data); takes data and converts it to a JSON text, which it stores in a string.
console.log(test[1]); then reads the character at index 1 in that string and displays it.
This is normal behaviour.
If you want to deal with the data as a JavaScript data structure then don't convert it to JSON!.
Just work directly with the data structure in data.

Convert from JSON to array of objects

I'm trying to convert an array of Hazards(class that i created) to JSON,
this is my code:
$.ajax({
async: true,
url: web + "/GetHazards",
method: "POST",
contentType: "application/json",
success: function (data) {
var res = data.d;
var i;
alert(res[0]);
the returned data is like this :
"[{\"Hazard_ID\":3014,\"Hazard_Lat\":32.2615929,\"Hazard_Long\":35.01423},{\"Hazard_ID\":3013,\"Hazard_Lat\":32.3426857,\"Hazard_Long\":34.9103165},{\"Hazard_ID\":3012,\"Hazard_Lat\":32.3426857
My server side code returns the correct values that i need, but the problem is when i alert the res[i] it behave like res is a string and alerts me "["
what i need to get is
{\"Hazard_ID":3014,\"Hazard_Lat\":32.2615929,\"Hazard_Long\":35.01423}
i dont know if it mind this is my server-side code by the way:
{
List<Returned_Hazard> rh = new List<Returned_Hazard>();
JavaScriptSerializer json = new JavaScriptSerializer();
.
.
.
while (reader.Read())
{
Returned_Hazard RH = new Returned_Hazard(
int.Parse(reader[0].ToString()),
float.Parse(reader[1].ToString()),
float.Parse(reader[2].ToString())
);
rh.Add(RH);
}
command.Connection.Close();
return json.Serialize(rh);
}
You need to parse the JSON, using JSON.parse:
var data = { d: "[{\"Hazard_ID\":3014,\"Hazard_Lat\":32.2615929,\"Hazard_Long\":35.01423},{\"Hazard_ID\":3013,\"Hazard_Lat\":32.3426857,\"Hazard_Long\":34.9103165}]"
};
var res = JSON.parse(data.d);
console.log(res[0].Hazard_ID); //3014

Sending Json Array in POST request for JavaScript

I am having trouble in sending a JSON array in an AJAX call. Following is my Code
var company_name = $('input#company_name').val();
var company_localname = $('input#company_localname').val();
var companytype = $('#companytype').val();
if (companytype == 'retailer') {
var bank_name = $('input#bank_name').val();
var account_title = $('input#account_title').val();
var business_nature = $('input#business_nature').val();
var gross_sales = $('input#gross_sales').val();
}
After getting all the values I am storing the data in Json like the following
var jsonArray = [];
jsonArray["company_name"] = company_name;
jsonArray["company_localname "] = company_localname;
if (companytype == 'retailer') {
jsonArray["bank_name"] = bank_name;
jsonArray["account_title"] = account_title;
jsonArray["business_nature"] = business_nature;
jsonArray["gross_sales"] = gross_sales;
}
Now for sending the jsonArray in Ajax call
$.ajax({
url : url,
type : "POST",
dataType : 'json',
contentType : 'application/json; charset=UTF-8',
data : JSON.stringify(jsonArray),
success : function(response) {
//Some Code here
}
});
Please help me sending data. Or tell me if I am making any mistake here. Thank you
In JavaScript / JSON arrays are 0 based indexed data structures. What you are using here is more like a Map:
var jsonArray = [];
jsonArray["company_name"]=company_name ;
In JavaScript you cannot use arrays like this (well you can, but it is probably not what you want). For a data structure like a map that maps strings to objects rather then an index to objects, just use an object.
Or in short: Use var jsonArray = {}; rather than var jsonArray = []; The {} will create an object that you can assign properties to like you did. And JSON.stringify will correctly translate this into a JSON string like this:
{ "property": value, "otherProperty", otherValue }
Do something like this.
$.ajax({
url: url,
type: "POST",
dataType: 'json',
contentType: 'application/json; charset=UTF-8',
data: JSON.parse(JSON.stringify(jsonArray)),
success: function(response) {
//Some Code here
}
});
The JSON.parse() method parses a string as JSON, optionally transforming the value produced by parsing. Read more about JSON.parse() method
The JSON.stringify() method converts a JavaScript value to a JSON string. Read more about JSON.stringify() method
Here simply you can send an array and Parse it in server side.
$.ajax({
url : url,
type : "POST",
dataType : 'json',
data : jsonArray,
success : function(response) {
//Some Code here
}
});

sending json data to server returns 400 bad request

I want to send my string value to server as json data, but i get 400 bad request.
here is the code how i am sending data.
dataString = '{"comment":"' +dataString+ '"}';
dataString = '[' + dataString + ']';
$.parseJSON(dataString);
console.debug("After parsing : "+dataString);
$(form_element).clearForm();
$.ajax({
type : "POST",
url : loc,
cache : false,
data : dataString,
dataType: 'json',
contentType: "application/json",
success : function(data) {
console.debug("After success");
}
When i debug the code, the #RequestParameter "comment" have null value.
Kindly help me, thanks in advance.
The parseJSON function returns an object.
You should do
var obj = $.parseJSON(dataString);
$.ajax({
type : "POST",
url : loc,
cache : false,
data : obj,
That's supposing you really need to build your string as you do. It's generally simpler to just build your object instead of making a json string, parsing it then asking jQuery to serialize it again.
I think you shoud pass json object NOT json array.
var dataString = '{"comment":"test"}';
//dataString = '[' + dataString + ']'; //delete this, NOT array
var obj = $.parseJSON(dataString);
console.log(obj);
$.ajax({
type : "POST",
url : url,
cache : false,
data : obj,
contentType:"application/json; charset=utf-8",
dataType:"json",
success : function(data) {
console.debug("After success");
}
});

Categories