1

I am sending php array using serialise but the response is different. Here is my attempt

$array = serialize($out);
var_dump(serialize($array));
//string(58) "s:50:"a:2:{s:9:"sidebar-1";i:5;s:12:"footer-insta";i:2;}";"

The way I am sending this value,

echo '<div data-ad = '.$array.' class="ash_loadmore"><span>LOAD MORE</span></div>';

As I am sending the serialised value using ajax, the value that ajax response give me,

string(54) "a:2:{s:9:\"sidebar-1\";i:5;s:12:\"footer-insta\";i:2;}"

I need the exact value as I have unserialise again to make it array. Why there is extra \ and output is different.

2
  • 2
    Why are you serializing it? If you need to make a PHP array available for use in JavaScript, use json_encode to encode it as JSON. Jul 18, 2017 at 0:52
  • @JacobPeattie, Thanks for suggestion I will try that in wordpress to see how it can be done . Jul 19, 2017 at 15:23

3 Answers 3

2

Well it seems @JacobPeattie mentioned to use json, I just echoing that.

  1. First json encode the variable $array = json_encode($out);

  2. Then send this value echo '<div data-ad = '.$array.' class="ash_loadmore"><span>LOAD MORE</span></div>';

  3. To get that echo json_encode($_POST['ad'])

I think that's it.BTW you don't have now that string problem as the output will be like this {"footer-insta":2,"sidebar-1":3} you see it is wrapped by {}

0

Well, this \ is getting added to escape the ". For example you are storing the whole string "sidebar-1". Notice the string contains opening " and also closing ". Now the string is also wrapped with another "", so for separating the opening " and closing " of the stored string it's adding a \ to escape it. This way it makes it hidden form parsing the "" of the stored string as a real quote.

0

The simplest and least problematic solution:

$array = json_encode($out);
var_dump(array); // string "{\"sidebar-1\":5,\"footer-insta\":2}"

In JS you can use:

JSON.parse("{\"sidebar-1\":5,\"footer-insta\":2}")

and you have object with data

Not the answer you're looking for? Browse other questions tagged or ask your own question.