Jquery get array data

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

(This is a script to authenticate the user, and he needs to return his name and user ID. I realized that I can encode it as JSON and receive data in the format below.

It returns an "undefined" error for warning () .

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

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'm going wrong would be greatly appreciated!

Thank.

Solution: The solution added a data type.

+3
source share
5 answers

You are 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) option jQuery.getJSONis if you know you get JSON.

+4

jQuery < 1.4, dataType: "json".

1.4, dataType :

(xml, json, script, html)

, "json". :

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

dataType .

, alert(results);, , .

. , , , , , .

+3

dataType JSON, , :

$.ajax({
 type: "POST",
 url: "myURL.php",
 dataType: "json",
 data: {username: username, password: password},
 success: function(results) {
  alert('Hi '+results.name);
 }
});

dataType .

:

$.getJSON( "myURL.php", {username: username, password: password}, 
  function(results) {
    alert('Hi '+results.name);
});
+1

I assume you expect JSON, but you get a string.

+1
source

You either need to specify the data type in the request as follows:

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

or you can set the content type from php using

header( "Content-Type: application/json" );
+1
source

Source: https://habr.com/ru/post/1742869/


All Articles