Currently I am doing the POST Operation to PHP file from the Javascript to perform the operation in PHP and get the response, But in the php file I am having the Array and I wanted to receive it to JavaScript as JSON Array How Can I do that

Java Script

$scope.details = function() {
  $http({
    method: 'POST',
    url: 'myjson.json'
  }).then(function(response) 
  })

PHP Code

 <?php

header('Content-Type: application/json');
// index.php
// Run the parallel get and print the total time
$s = microtime(true);
// Define the URLs
$urls = array(
  "url1",
  "url2",
  "url3"
);
$pg = new ParallelGet($urls);
//print "<br />total time: ".round(microtime(true) - $s, 4)." seconds";

// Class to run parallel GET requests and return the transfer
class ParallelGet
{
  function __construct($urls)
  {
    // Create get requests for each URL
    $mh = curl_multi_init();
    $headers = array(
    'authorization: Basic xyz',
    'cache-control' => 'no-cache',
    'Accept:application/json'
  );
    foreach($urls as $i => $url)
    {
      $ch[$i] = curl_init($url);
      curl_setopt($ch[$i], CURLOPT_SSL_VERIFYHOST, 0);
      curl_setopt($ch[$i], CURLOPT_SSL_VERIFYPEER, 0);
      curl_setopt($ch[$i], CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch[$i], CURLOPT_HTTPHEADER, $headers);
      curl_multi_add_handle($mh, $ch[$i]);
    }

    // Start performing the request
    do {
        $execReturnValue = curl_multi_exec($mh, $runningHandles);
    } while ($execReturnValue == CURLM_CALL_MULTI_PERFORM);
    // Loop and continue processing the request
    while ($runningHandles && $execReturnValue == CURLM_OK) {
      // Wait forever for network
      $numberReady = curl_multi_select($mh);
      if ($numberReady != -1) {
        // Pull in any new data, or at least handle timeouts
        do {
          $execReturnValue = curl_multi_exec($mh, $runningHandles);
        } while ($execReturnValue == CURLM_CALL_MULTI_PERFORM);
      }
    }

    // Check for any errors
    if ($execReturnValue != CURLM_OK) {
      trigger_error("Curl multi read error $execReturnValue\n", E_USER_WARNING);
    }

    // Extract the content
    foreach($urls as $i => $url)
    {
      // Check for errors
      $curlError = curl_error($ch[$i]);
      if($curlError == "") {
        $res[$i] = curl_multi_getcontent($ch[$i]);
        //$finalResponse[] = $res[$i]->load();
      } else {
        print "Curl error on handle $i: $curlError\n";
      }
      // Remove and close the handle
      curl_multi_remove_handle($mh, $ch[$i]);
      curl_close($ch[$i]);

    }
    // Clean up the curl_multi handle
    curl_multi_close($mh);
      //print_r($res);
    $responseArray = $res;
    // Print the response data

  $responseMSO = json_encode($res);
//print_r(utf8_encode(json_encode($res)));
  //echo $finalResponse[1];
  //echo $responseMSO;
  }

}
?>

Now I want to send these to Javascript as JSONArray

I have seen the suggestion to use json_encode in PHP but when I use that I am getting response as utf-encoded.

Any one please help here

I have referred all the below but didn't help much

Link 1

Link 2

  • "I am getting response as utf-encoded" and why is that a problem? Are you using some other type of encoding? – Patrick Evans Sep 3 '17 at 17:52
  • 1
    It's just echo json_encode($myarray) in your PHP – adeneo Sep 3 '17 at 17:53
  • can you show us the code through which you are getting this $myarray – Alive to Die Sep 3 '17 at 17:56
  • Hi Batman. your json format was wrong. Please copy and paste json data into this url to check your json data jsonformatter.curiousconcept.com – Krishna Jonnalagadda Sep 3 '17 at 17:57
  • I have made my json very simplied to make it easy. I will put the way its showing when I am using json_encode – Ron Sep 3 '17 at 17:57
up vote 2 down vote accepted

Try this:

<?php 

$myarray = array('{ "name":"中", "age":30, "car":null }','{ "name":"Mike", "age":32, "car":null }');
foreach ($myarray as $array) {
    $arrays[] = json_decode($array);
}

echo json_encode($arrays, JSON_UNESCAPED_UNICODE);
echo '<br>';
echo json_encode($arrays);

?>

As you can see the first sample has unescaped unicode

OUTPUT:

