format ajax POST data, json into variable - javascript

If I need to call a controller like this:
name.php?data={"user":"test","pass":"test"}
In order to obtain the information I need, via .ajax, I need help setting the variable to be sent with that specific format.
I used to the following code:
var arr = [{
data: {
"user" : $("#usuario").val(),
"pass" : $("#password").val()
}];
arr = JSON.stringify(arr);
However if doesn't send the right output, I've been said I need to send the variable with the json on it.
function callAjax(url, arr) {
var response = null;
jQuery.ajax({
url: url,
type: 'POST',
data: arr,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function(data) {
response = data;
},
error: function(jqXHR, textStatus, errorThrown) {
response = errorThrown;
},
timeout: 5000
});
return response;
}
Any advises?
Best Regards!

This link will help you a lot!
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

I used .post instead and solved the issue

Related

How to pass javascript variable to ajax 'data' attribute

I am tying to pass a javascript variable as an ajax paramater but it is being sent as null. Simply passing 'host' gives 'host' itself which isn't what is desired
var host = "some value"
$.ajax({
type: 'GET',
url: '/Main/GetData/',
data: '{'
hostname '=' + host '}',
dataType: 'json',
success: function(json) {
var data = json;
},
}); //ajax
Try the following:
data: {'hostname' : host},
Pass the data as an object, using key you can access the value of the variable on the server side.
USE:
var host = "some value"
$.ajax({
type: 'GET',
url: '/Main/GetData/',
data: {
"hostname": host
},
dataType: 'json',
success: function(json) {
var data = json;
},
}); //ajax
If you are trying to send data as a string make use of JSON.stringify()
dataToSend = JSON.stringify({ "hostname": host });
And in your AJAX
data : dataToSend
I feel the problem is you have made the wrong JSON data format.
the correct JSON format should be like this:{key:value}
Give an eg. here:
"employees": [
{ "firstName":"Bill" , "lastName":"Gates" },
{ "firstName":"George" , "lastName":"Bush" },
{ "firstName":"Thomas" , "lastName":"Carter" }
]
ex:the employee contains 3 elements
Wish can make some help :)

Is my ajax call correct?

Hi I am trying to make a simple call like this in ajax:
$.ajax({
type: "GET",
url :"${info.contextPath}/secured/contribution/employer/contributionsearch/viewNewContribution?employerCode="+code+"&contbYear="+year+"&contbMonth="+month
+"&orgId="+orgId+"&contbStatus="+status+"&employerDetailId="+employerId,
success: function(data){
alert('123'+data);
$("#newContribution").html(data);
}
});
However, when I see the pop up of my alert I only see '123'. Is my call wrong ?
Use data: {key: value} instead of url concatenation.
Make sure that server's response is correct
Check for the server's response. If possible follow this approach :
$.ajax( {
method : 'GET',
url : '/uri',
data : {key1 : "value1", key2 : "value2"}
}).success(function (data) {
console.log(data);
alert(data);
});
Just try to serialize the response in alert.
$.ajax({
type: "GET",
dataType: "json",
url :"${info.contextPath}/secured/contribution/employer/contributionsearch/viewNewContribution?employerCode="+code+"&contbYear="+year+"&contbMonth="+month +"&orgId="+orgId+"&contbStatus="+status+"&employerDetailId="+employerId,
success: function(data){
var resp = JSON.stringify(data);
alert('123'+resp);
$("#newContribution").html(resp);
}
});

How to call json object from AJAX?

