Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery get array details

Tags:

json

jquery

php

I'm having trouble getting a response back from a Jquery ajax call...

(It's a script to authenticate a user, and needs to return their name and user ID. My understanding was that I could encode it as JSON and get the data in the format below.

It is returning an error of "undefined" for the alert().

The javascript

$.ajax({
 type: "POST",
 url: "myURL.php",
 data: {username: username, password: password},
 success: function(results) {
  //THIS IS WHERE THE PROBLEM IS
  alert('Hi '+results.name); //Should be "Hi Basil Fawlty"
  }
});

The PHP (myURL.php)

//This comes from a SQL call that returns the following name
json_encode(array(
 'id'=>1,
 'name'=>'Basil Fawlty'
));

Any help or ideas on where I am going wrong would be greatly appreciated!

Thanks.

Solution: The solution was adding a dataType.

like image 265
Matt Avatar asked Jan 18 '26 01:01

Matt


2 Answers

You're missing dataType: "json":

$.ajax({
 type: "POST",
 url: "myURL.php",
 dataType: "json",
 data: {username: username, password: password},
 success: function(results) {
  //THIS IS WHERE THE PROBLEM IS
  alert('Hi '+results.name); //Should be "Hi Basil Fawlty"
  }
});

Another (less verbose) alternative is jQuery.getJSON if you know you are getting JSON.

like image 114
Vivin Paliath Avatar answered Jan 20 '26 18:01

Vivin Paliath


If you are using jQuery < 1.4, you must specify dataType: "json".

As of 1.4, dataType defaults to:

Intelligent Guess (xml, json, script, or html)

But this requires that the response header contains the string "json". So you'll want to send:

header('Content-type: application/json');

This newly added flexibility with dataType allows handlers to respond to multiple returned types.

If the problem continues, you'll want to alert the entire response alert(results); to see what's actually being returned.

Lot of similar answers here. Not sure who started it but whoever did no doubt invaded Poland.

like image 44
webbiedave Avatar answered Jan 20 '26 17:01

webbiedave



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!