简体   繁体   中英

Can't retrieve POST data sent from AJAX, undefined index php

This is my ajax form which works,

$.ajax({
type: "POST",
url: "update_coordinate.php",
data: 
'id=' +$id+
'name=' +$name+
'wname=' +$wname+
'xcor=' +$xcor+
'ycor=' +$ycor+
'xwid=' +$xwid+
'yhei=' +$yhei+
'photo=' +$photo+
'targeturl=' +$targeturl,
success: function(data){
alert(
' id:' +$id+
' name:' +$name+
' wname:' +$wname+
' xcor:' +$xcor+
' ycor:' +$ycor+
' xwid:' +$xwid+
' yhei:' +$yhei+
' photo:' +$photo+
' targeturl:' +$targeturl
);
alert(data);
}
});

the alert shows all of the data, the problem is the php side which doesn't seem to read the value, I'm not sure if I am missing something.

This is interesting: While messing around, I somehow got the entire concatenated string to be entered in the name field with the equals sign included... how could that have happened?

I took out the if(post) argument which is used when submitting an html form to the same page with method post and a submit button. I don't know if that is bad.

I tried both of these

if(isset($_POST['id'])){
 $id = $_POST['id'];
 }else {
 $id = "";
 }

 $name = $_POST['name'];

Getting errors Undefined index: name which the rest are fine because I specify an arbitrary string value of empty

What am I missing?

Using jQuery Post:

$.post( "update_coordinate.php", { 
    'id':$id,
    'name':$name,
    'wname':$wname,
    'xcor':$xcor,
    'ycor':$ycor,
    'xwid':$xwid,
    'yhei':$yhei,
    'photo':$photo,
    'targeturl':$targeturl
}).done(function( data ) {
    alert( "Server Response: " + data );
});

as this will send the POST data correctly, as every time i tried using ajax and having a data string, it seem to always get sent as a GET due to the server thinking it was a url / query string.

Also, by doing the above.. You can then easily send a JS array to PHP or other objects.

what you are missing is how to format JSON. The "+" operator is concatenating everything as one string. JSON is formatted with {propertyname} : {value}

$.ajax({
   type: "POST",
   url: "update_coordinate.php",
   data: {
           'id' : $id,
           'name': $name,
           'wname': $wname,
           'xcor': $xcor,
           'ycor': $ycor,
           'xwid': $xwid,
           'yhei': $yhei,
           'photo': $photo,
           'targeturl': $targeturl
   }, 
   success: function(data){
     alert(
       ' id' +$id+
       ' name:' +$name+
       ' wname:' +$wname+
       ' xcor:' +$xcor+
       ' ycor:' +$ycor+
       ' xwid:' +$xwid+
       ' yhei:' +$yhei+
       ' photo:' +$photo+
       ' targeturl:' +$targeturl
 );
 alert(data);
 }

});

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