Here is my script:
$.ajax({
type: "Get",
url: "Sample.js",
datatype: 'json',
data: JSON.stringify({ key:key }),
success: function (data) {
var sample = data.name;
$("#html").html(sample);
},
error: function () {
alert("Error");
}
});
This is my Sample.js file:
{ "name": "user" }
When I run this code I get a blank screen. This is my script using getJSON():
$.getJSON("Sample.js", function (data) {
var sample = data.name;
$("#html").html(sample);
})
This produces "user" perfectly. What is the problem with $.ajax code?
In the getJSON version your don't send any data. Could this be the reason why that works? To me it looks like this could be sth. on the server side that delivers an empty JSON object when you pass the key parameter.
As the jQuery documentation states:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
Try modifying the dataType param.
change your datatype to dataType. Its case sensitive. Refer http://api.jquery.com/jQuery.getJSON/
Remove JSON.Stringify and change Get to GET
$.ajax(
{ type: "GET",
url: "Sample.js",
dataType: "json",
data: {key:key },
success: function (data)
{ var sample = data.name; $("#html").html(sample); },
error: function () { alert("Error"); }}
);

howto cut json string?

I have a problem here and no idea how to solve it...
I have a json file like this:
{"data":[{"kw":"48","val":"10","val2":"05"},{"kw":"49","val":"04","val2":"05"}]}
But I need this format:
[{"kw":"48","val":"10","val2":"05"},{"kw":"49","val":"04","val2":"05"}]
In javascript/jQuery I make an ajax request and get the json back:
$.ajax({
type : "POST",
cache : "false", // DEBUG
url : weburl,
dataType : "json",
contentType : "application/json; charset=utf-8",
success : function(data) {
// Strip data?
}
});
Does anyone know how to do this?
Thanks!
success : function (data) {
var array = data ? data.data : null;
// now perform the required operations with array variable.
}
This will return just the array, not wrapped in a object.
$.ajax({
type: "POST",
cache: "false", // DEBUG
url: weburl,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data) {
var arrayYouWant = data.data; // http://thedailywtf.com/Articles/Data-Data-data-Data.aspx
}
});
Why do you need to strip it, you just reference it
success : function(data) {
var myArrayofObjects = data.data;
}
In order to really understand read about the Member operators in Javascript, particularly the dot notation. JSON is a subset of Javascript and the JSON object is a Javascript object in the end.
Not sure what you mean by archive. Do you mean simply access the array that is associated with the data property?
The array is associated to the 'data' property in your JSON string. I would maybe change the name of the data argument passed into the success function.
Try this:
$.ajax({
type: "POST",
cache: "false", // DEBUG
url: weburl,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(resp) {
var yourArray = resp.data;
console.log(yourArray);
}
});

cannot display json data returned from jquery ajax call

can somebody please tell me, how can I display json data returning from the ajax call. I am new to this.
$.ajaxSetup({
cache: false,
timeout: 5000
});
//String.prototype.toJSON;
var the_object = {};
function concatObject(obj) {
strArray = []; //new Array
for (prop in obj) {
strArray.push(prop + " value :" + obj[prop]);
}
return strArray.join();
}
//var ntid = "hhsh";
//document.writeln("httpRequest.responseText");
$(document).ready(function() {
$("button").ajaxStart(function() {
alert('Triggered ajaxStart handler.');
});
$("button").click(function() {
$.ajax({
type: "POST",
dataType: 'JSON',
//data: "{'ntid':'john'}",
//contentType: "application/json; charset=utf-8",
//processData: false,
url: "Testing.aspx/SendMessage",
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
success: function(result, txtStatus, httpRequest) {
alert(txtStatus);
//$('#status').html(httpRequest.responseText);
//the_object = result;
$('#status').html(concatObject(result));
//$('#status').html(the_object);
//alert("hello" + concatObject(the_object));
//document.writeln(concatObject(the_object));
}
});
//alert(concatObject(the_object));
//$('#status').html(concatObject(the_object));
});
});
above is the js file. should i need to do something on asp file directly to display it. if yes, then how? please reply me soon. i m stuck here and unable to display data here. Its only diplaying this line:
toJSON value :function (key) { return this.valueOf(); }
Your result is most likely rooted with a property named d. Try modifying your success to use result.d;
This is usually a security measure that has to do with exploits which target a JSON collection with single root parent.

Categories