简体   繁体   中英

Sending Array to php via ajax.

I'm storing an array and sending this via ajax...

var heart = [31,32,33,34,35,36,37,38,39,42,43];
// Sending this data via ajax to php file/ 
 $.ajax({
 type: "POST",
 data:{ 'system': heart }, 
 url: "login-function.php",
 success: function(msg){
 alert('yes');
}
});

I believe its sending correctly because i'm getting a alert saying yes. This is my php file:

$system = $_POST['system'];
echo $system;

Am I storing this into a variable right ? How can i echo this value onto the page?

You have 2 issues. A: you are not using the ajax return value, in your code msg - this contains the output from php, so to display it, add it to the page somehow:

html:

<div id="result"></div>

js:

 var heart = [31,32,33,34,35,36,37,38,39,42,43];
 // Sending this data via ajax to php file/ 
 $.ajax({
     type: "POST",
     data:{ 'system': heart }, 
     url: "login-function.php",
     success: function(msg){
         $('#result').html(msg);
    },
     error: function(jqXHR, textStatus, errorThrown){
         console.log(errorThrown);
    }
});

B: You cant just echo an array, its not a string. to display ist contents you can use a number of php functions, for example var_dump() :

$system = $_POST['system'];
var_dump($system);

you can use print_r( $system ); or use a foreach statement:

foreach ( $system as $itm ) {
    echo $itm . '<br />';
}

edit: echo ing in PHP is only available for strings, intergers etc; not arrays or objects.

$system = $_POST['system'];
print_r($system);

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