[{"name":"中","age":30,"car":null},{"name":"Mike","age":32,"car":null}] [{"name":"\u4e2d","age":30,"car":null},{"name":"Mike","age":32,"car":null}]

  • Okay Micheal let me try and update you thanks..I am issue with server now will test and update back once it is up.. – Ron Sep 3 '17 at 18:20
  • I have tried this but , In the JS Console I am getting proper response {"status":{"1":{"id":1,"color":"#75B000","description":"Test was executed and passed successfully.","name":"PASS"} But When Just run the standalone PHP page I am getting ["{\"status\":{\"1\":{\"id\":1,\"color\":\"#75B000\",\"description\":\"Test was executed and passed successfully.\",\"name\":\"PASS\"}, – Ron Sep 4 '17 at 1:34
  • 1
    Seems like your curl_multi_getcontent($ch[$i]) is already in json format. Convert that to array first to avoid double encoding phpwin.org/s/J2LabK – Michael Eugene Yuen Sep 4 '17 at 2:43
  • Perfect thanks for really making understand with this example :) – Ron Sep 4 '17 at 17:39

Now I want to send these to Javascript as JSONArray like below

[{ "name":"John", "age":30, "car":null },{ "name":"Mike", "age":32, "car":null }]

OK so set up php array first:

$myarray = array(
        array(
            'name' => 'John',
            'age'  => 30,
            'car'  => null
        ),
        array(
            'name' => 'Mike',
            'age'  => 32,
            'car'  => null
        )
);

then json encode it in php

echo  json_encode($myarray);

Result:[{"name":"John","age":30,"car":null},{"name":"Mike","age":32,"car":null}]

For more details on proper way to send a json response from php using json take a look at this: Returning JSON from a PHP Script

  • ["{\"status\":{\"1\":{\"id\":1,\"color\":\"#75B000\",\"descr‌​iption\":\"Test was executed and passed successfully.\" I am getting this for each I am getting \ symbol not sure why. Where As I should be getting only ["{"status":{"1":{"id":1,"color":"#75B000","descr‌iption":"T‌​est was executed and passed successfully." – Ron Sep 3 '17 at 18:16
  • I have this problem with json_encode – Ron Sep 3 '17 at 18:17
  • 1
    in json_encode pass in a second param json_encode($myarray, JSON_UNESCAPED_SLASHES) – Robert Rocha Sep 3 '17 at 18:20
  • I have tried this but , In the JS Console I am getting proper response {"status":{"1":{"id":1,"color":"#75B000","description":"Test was executed and passed successfully.","name":"PASS"} But When Just run the standalone PHP page I am getting ["{\"status\":{\"1\":{\"id\":1,\"color\":\"#75B000\",\"descr‌​iption\":\"Test was executed and passed successfully.\",\"name\":\"PASS\"}, – Ron Sep 4 '17 at 1:34
  • create a phpfiddle to see what you are doing – Robert Rocha Sep 4 '17 at 1:46

If you wish to convert an array of objects in PHP and have it JSON-encoded so that JavaScript can use the result, here's one way to accomplish that feat:

<?php


$o = new stdClass;
$o->name = "John";
$o->age = 30;
$o->car =null;

$o2 = new stdClass;
$o2->name = "Mike";
$o2->age = 32;
$o2->car =null;

$myarray = [$o, $o2];

var_dump(json_encode($myarray));

// result:
 "[{"name":"John","age":30,"car":null},{"name":"Mike","age":32,"car":null}]"

see example here.

For the json-encoded PHP array of objects to be useful for JavaScript it needs to be enclosed in single quotes and then parsed with JSON, as follows:

<script language="JavaScript">
var obj = JSON.parse('<?php echo json_encode($myarray) ?>');
console.log(obj[0].name + "\t" + obj[1].name); // John   Mike
</script>

See useful resource here and this discussion.

  • ["{\"status\":{\"1\":{\"id\":1,\"color\":\"#75B000\",\"descr‌​iption\":\"Test was executed and passed successfully.\" I am getting this for each I am getting \ symbol not sure why. Where As I should be getting only ["{"status":{"1":{"id":1,"color":"#75B000","descr‌iption":"T‌​est was executed and passed successfully." – Ron Sep 3 '17 at 18:16
  • I am having this problem when I use json_encode – Ron Sep 3 '17 at 18:16
  • @Batman please take a look at my updated example code with respect to how to use the json-encoded PHP array of objects in JavaScript; this should now work for you. – slevy1 Sep 3 '17 at 19:08

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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