简体   繁体   中英

How to retrieve the value sent by a $.ajax function in my php file?

I get the following error on the .php page. Notice: Undefined index: name

$.ajax({
    url: 'test.php',
    type: "GET",
    data: ({name: "James"}),
    success: function(data){
    console.log(data);
    }
 });  

I am trying to get the value sent from the data object in the test.php file as follows:

if(isset($_GET['name'])){
     echo $_GET['name'];   
} else {
    echo "Not working";
}

Try this :

data: {name: "James"},

Instead of

data: ({name: "James"}),

I suspect it's something wrong with the jQuery part. Try to make the data a valid JSON object data: {"name": "James"} (notice how "name" is enclosed in quotes):

$.ajax({
    url: "test.php",
    type: "POST",
    data: {"name": "James"},
    success: function(data){
        console.log(data);
    }
});

Edit: Removed dataType . As Taplar pointed out, this is linked to the returned data.

You can use serialize for accommodate your data

example :

var serializedData = 'name=James';

$.post('test.php', serializedData,
  function (enumData) {
    console.log(enumData);
  }
);

hope this helps you. cheers :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM