Cannot read property '0' of undefined using ajax to get json data - javascript

I have an error in my ajax:
Cannot read property '0' of undefined
dmpConnectInstance.hl_readCpxCard(getCpsPinCode(), function (a) {
var path = "cpx";
$.ajax({
type: "POST",
url: path,
data: a,
success: function (data) {
//
$("#res").html("okyou" + data.PracticeLocations[0].s_practiceLocationName);
console.log('yooo' +
data.PracticeLocations[0].s_practiceLocationName);
}
,
error: function () {
console.log('ko');
}
});
});
Here is the json format:
{
"PracticeLocations":[
{
"s_practiceLocationActivity":"SA07",
"s_practiceLocationHealthcareSettings":"SA07",
"s_practiceLocationName":"CABINET M. INFIRMIER3681"
}
],
"i_remainingPinCodeInputs":3,
"s_given":"ALAIN",
"s_internalId":"00B6036814",
"s_name":"INFIRMIER3681",
"s_profession":"60",
"s_professionOid":"1.2.250.1.71.1.2.7",
"s_speciality":"",
"s_status":"OK"
}
I think I have a problem with the data, when I debug data I got empty message.
Otherwise if I put directly into the function:
console.log('yooo'+a.PracticeLocations[0].s_practiceLocationName);
I got the result.

The JSON content you display in your post, is that what is going in or coming out, and how did you confirm the result if indeed the case? The nature of the error is saying that data.PracticeLocations is null and doesn't contain anything at position 0. If data came back as a truly empty result, then that would make sense and including the code that returns your response would help.
Your subsequent statement in the post was:
console.log('yooo'+a.PracticeLocations[0].s_practiceLocationName);
This has a.PracticeLocations, not data.PracticeLocations, which variable a is not referenced anywhere. I presume that is a typo?

Related

shift() and pop() is not a function

