I have the following but it's not working, I read somewhere on the stackoverflow that it works like this but I can't seem to get it to work.. it errors... am I doing something wrong?
If I do pass data like this - it works -- so I know my service is working
//THIS WORKS
data: "{one : 'test',two: 'test2' }"
// BUT SETTING UP OBJECT doesn't work..
var saveData = {};
saveData.one = "test";
saveData.two = "tes2";
$.ajax({
type: "POST",
url: "MyService.aspx/GetDate",
data: saveData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg.d);
},
error: function(msg) {
alert('error');
}
});
I believe that code is going to call .value or .toString() on your object and then pass over the wire. You want to pass JSON.
So, include the json javascript library
http://www.json.org/js.html
And then pass...
var saveData = {};
saveData.one = "test";
saveData.two = "tes2";
$.ajax({
type: "POST",
url: "MyService.aspx/GetDate",
data: JSON.stringify(saveData), // NOTE CHANGE HERE
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg.d);
},
error: function(msg) {
alert('error');
}
});
According to this blog post, the reason it doesn't work when you try to pass the object is that jQuery attempts to serialize it. From the post:
Instead of passing that JSON object through to the web service, jQuery will automatically serialize and send it as:
fname=dave&lname=ward
To which, the server will respond with:
Invalid JSON primitive: fname.
This is clearly not what we want to happen. The solution is to make sure that you’re passing jQuery a string for the data parameter[...]
Which is what you're doing in the example that works.
My suggestion would be to use the jquery-json plug-in and then you can just do this in your code:
...
data: $.toJSON(saveData),
...
Related
I can't find what the error is in an AJAX call.
I have a PHP file output:
[{"value":"123","name":"My Name"}]
and this output is correct. And my AJAX call returns undefined after success:
$.ajax({
type: "POST",
url: "correct_file_location.php",
data: $(this.form).serialize(),
dataType: "json",
success: function (pk) {
alert(pk.value);
$("#label_id_name").text(pk.value);
},
error: function (){
alert("error");
}
});
Since the result is an array of objects, you need to first get the object from the array, and then access the properties of that object.
pk[0].value
should work.
*It is showing undefined because you are getting an array of objects and not only object *
try what #freedomn-m suggested in the comments
Try below code it will be work.
$.ajax({
type: "POST",
url: "correct_file_location.php",
//data: $(this.form).serialize(),
dataType: "json",
success: function (pk) {
var data1 = JSON.parse(pk[0].value);
console.log(data1);
// $("#label_id_name").text(pk.value);
},
error: function (){
alert("error");
}
}) ;
Your code will also work but your php response code must be in javascript object.
Please add below code in 'correct_file_location.php' and check with your ajax code.
'{"value":"123","name":"My Name"}';
I have an AJAX script like this
function savetoDB(inp) {
var userID = (FB.getAuthResponse() || {}).userID;
jQuery.ajax({
url: URL,
type: 'GET',
data:{ 'input': JSON.stringify(inp) },
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: true,
success: function(msg) {
console.log(msg);
alert(msg);
}
});
}
The problem I am facing is that the php returns (echo's) some string , but I am unable to see it in alert.
I used the inspect element and Inside inspect element I can see the Response, and also the status is 200, what could be the reason that it is not showing the response in alert?
You are returning a JSON object, so it won't show in alert, which only displays strings. Convert it to a string first:
success: function(msg) {
console.log(msg);
alert(JSON.stringify(msg));
}
Replace "URL" with the actual url of file you're extracting data from otherwise you'll get an empty response as is the case.
Let me start by saying I am not extremely familiar with Javascript and I cannot figure out what is going on here.
I have the following function:
self.search = function () {
var searchTerms = {
"City": this.cityName,
"State": this.stateName,
"StoreNumber": this.storeNumber,
};
$.ajax("/api/SearchApi", {
data: searchTerms,
type: "POST", contentType: "application/json",
success: function (result) {
alert(result);
}
}
});
When I submit, what happens is that instead of submitting a nice JSON object as expected, it submits a JSON objected formatted as so: "City=testing&State=AL&StoreNumber=test "
Ideally I would like to use a GET method that passes the object to my server so that I can return the results, but when I use a get method, it simply appends the above to the API call url resulting in a URL request formed as so: http://localhost:57175/api/SearchApi?City=testing&State=AL&StoreNumber=test
Any help would be appreciated.
Make sure you add the dataType of JSON to your $.ajax({ }); object. That should solve the problem!
$.ajax({
// ...
data : JSON.stringify( searchTerms ), // Encode it properly like so
dataType : "json",
// ...
});
2 Things
Add the json content type(not the data type) to your ajax object important to note is the charset your server is using in this case utf-8.
Use the Json2 Library to stringify and parse Json when sending and retrieving it can be found here : https://github.com/douglascrockford/JSON-js/blob/master/json2.js
$.ajax({
url: URL,
type: "POST",
//Stringify the data you send to make shure its properly encoded
data: JSON.stringify(DATA),
//This is the type for the data that gets sent
contentType: 'application/json; charset=utf-8',
//This is for the data you receive
dataType: "json"
}).done(function(data) {
var dataYouGet = JSON.parse(data);
}).fail(function(xhr, ajaxOptions, thrownError) {
}).always(function(data) {
});
I have a JSON response coming from REST web service and want to bind that data to html using jQuery. Looks like its not even hitting web service url which I have provided in my jquery.
Url is working fine which gives me JSON data in browser but jQuery I am using unable to get any content from this. I am pasting my code here, plz let me know if some one can help.
While debugging script its directly going on error section in ajax call.
<script type="text/javascript">
$(document).ready(function () {
GetData();
});
function GetData() {
// alert(textblock.value);
$.ajax({
type: "GET",
url: "http://localhost:8092/api/Employees",
data: "{'employeeId'= '" + 1234 + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var results = $.parseJSON(msg.d);
alert(msg);
alert(results);
},
error: function (result) {
alert('here');
var tt = result.text;
alert(tt);
}
});
}
</script>
finally i am able to get data now.
I added below properties in $.ajax:
processData: false,
async: false,
I'm using jQuery to grab some JSON data. I've stored it in a variable called "ajaxResponse". I cant pull data points out of it; I'm getting ajaxResponse.blah is not defined. typeof is a string. Thought it should be an object.
var getData = function (url) {
var ajaxResponse = "";
$.ajax({
url: url,
type: "post",
async: false,
success: function (data) {
ajaxResponse = data;
}
});
return ajaxResponse;
},
...
typeof ajaxResponse; // string
ajaxResponse.blah[0].name // ajaxResponse.blah is not defined
make sure you specify option dataType = json
$.ajax({
url: url,
type: "post",
dataType: "json",
async: false,
success: function (data) {
ajaxResponse = data;
}
});
Q8-coder has the right of it, but to give you some details: your server is really passing back a string that you've formatted into JSON. You'll need to tell jQuery what to expect, otherwise it just assumes it received a string.
Add the following to your $.ajax options:
dataType: "json"
Also, refer to the jQuery API for examples and documentation for these options.