value missing on AJAX response - javascript

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"}';

Related

Getting Certain values from an AJAX return JSON object

I am trying to retrieve certain values in a JSON object retrieved from AJAX.
Using console.log(), I was able to view these:
0: Object
title: "First post"
body: "This is a post"
id: 1
userId: 27
.
.
.
100: //same format of data as object 0
Now I want to try storing the whole JSON object above so that I can use the userId and match it with another list of data to find the user who made the post. Problem is, I can't store it to a global variable. Here is my jscript snippet:
var postJson; //global variable
---somewhere in a function---
$.ajax({
url: root + '/posts',
type: "GET",
dataType: "JSON",
success: function(response){
postJson = response;
console.log(response);
}
});
I also tried doing postJson = $.ajax but nothing happened and postJson continues to be undefined.
$.ajax is async function, you need to use callback or do all the code in success function
var postJson; //global variable
function doSomething(r){
//r is here
}
---somewhere in a function---
$.ajax({
url: root + '/posts',
type: "GET",
dataType: "JSON",
success: function(response){
postJson = response;
//do something with postJson or call function doSomething(response)
}
});
function doSomething(r){
//r is here
}
---somewhere in a function---
$.ajax({
url: root + '/posts',
type: "GET",
dataType: "JSON",
success: function(response){
doSomething(response);
//do something with postJson or call function doSomething(response)
}
});
You can do directly via calling function from response no need to declare variable. Hope it will also helps you

converted JS array to JSON object but not able to read that json object at java servelet end

this is javascript code to create json variable and i am not able to get how to acess >this json variable at servlet end.
<script>
function()
{ alert("sending");
var Jsonobj=JSON.stringify(folderarray);
alert(Jsonobj);
$.ajax({ url: '/Chandrayan-2014/src/Handler/FolderHandler.java'+param,
type: 'POST',
dataType: 'json',
success: function(result) {
alert('SUCCESS'); } });
alert("sent");
}
May i suggest you to use console.log instead of alert?
also, like cloudwalker said, i see your ajax call is missing the data property
var Jsonobj=JSON.stringify(folderarray);
console.log(Jsonobj);
$.ajax({
'type' : 'POST',
'url' : '/route/to/my/handler',
'data' : Jsonobj,
'success' : function () { console.log('succeed with args %o', arguments); },
'error' : function () { console.log('failed with args %o', arguments); }
});
Note that the dataType property is used to specified the type of data that you're expecting back from the server. Not the type of data you're submiting
I don't see where you're actually passing the jsonobj as a parameter. You'd maybe want something like:
$.ajax({ url: '/myUrl',
type: 'POST',
dataType: 'json',
data: {myJsonObj: Jsonobj} --PASS THE OBJECT HERE
success: function(result) {
alert('SUCCESS'); } });
alert("sent");
I'm also a little confused about your url. Are you trying to link directly to a java source file, or did you just set up a servlet mapping that has .java at the end?

jQuery .ajax call never calling method

In this SO post I learned how to get a return value from an AJAX call:
function CallIsDataReady(input) {
$.ajax({
url: "http://www.blah.com/services/TestsService.svc/IsDataReady",
type: "GET",
contentType: "application/json; charset=utf-8",
data: input,
dataType: "json",
success: function (data) {
if (!data) {
setTimeout(function (inputInner) { CallIsDataReady(inputInner); }, 1000);
}
else {
//Continue as data is ready
callUpdateGrid(input);
}
}
});
}
$(document).ready(function () {
var input = { requestGUID: "<%=guid %>" };
CallIsDataReady(input);
});
This function calls its web service wich does return true. The problem is that inside the following callUpdateGrid, the logging shows that that web service method is not getting called from the $.ajax call:
function callUpdateGrid(input) {
console.log(input);
$.ajax({
url: "http://www.blah.com/services/TestsService.svc/GetContactsDataAndCountbyGUID",
type: "GET",
contentType: "application/json; charset=utf-8",
data: input,
dataType: "json",
success: function (data) {
var mtv = $find("<%= RadGrid1.ClientID %>").get_masterTableView();
console.log(data);
mtv.set_dataSource(data.d.Data);
mtv.dataBind();
}
});
}
Anyone know what is wrong?
It is always a good idea to include an error handler function as one of the options passed to $.ajax. For example, add this code after your success functions:
,
error: function(jqXHR, textStatus, errThrown) {
console.log("AJAX call failed");
console.log(errThrown);
}
That will log at least a bit of information if the $.ajax call doesn't succeed.
EDIT
According to your comment, this logs
SyntaxError: Invalid character
And in fact, I now see that you are giving a plain JavaScript object as the data option passed to $.ajax, but indicating that it is a JSON object in the dataType field. You need to actually convert the input object into JSON yourself, like so:
data: JSON.stringify(input),
dataType: 'json',
Alternatively, you could simply format input as a JSON object in first place, like so:
var input = { "requestGUID": "<%=guid %>" };
The quotes around the field name requestGUID are sufficient, in this case, to give you a JSON object.

AJAX: How to use returned array?

I have an ajax POST that sends data to a controller function and that function returns a string array back to the ajax call as the default 1st parameter in the ajax success method. When I tried to use the returned data, it won't let me print the 1st element to an alert box. How come?
i.e.
$.ajax(
{
type: "POST",
url: "../Home/stringSplitFunct",
data: { 'parameter1': Input },
success: function (response)
{
alert(response[0]);
}
});
In fact, I don't think it even recognize it as a string array.
You need to specify dataType. Read more here.
$.ajax({
type: "POST",
url: "../Home/stringSplitFunct",
data: { 'parameter1': Input },
dataType: 'json',
success: function (response)
{
alert(response[0]);
}
});
Looks like the data is being returned as a raw sting.
Use dataType property for your ajax request
dataType: 'json'
Also avoid using alert as it stops the execution flow. Use console.log instead

Passing js object as json to jquery?

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),
...

Categories