0

I have this array:

    $users = array();
// Finally, loop over the results
foreach( $select as $email => $ip )
{
    $users[$email] = $ip;
}

Now i want to pass this array to ajax and print in another script:

$html="<center><a href=\"#\" id=\"check_spam\" onclick=\"$.ajax({type: 'POST', url: 'mcheck.php', data:'users=$users', success: function(data){ $('#results').html(data);}});\">Check users for spam</a></center>";

mcheck.php

echo $_POST['users'];

This code does not work. How can i do this?

2
  • 2
    You can not pass array to ajax you have to convert it to json format and then you can pass Commented Jun 22, 2017 at 13:37
  • yes json_encode - will help you here. Commented Jun 22, 2017 at 13:39

3 Answers 3

2

As Sergiu Costas pointer out, the best way is to JSON encode it and then decode, but you can also try:

$html="<center><a href=\"#\" id=\"check_spam\" onclick=\"$.ajax({type: 'POST', url: 'mcheck.php', data: '" . http_build_query(array('users' => $users)) . "', success: function(data){ $('#results').html(data);}});\">Check users for spam</a></center>";

If your $users array is:

$users = array( array('email' => '[email protected]'), array('email' => '[email protected]')));

then http_build_query('users' => $users) will generate:

users%5B0%5D%5Bemail%5D=a%40email.com&users%5B1%5D%5Bemail%5D=b%40email.com

which is the url-encoded version of:

 users[0][email][email protected]&users[1][email][email protected]

which will be decoded back to array in mcheck.php

Sign up to request clarification or add additional context in comments.

Comments

2

The Best way is to encode array into JSON format.

In PHP:

$users_json = json_encode($users);

// To decode in javascript

var obj = JSON.parse(json_str);

Comments

0

if u want to pass php array to js you can json_encode the array to do that.

$html="<center><a href=\"#\" id=\"check_spam\" onclick=\"$.ajax({type: 'POST', url: 'mcheck.php', data:'users=".json_encode($users)."', success: function(data){ $('#results').html(data);}});\">Check users for spam</a></center>";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.