So i was making a random quote generator machine project for learning purposes and encountered a error.
I tried looking for it in other answers but couldn't understand/solve it.
here is the JS code:
$('#new').on('click', function(e) {
e.preventDefault();
$.ajax( {
url: 'https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=mycallback',
success: function(data) {
console.log(data);
var post = data.shift(); // The data is an array of posts. Grabbing the first one.
$('.author').text(post.title);
console.log(post.title);
$('.quote').html(post.content);
console.log(post.content);
},
cache: false
});
});
For the first console.log it shows data in form of array, So I tried pop and shift functions to extract the data. here is the format of data:
/**/mycallback([{"ID":1640,"title":"Scott Belsky","content":"<p>To envision what will be, you must remove yourself from the constant concern for what already is.<\/p>\n","link":"https:\/\/quotesondesign.com\/scott-belsky\/","custom_meta":{"Source":"<a href=\"http:\/\/the99percent.com\/book\">book<\/a>"}}])
It gave undefined for the next 2 console.log() .
Here is the error:
Uncaught TypeError: data.shift is not a function
and it gave errors on both functions. any help would be appreciated.
Two things:
Don't define the callback function. Leave that to $.ajax by replacing the explicit function name to ?
Set the data type to jsonp
$.ajax( {
url: 'https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=?',
dataType:'jsonp',
cache: false,
success: function(data) {
console.log(data);
var post = data.shift();
console.log(post);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>

Uncaught SyntaxError: Unexpected end of input in parseJSON method javascript

In a webpage that uses javascript, I pass data to a hidden input field using
$("#waypt_sel").val(JSON.stringify(itins.arr_intin));
and then later access that data using
waypts_input = $.parseJSON($("#waypt_sel").val())
This works, except that sometimes it gives a
Uncaught SyntaxError: Unexpected end of input
. I tracked the error to this line with the json parsing. but I am baffled because this works sometimes but sometimes it doesn't for the same, identical string.
I checked the values that are passed to the html inputs and it works and doesn't work for the same values.
Here's an example of the json string I am passing:
"[{\"location\":\"8.3353156, 80.3329846\",\"stopover\":true}, {\"location\":\"8.0326424, 80.7446666\",\"stopover\":true}, {\"location\":\"7.9577778, 80.667518\",\"stopover\":true}, {\"location\":\"7.953208, 81.006675\",\"stopover\":true}, {\"location\":\"7.885949, 80.651479\",\"stopover\":true},{\"location\":\"7.2905425, 80.5986581\",\"stopover\":true},{\"location\":\"7.300322, 80.386362\",\"stopover\":true}]"
Here's the structure of the code I use.
$(document).ready(function() {
$.ajax({
url: "aa.php",
type: "POST",
data: {
id: selected_i
},
success: function(result) {
itins = $.parseJSON(result);
$("#waypt_sel").val(JSON.stringify(itins.arr_intin));
}
});
$.ajax({
type: "POST",
contentType: "application/json",
url: "dd.php",
success: function(result) {
locations = $.parseJSON(result);
initializeMap();
}
});
function initializeMap() {
//other code
calculateAndDisplayRoute();
//other code
function calculateAndDisplayRoute() {
//other code
waypts_input = $.parseJSON($("#waypt_sel").val());
waypts_json_input = $.parseJSON(waypts_input);
//other code
}
}
});
And here is the detailed error message I get on firefox developer edition browser.
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of
the JSON data
calculateAndDisplayRoute() map.js:366
initializeMap() map.js:290
.success() map.js:62
m.Callbacks/j() jquery-1.11.3.min.js:2
m.Callbacks/k.fireWith() jquery-1.11.3.min.js:2
x() jquery-1.11.3.min.js:5
.send/b() jquery-1.11.3.min.js:5
Thanks in advance.
"\" is unnecessary when deserialize json string in javascript .
what json tools you used?
you serialize in one tool , and deserialize with other , may get this scene .
The issue was that I was using an asynchronous ajax request to retrieve json data. by the time the data had been retrieved and pasted to the html, the execution of the code that used the html data had happened, and thus gave an error. I used a callback function for the ajax query and this did the job.
function get_det(callback) {//Your asynchronous request.
$.ajax({
url: "aa.php",
type: "POST",
success: function (result) {
alert("1st call");
callback();//invoke when get response
}
});
}
and in the code where this is called:
get_det(secondFunction);//calling with callback function
function secondFunction()//your callback function
{
alert("2nd Call");
}
Alternatively you may also try async: false in the ajax query parameters. But this can cause browser freezing and is not recommended.

getting string from object

I am having a problem with this code, could someone help me out?
<script type="text/javascript">
$(document).ready(function()
{
$obj = $.get('getSesion.php',function(data){ } );
//$dato=JSON.stringify(obj);
//$dato=dojo.toJson(obj);
alert($obj);
if($obj != 'NULL')
{
$('#apDiv7').load('logeado.php');
}else{
$('#apDiv7').load('deslogeado.php');
}
}
);
</script>
The problem is that from $obj I get [object Object]. I searched how to convert it but I had no success.
MORE DETAILS. From data I can get a number (0-infinite) or the string NULL. Depend on what value I get, in apDiv7 I will load login window or a window's user connected.
I tried
var data =$obj.d;
but i get "undefined" string
Console log
http://imageshack.com/a/img46/4004/ufgv.jpg
Solution for this case:
var msg = $.ajax({type: "GET", url: "getSesion.php", async: false}).responseText;
.get is an async call, so you should be doing this logic in the callback:
$.get('getSesion.php',function(data) {
console.log(data);
});
Always use console.log so you can actually expand the complex object. Then simply reference the property names of the data response object.

Jquery returns [Object object] from POST function

i want to get a string from a php file, using a jquery post.
function getString(string) {
return $.ajax({
type : 'POST',
url : 'scripts/getstring.php',
data : { 'string': string }
});
};
in the firebug console i can see that the desired string is found, but if i want to get it with
var blub = getString("test");
alert(blub);
only "object Object" is shown.
just cant get where my mistake is..
That Ajax request that is made to the server is performed asynchronously, so the ajax method actually returns an object representing the request itself, rather than the actual response from the server.
The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of jQuery 1.5 is a superset of the browser's native XMLHttpRequest object.
You could use the success callback instead:
function getString(string) {
return $.ajax({
type : 'POST',
url : 'scripts/getstring.php',
data : { 'string': string }
success: function(result) {
alert(result);
},
});
};
Or if you want to be a bit more flexible, you could take the callback function as a parameter:
function getString(string, callback) {
return $.ajax({
type : 'POST',
url : 'scripts/getstring.php',
data : { 'string': string }
success: callback,
});
};
getString('test', function(result) {
alert(result);
})
You are returning an jQuery jqXHR object.
If you want to deal with the data from the HTTP response, then you need to add a done (or success handler.
blub.done(function (data) {
alert(data);
});
object Object is the expected response, because the data being returned is and object.
If you want to see the resultant object, try:
console.log(blub) instead and view it in the console.
This can then help you determine the correct path to the data you want to retrieve in the object.

JSON Request appended with [object%20Object] in jQuery

I'm trying to fetch a custom JSON feed I have written with jQuery using the getJSON method. For an unknown reason the URL seems to be having cache_gen.php?location=PL4 stripped from the end and replaced with [object%20Object] resulting in a 404 error occurring.
Here's the jQuery I'm using:
var fetchData = function() {
if (Modernizr.localstorage) {
var api_location = "http://weatherapp.dev/cache_gen.php";
var user_location = "PL4";
var date = new Date();
console.log(api_location + '?location=' + user_location);
jQuery.getJSON({
type: "GET",
url: api_location + '?location=' + user_location,
dataType: "json",
success: function(jsonData) {
console.log(jsonData);
}
});
} else {
alert('Your browser is not yet supported. Please upgrade to either Google Chrome or Safari.');
}
}
fetchData();
From the console log I can see the URL string is calculated correctly as: http://weatherapp.dev/cache_gen.php?location=PL4
However the second line in the console is: Failed to load resource: the server responded with a status of 404 (Not Found).
Can anyone point me in the right direction with this?
UPDATE 19/01/2013 23:15
Well, I've just converted so that is fits the docs perfectly using $.ajax. I've also added a fail event and logged all of the data that gets passed to it.
var fetchData = function() {
if (Modernizr.localstorage) {
var api_location = "http://weatherapp.dev/cache_gen.php";
var user_location = "PL4";
var date = new Date();
var url = api_location + '?location=' + user_location;
console.log(url);
jQuery.ajax({
type: "GET",
url: api_location + '?location=' + user_location,
dataType: "json",
success: function(jsonData) {
console.log(jsonData);
},
error: function( jqXHR, textStatus, errorThrown ) {
console.log('textStatus: ' + textStatus );
console.log('errorThrown: ' + errorThrown );
console.log('jqXHR' + jqXHR);
}
});
} else {
alert('Your browser is not yet supported. Please upgrade to either Google Chrome or Safari.');
}
}
fetchData();
After this my console gives me the following information:
http://weatherapp.dev/cache_gen.php?location=PL4
download_api.js:44textStatus: parsererror
download_api.js:45errorThrown: SyntaxError: JSON Parse error: Unable to parse JSON string
download_api.js:46jqXHR[object Object]
I have ensured the headers for the JSON feed are current, and the feed is definitely serving valid JSON (it effectively caches a 3rd party service feed to save costs on the API).
The reason why you see this error:
http://weatherapp.dev/cache_gen.php?location=PL4
download_api.js:44textStatus: parsererror
download_api.js:45errorThrown: SyntaxError: JSON Parse error: Unable to parse JSON string
download_api.js:46jqXHR[object Object]
Is because your JSON is invalid. Even if a response comes back from the server correctly, if your dataType is 'json' and the returned response is not properly formatted JSON, jQuery will execute the error function parameter.
http://jsonlint.com is a really quick and easy way to verify the validity of your JSON string.
I was running into the same issue today. In my case I was assigning a JSON object to a variable named 'location' which is a reserved word in JavaScript under Windows and appearantly is a shorthand for windows.location! So the browser redirected to the current URL with [object%20Object] appended to it. Simple use a variable name other than 'location' if the same thing happens to you. Hope this helps someone.
Check out the actual function usage:
http://api.jquery.com/jQuery.getJSON/
You can't pass on object parameter into $.getJSON like with $.ajax, your code should look like this:
jQuery.getJSON('api_location + '?location=' + user_location)
.done(function() {
//success here
})
.fail(function() {
//fail here
});
To maybe make it a little clearer, $.getJSON is just a "wrapper function" that eventually calls $.ajax with {type:'get',dataType:'JSON'}. You can see this in the link I provided above.

Categories

Resources