How to Pass PHP Array to Javascript as JSON Array - javascript

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

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}]

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

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.

Related

How to get the key ID value in a JWK response (PHP)

I'm generating a public key on the server side to pass on the client side to render an iframe (hosted by a third party).
I'm getting a whole chunk of data from the JWK response, but I only need the keyID value.
{
"data": "{\"keyId\":\"eyJraWQiOiIzZyIsImFsZyI6IlJTMjU2In0.eyJmbHgiOnsicGF0aCI6Ii9mbGV4L3YxL3Rva2Vucz9mb3JtYXRcdTAwM2RKV0UiLCJkYXRhIjoiOFZ6WnhyUHd2b1dRb1I0QTVTRWNteEFBRUliNlJsT1YzdGU4UUxGdmEwb08wTEliWkhtWmE4Z2ZqT0lSWklmS1FaUElRYmhaZHVlRFNwQzZZZllUanF0cU94d2xtUVlQa1FzZUcrL05WUGlBbUZUdGtUNjlUbXAyb3pEOWJqT0NyVFlQIiwib3JpZ2luIjoiaHR0cHM6Ly90ZXN0ZmxleC5jeWJlcnNvdXJjZS5jb20iLCJqd2siOnsia3R5IjoiUlNBIiwiZSI6IkFRQUIiLCJ1c2UiOiJlbmMiLCJuIjoiaGNLRlU5UllCR0VwY1JyR3FQQ2J1U3BlOFdyeTRRUUNvMUdiRml4ZHdWMUtuN09BMHQtRDdXM2tvUjN6MDc3UndnYnBldTdvbV8xd0ZrRjVRLTBNeVNfdzk3TklmaVk1OVNLb3JqdWhfQmt2NHdJVGVUbm9LN2ZROHJyOTJSOUNKTFp6UFdlUVJPMDVxeWxiLVdVWUJvOU5sa2QwZHl6b2RlbEoxWVRzQ1JzYlRVc0ZRMUxKZHVIWWw0X3kzTF9FbnkwaG1mSFg5cll4U2ozamhmZVpZYVhYa0wtdERCa2k5VF9zXzhzb19RQjNLN29oR2tqSDU1TUQwRkdDNzVpRS1UcmtqNFd0cWNyYjI3S3BNSzdXWm1qSnJUMFE0bzlMMTBURXJvZE1HeEpfTm5IMGdSYmUwTFVSOWhaVnUzMG9tWkdrQVhfQXhUa1VJWktXQzZENkJ3Iiwia2lkIjoiMDd1SlMwT0dpR2pObzF6ejRTbGFpZUIzQkprSWc1bVAifX0sImN0eCI6W3siZGF0YSI6eyJ0YXJnZXRPcmlnaW5zIjpbImh0dHA6Ly9sb2NhbGhvc3Q6ODA4MiJdLCJtZk9yaWdpbiI6Imh0dHBzOi8vdGVzdGZsZXguY3liZXJzb3VyY2UuY29tIn0sInR5cGUiOiJtZi0wLjExLjAifV0sImlzcyI6IkZsZXggQVBJIiwiZXhwIjoxNTgwMTg5NDA2LCJpYXQiOjE1ODAxODg1MDYsImp0aSI6InNYYWNWSm43bkI1a1ZvSnIifQ.Hr-DwfFv-90bBtUWhACXwkhVFefh7fNOV9FS5Epu5fcL7Ji_pE9GHQIhaX5F31VM-EAOz55gG0eYnEu7ZAptR1mq3WgxNx3Af9ngKpbl4ZTb9cUxjGf3DdGJ1-J26aziJx3GcaZREfFyabDWbThyKlGTxSbnGHb7-UcQ_MPmh-znt_691y_gX9Qo8fe6XeJw8-Ir4XwwznjNLa31-EctYfnYUbfOnjR_8rfuFNnulvQecHs1e4zFVVAqm8mqex-umdlPbPUGT8xzYN-G0oLMdj3uMAAeSuyrdAifVXWSXyyyBHU5rIp-8anGWj_9RQrwvOH7MOIerV3Lej1-lEOxTw\",\"der\":null,\"jwk\":null}"
}
I need the keyID value and pass it in the client side on a variable called "captureContext".
This is my client side code but it's returning me all the data above:
var captureContext = <?php echo json_encode($body)?>;
console.log(captureContext);
This is how I'm generating the public key in the server side:
<?php
define ('HMAC_SHA256', 'HmacSHA256');
//Step 0. Set Secret Key a
define ('SHARED_SECRET_KEY', '--insert shared secret--');
define ('KEY_ID','--insert key ID--');
define ('MERCHANT_ID','--insert merchant ID--');
define('TARGET_ORIGIN',"http://localhost:8082");
define ('SECURE_HTTPS','https://');
define('HOST','apitest.cybersource.com');
define('DESTINATION_RESOURCE','flex/v1/keys?format=JWT');
define('SHA256','sha256');
define('ENCRYPTION_TYPE','RsaOaep256');
function loggingHelper( $response, $curl, $testInfo, $requestBody ) {
printf("%s\n",$testInfo);
if(!$response) {
printf ('Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl));
} else {
if (empty($requestBody) == false && $requestBody != '') {
$json = json_decode($requestBody);
$json = json_encode($json, JSON_PRETTY_PRINT);
printf("Request Body : %s\n", $json);
}
$header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);
printf ("Response Status: %s\n",curl_getinfo($curl, CURLINFO_HTTP_CODE));
printf($header);
if (empty($body) == false && $body != '') {
$json = json_decode($body);
$json = json_encode($json, JSON_PRETTY_PRINT);
printf("Response Body : %s\n", $json);
}
}
}
function getSignature($params){
return signData(buildDataStringToSign($params), SHARED_SECRET_KEY);
}
function getHeadersString($params) {
$headerStringArray = array();
foreach($params as $field => $value){
$headerStringArray[] = $field;
}
return implode(" ",$headerStringArray);
}
function buildDataStringToSign($params) {
$dataStringArray = array();
foreach ($params as $field => $value) {
$dataStringArray[] = $field . ": " . $value;
}
return implode("\n",$dataStringArray);
}
function jdebug($variable,$text){
echo "<br>=====".$text."=====<br>";
var_dump($variable);
echo "<br>=====".$text."=====<br>";
}
function signData($data, $secretKey) {
//Remember, the key is provided in a base64 format, so it must be decoded before using in the hmac
return base64_encode(hash_hmac(SHA256, $data, base64_decode($secretKey),true));
}
function commaSeparate ($dataToSign) {
return implode(",",$dataToSign);
}
function getServerTime() {
return gmdate("D, d M Y H:i:s \G\M\T");
}
function getDigestHeader($params) {
return "SHA-256=".base64_encode(hash(SHA256,$params,true));
}
function getDigestBody() {
$digestBody = Array("encryptionType" => ENCRYPTION_TYPE,
"targetOrigin" => TARGET_ORIGIN );
//return "{\n \"encryptionType\": \"".ENCRYPTION_TYPE."\",\n \"targetOrigin\": \"".TARGET_ORIGIN."\"\n}";
return json_encode($digestBody);
}
$digestBody = getDigestBody();
$digestHash = getDigestHeader($digestBody);
$serverTime = getServerTime();
$signedHeaders['host'] = HOST;
$signedHeaders['date'] = $serverTime;
$signedHeaders['(request-target)'] = 'post /'.DESTINATION_RESOURCE;
$signedHeaders['digest'] = $digestHash;
$signedHeaders['v-c-merchant-id'] = MERCHANT_ID;
$signature = getSignature($signedHeaders);
$signatureHeader = "";
$signatureHeader.="keyid=\"".KEY_ID."\"".", ";
$signatureHeader.="algorithm=\"".HMAC_SHA256."\"".", ";
$signatureHeader.="headers=\"".getHeadersString($signedHeaders)."\"".", ";
$signatureHeader.="signature=\"".$signature."\"";
$curl = curl_init ();
$headers = array("host: ".$signedHeaders['host'],
"date: ".$signedHeaders['date'],
"digest: ".$signedHeaders['digest'],
"signature: ".$signatureHeader,
"Content-Type: application/json; charset=utf-8",
"v-c-merchant-id: ".$signedHeaders['v-c-merchant-id']);
$absUrl = SECURE_HTTPS.HOST."/".DESTINATION_RESOURCE;
$opts = array ();
$opts [CURLOPT_POST] = 1;
$opts [CURLOPT_POSTFIELDS] = $digestBody;
$opts [CURLOPT_PROTOCOLS] = CURLPROTO_HTTPS;
$opts [CURLOPT_SSLVERSION] = CURL_SSLVERSION_TLSv1_2;
$opts [CURLOPT_URL] = $absUrl;
$opts [CURLOPT_RETURNTRANSFER] = true;
$opts [CURLOPT_CONNECTTIMEOUT] = 50;
$opts [CURLOPT_TIMEOUT] = 100;
$opts [CURLOPT_HTTPHEADER] = $headers;
$opts [CURLOPT_HEADER] = 1;
curl_setopt_array ( $curl, $opts );
$response = curl_exec ( $curl );
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);
$response = json_decode($body);
$jwk = $response->jwk;
curl_close ( $curl );
?>
Hope you can help me out! Thank you in advance!
I have tried my best to understand the code you pasted, but it is hard to say how did the response is being generated/responsed from server, because from my scanning of the code, there was no indication if first part code and the second are both on the server side, or first part is a test code on the client side (that first part is clearly a code mixture with php, such as js+php).
So there are two possibilities:
both code are on server side
only second code is on server side
1: if the first part of the code is on the server side and is being requested from client side, and you want to split is result and send only the key back, all you need to do is:
// if $body is an array in php
var captureContext = <?php echo $body['data']['keyId'] ?>;
// if $body is an object in php
var captureContext = <?php echo $body->data->keyId ?>;
2: if the first part should be client side, which mean the somewhere in the second part responsed the data back to the client request (normally with an echo), then you need to find the response data carrier (e.g. $response in the second part) and do:
# if $response is the final response data carrier/variable
echo $response->data->keyId;
if the first part of the code is what the client side should be getting and your asking how to split the key from the whole response data:
var captureContext = <?php echo json_encode($body)?>;
var resp = JSON.parse(captureContext);
var keyID = resp.data.keyId;
console.log(keyID);
if this still gives you an error of undefined to keyId, try:
var captureContext = <?php echo json_encode($body)?>;
var resp = JSON.parse(captureContext);
var respData = JSON.parse(resp.data);
var keyID = respData.keyId;
console.log(keyID);
the reason of such error is because I noticed that your post of JWK from console.log() shows a data and keyId in defferent symbols, " and \", and the whole data value is under a String format, so you might need to translate twice for another inner JSON structure.
From my guess the first code and the second are sharing variable names, and if $body are the same variable, then split keyId from a JSON format is a very easy process.
I tried something and i think i got it:
$body = '{ "data": "{\"keyId\":\"eyJraWQiOiIzZyIsImFsZyI6IlJTMjU2In0.eyJmbHgiOnsicGF0aCI6Ii9mbGV4L3YxL3Rva2Vucz9mb3JtYXRcdTAwM2RKV0UiLCJkYXRhIjoiOFZ6WnhyUHd2b1dRb1I0QTVTRWNteEFBRUliNlJsT1YzdGU4UUxGdmEwb08wTEliWkhtWmE4Z2ZqT0lSWklmS1FaUElRYmhaZHVlRFNwQzZZZllUanF0cU94d2xtUVlQa1FzZUcrL05WUGlBbUZUdGtUNjlUbXAyb3pEOWJqT0NyVFlQIiwib3JpZ2luIjoiaHR0cHM6Ly90ZXN0ZmxleC5jeWJlcnNvdXJjZS5jb20iLCJqd2siOnsia3R5IjoiUlNBIiwiZSI6IkFRQUIiLCJ1c2UiOiJlbmMiLCJuIjoiaGNLRlU5UllCR0VwY1JyR3FQQ2J1U3BlOFdyeTRRUUNvMUdiRml4ZHdWMUtuN09BMHQtRDdXM2tvUjN6MDc3UndnYnBldTdvbV8xd0ZrRjVRLTBNeVNfdzk3TklmaVk1OVNLb3JqdWhfQmt2NHdJVGVUbm9LN2ZROHJyOTJSOUNKTFp6UFdlUVJPMDVxeWxiLVdVWUJvOU5sa2QwZHl6b2RlbEoxWVRzQ1JzYlRVc0ZRMUxKZHVIWWw0X3kzTF9FbnkwaG1mSFg5cll4U2ozamhmZVpZYVhYa0wtdERCa2k5VF9zXzhzb19RQjNLN29oR2tqSDU1TUQwRkdDNzVpRS1UcmtqNFd0cWNyYjI3S3BNSzdXWm1qSnJUMFE0bzlMMTBURXJvZE1HeEpfTm5IMGdSYmUwTFVSOWhaVnUzMG9tWkdrQVhfQXhUa1VJWktXQzZENkJ3Iiwia2lkIjoiMDd1SlMwT0dpR2pObzF6ejRTbGFpZUIzQkprSWc1bVAifX0sImN0eCI6W3siZGF0YSI6eyJ0YXJnZXRPcmlnaW5zIjpbImh0dHA6Ly9sb2NhbGhvc3Q6ODA4MiJdLCJtZk9yaWdpbiI6Imh0dHBzOi8vdGVzdGZsZXguY3liZXJzb3VyY2UuY29tIn0sInR5cGUiOiJtZi0wLjExLjAifV0sImlzcyI6IkZsZXggQVBJIiwiZXhwIjoxNTgwMTg5NDA2LCJpYXQiOjE1ODAxODg1MDYsImp0aSI6InNYYWNWSm43bkI1a1ZvSnIifQ.Hr-DwfFv-90bBtUWhACXwkhVFefh7fNOV9FS5Epu5fcL7Ji_pE9GHQIhaX5F31VM-EAOz55gG0eYnEu7ZAptR1mq3WgxNx3Af9ngKpbl4ZTb9cUxjGf3DdGJ1-J26aziJx3GcaZREfFyabDWbThyKlGTxSbnGHb7-UcQ_MPmh-znt_691y_gX9Qo8fe6XeJw8-Ir4XwwznjNLa31-EctYfnYUbfOnjR_8rfuFNnulvQecHs1e4zFVVAqm8mqex-umdlPbPUGT8xzYN-G0oLMdj3uMAAeSuyrdAifVXWSXyyyBHU5rIp-8anGWj_9RQrwvOH7MOIerV3Lej1-lEOxTw\",\"der\":null,\"jwk\":null}" }';
$body = json_decode($body, true);
$body = json_decode($body['data'], true);
$keyId = $body['keyId'];
And since you tagged PHP in it this is my server side answer.
EDIT:
You have to make your $body variable a string. Put quotes around it. Tested and confirmed, this works.

Send multiple AJAX calls using JavaScript in a single request

I have a page on my website that is fetching flight details from https://hotelspro.com
After entering the flight details, I am getting around 400 different records. The problem is that I have to loop in each record, and send individual API requests to get the hotel info.
I can only use PHP or JavaScript.
Using PHP, its taking like forever. I have tried several solutions:
PHP - Solution 1: Using curl_exec()
$count = xxx; //Where xxx is the number of hotels
for ($i = 0; $i < $count; $i++) {
$hotelCode = $json["results"][$i]["hotel_code"];
$url = "http://cosmos.metglobal.tech/api/static/v1/hotels/" . $hotelCode . "/" ;
$username = 'xxx';
$password = 'xxx';
$auth = base64_encode("$username:$password");
$curl = curl_init();
$data = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"authorization: Basic $auth",
"cache-control: no-cache",
'Content-Length: 0'
),
);
curl_setopt_array($curl, $data);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
$json = json_decode($response, true);
}
PHP - Solution 2: Using curl_multi_exec()
The below code is copied from an answer on Stack Overflow
$urls = array() ;
for ($i = 0; $i < $count; $i++) {
$urls[] = "http://cosmos.metglobal.tech/api/static/v1/hotels/" . $json["results"][$i]["hotel_code"] . "/" ;
}
/* ********** Start Multi Threading ********** */
$active = 0 ;
// cURL multi-handle
$mh = curl_multi_init();
// This will hold cURLS requests for each file
$requests = array();
$options = array(
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_AUTOREFERER => true,
CURLOPT_HTTPHEADER => array("Content-Type: application/json"),
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERPWD => "xxx:xxx"
);
foreach ($urls as $key => $url) {
// Add initialized cURL object to array
$requests[$key] = curl_init($url);
// Set cURL object options
curl_setopt_array($requests[$key], $options);
// Add cURL object to multi-handle
curl_multi_add_handle($mh, $requests[$key]);
$active++;
}
// Do while all request have been completed
do {
curl_multi_exec($mh, $active);
} while ($active > 0);
// Collect all data here and clean up
$j = 0 ;
foreach ($requests as $key => $request) {
$result = curl_multi_getcontent($request); // Use this if you're not downloading into file, also remove CURLOPT_FILE option and fstreams array
curl_multi_remove_handle($mh, $request); //assuming we're being responsible about our resource management
curl_close($request); //being responsible again. THIS MUST GO AFTER curl_multi_getcontent();
$json["results"][$j]["hotel_details"] = json_decode($result, true) ;
$j++ ;
}
curl_multi_close($mh);
/* ********** End Multi Threading ********** */
Both PHP Solutions take more that 1 minute to loop through all the records. So I am trying now to send the requests using JavaScript Synchronous Requests.
JavaScript - Solution 1:
for (var i = 0; i < maxCount; i++) {
var thisHotel = extJson.hotels.results[i] ;
var hotelCode = thisHotel.hotel_code;
$.get("/travel/hotel_pro_details/" + thisHotel.hotel_code, function (json) { // /travel/hotel_pro_details/ is a function on my website that calls HotelsPro API
//Code Handling Here
}
}
The above JavaScript Solution is also taking a lot of time, but the positive thing in it is that I can append the results 1 after the other after being fetched from the API.
But I am looking for a better solution to reduce the load time.
Since I am looping through the records in JavaScript, I am not able to send all the records at once and wait for the results.
So my question is:
Is there a way using JavaScript, where I can send multiple records in a single AJAX call, and then handle all the replies one by one ?
Thank You...
If you are prepared to use an external library, I guess you could consider rxjs and its Observable pattern, with this you can use their forkJoin method to send all your $get requests simultaneously:
Rx.Observable.forkJoin(array)
.subscribe(function(data) {
/* data for all requests available here */
}
Demo:
$(document).ready(function() {
// use your for loop to push() your requests into an array
var array = [
$.get('https://api.chucknorris.io/jokes/random'),
$.get('https://api.chucknorris.io/jokes/random'),
$.get('https://api.chucknorris.io/jokes/random'),
$.get('https://api.chucknorris.io/jokes/random')
];
// make all the http request at the same time
Rx.Observable.forkJoin(array)
.subscribe(function(data) {
// Handle the response for each request individually
$('body').append(data[0].value + '<br><hr>');
$('body').append(data[1].value + '<br><hr>');
$('body').append(data[2].value + '<br><hr>');
$('body').append(data[3].value + '<br>');
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.0.7/rx.all.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Rewrite a JSON array in PHP so that jQuery can read it?

I'm trying to create a JSON array in PHP that jQuery can use and access but for some reason It doesn't work. I get no error messages on the client side nor in the server logs and if I access enc.php directly, it does work, but I'm not sure if the output is correct (the array format).
What I want:
I would like to access the data with jQuery using data[i][0] for the ID ([i] because it's in a loop), and data[i][1] for the message and so on.
Maybe I'm trying to do this the wrong way, if so please help me by pointing me in the right direction or provide an example.
My code:
The current PHP code:
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$fetchedid = $row['id'];
$fetchedkey = $row['chat_key'];
$fetchednonce = $row['chat_nonce'];
$fetcheduser = $row['chat_user'];
$fetchedmsg = $row['chat_msg'];
$plainmsg = \Sodium\crypto_secretbox_open($fetchedmsg, $fetchednonce, $fetchedkey);
$out = array('id' => $fetchedid, 'msg' => $plainmsg, 'user' => $fetcheduser);
header('Content-Type: application/json');
ob_end_clean();
echo json_encode($out);
}
Result:
{"id":297,"msg":"test message","user":"john"}
My jQuery (Ajax) code:
$.ajax({
type: "GET",
url: "enc.php",
dataType: "json",
success: function(data) {
console.log('Update success called');
if (data == 2) {
// No messages to fetch
} else if (data == 3) {
// Cookie Tampering detected
} else if (data == 5) {
$("#chat").remove();
alert("Den här chatten är stängd (tiden har gått ut).");
window.location.href = "/?logout=safe";
}
else {
for (i = 0; i < data.length; ++i) {
var mid = data[i][0];
$.cookie("cmid", mid);
var from = data[i][1];
var msg = data[i][2];
$("#chat").append('<div class="left spotmsg"><div class="chat-avatar pull-left"><img src="/img/them.png" alt="avatar" width="48" height="48"></div><div class="message"><div class="arrow-left"></div><p><strong>#'+from+'</strong></p><p class="txt">'+msg+'</p></div></div>');
}
$('textarea').focus();
$(".chat_area").animate({ scrollTop: $(".chat_area")[0].scrollHeight}, 1000);
}
}
});
You can access object using . notation. To access values use key. for example to access id use data.id. If you have object you can't loop using length.
var mid = data.id; //specify key to access id
$.cookie("cmid", mid);
var from = data.user;
var msg = data.msg;
$("#chat").append('<div class="left spotmsg"><div class="chat-avatar pull-left"><img src="/img/them.png" alt="avatar" width="48" height="48"></div><div class="message"><div class="arrow-left"></div><p><strong>#'+from+'</strong></p><p class="txt">'+msg+'</p></div></div>');
The issue is you are outputting individual JSON strings in your while loop which is not correct because the combined output is invalid JSON. The solution is to build an array and then output the array at the end.
$arr = array();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$fetchedid = $row['id'];
$fetchedkey = $row['chat_key'];
$fetchednonce = $row['chat_nonce'];
$fetcheduser = $row['chat_user'];
$fetchedmsg = $row['chat_msg'];
$plainmsg = \Sodium\crypto_secretbox_open($fetchedmsg, $fetchednonce, $fetchedkey);
$out = array('id' => $fetchedid, 'msg' => $plainmsg, 'user' => $fetcheduser);
$arr[] = $out;
}
header('Content-Type: application/json');
ob_end_clean();
echo json_encode($arr); // encode the final array
Now, your output can contain multiple chat messages and is valid JSON, such as:
[{"id":297,"msg":"test message","user":"john"}, {"id":300,"msg2":"test2 message","user":"john"}]
In the JavaScript, refer to the property names instead of [0], [1] etc:
var mid = data[i].id;
$.cookie("cmid", mid);
var from = data[i].user;
var msg = data[i].message;
the problem stems from the fact that your result is not the json for an array of objects but a simple object, so the line
for (i = 0; i < data.length; ++i) {
never iterates as data does not have a length. you want your result to look like
Result :
[
{"id":297,"msg":"test message","user":"john"}
]
that way it will also hold more than one john ;)
suggestion
so I believe your php should be :
$result = $stmt->get_result();
$out = array();
while ($row = $result->fetch_assoc()) {
//... your code doesn't change here
$plainmsg = \Sodium\crypto_secretbox_open($fetchedmsg, $fetchednonce, $fetchedkey);
//here we append to $out
$out[] = array('id' => $fetchedid, 'msg' => $plainmsg, 'user' => $fetcheduser);
header('Content-Type: application/json');
ob_end_clean();
//echo json_encode($out);// not yet...
}
echo json_encode($out);//but now!

Unexpected end of JSON input

I'm having a little trouble figuring out how to fix this error I'm getting. My code is as follows.
It all starts with a AJAX request whenever the user moves their mouse on the webpage.
$('body').mouseover(function() {
$.ajax({
url: '/core/home.php',
data: {action: 'refresh'},
type: 'post',
Next, the PHP file (home.php) executes a couple methods to get all the needed data and sends it back to AJAX Request.
require_once 'init.php';
if(isset($_POST['action']) && !empty($_POST['action'])) {
// Home Class
$h = new Home();
// Method to count all "vacs"
$h->getVacs('id');
$vacs = $h->count();
// Method to count all "users"
$h->getUsers('id');
$users = $h->count();
// Create array to store all data
$arr = array();
$arr[] = $vacs;
$arr[] = $users;
// Use JSON to send the array back
json_encode($arr);
return $arr;
}
Once the AJAX Request receives a success, the following executes
success: function(output) {
obj = JSON.parse(output);
// Separate the parts of the JSON string
vacs = obj[0];
users = obj[1];
// Show the result at the correct position on the webpage
$('#vac_num').html(vacs);
if(vacs == 1) $('#vac_txt').html('is'); else $('#vac_txt').html('zijn');
$('#users_num').html(users);
if(users == 1) $('#users_txt').html('is'); else $('#users_txt').html('zijn');
}
});
});
Unfortunately this code results into an error: Unexpected end of JSON input.
Any help is much appreciated.
Rather than returning variable you need to echo it
require_once 'init.php';
if(isset($_POST['action']) && !empty($_POST['action'])) {
// Home Class
$h = new Home();
// Method to count all "vacs"
$h->getVacs('id');
$vacs = $h->count();
// Method to count all "users"
$h->getUsers('id');
$users = $h->count();
// Create array to store all data
$arr = array();
$arr[] = $vacs;
$arr[] = $users;
// Use JSON to send the array back
echo json_encode($arr);
}

JSON Send empty array

When trying to send an array, and I know that the array contains data because I checked with var_dump, the json_encode does not send any data.
This is my code:
for($i=0;$i<count($dados_atividades)-1;$i++)
{
$arr[$i+1]['Descricao'] = $dados_atividades[$i]['Descricao'];
$arr[$i+1]['DataInicioPrevista'] = $dados_atividades[$i]['DataInicioPrevista'];
$arr[$i+1]['DataConclusaoPrevista'] = $dados_atividades[$i]['DataConclusaoPrevista'];
}
if(count($arr)>0) {
echo json_encode($arr);
}else{
$arr = array();
$arr[0]['Descricao'] = 'N/A';
echo json_encode($arr);
}
As you can see in the picture, the response does not contain any php echo
and this is my code with var_dump:
for($i=0;$i<count($dados_atividades)-1;$i++)
{
$arr[$i+1]['Descricao'] = $dados_atividades[$i]['Descricao'];
$arr[$i+1]['DataInicioPrevista'] = $dados_atividades[$i]['DataInicioPrevista'];
$arr[$i+1]['DataConclusaoPrevista'] = $dados_atividades[$i]['DataConclusaoPrevista'];
}
if(count($arr)>0) {
var_dump($arr);
echo json_encode($arr);
}else{
$arr = array();
$arr[0]['Descricao'] = 'N/A';
echo json_encode($arr);
}
and as you can see in the picture, the array contains data:
What can I do to fix this?
To expand upon the previous answer you need to encode the array data to UTF-8
function utf8_converter($array)
{
array_walk_recursive($array, function(&$item, $key){
if(!mb_detect_encoding($item, 'utf-8', true)){
$item = utf8_encode($item);
}
});
return $array;
}
Instead of echoing out the json each time round the loop, build the array in the loop and then echo the json once it has completed.
The browser is expecting to see one reply to the AJAX call and not multiple replies.
for($i=0;$i<count($dados_atividades)-1;$i++)
{
$arr[$i+1]['Descricao'] = $dados_atividades[$i]['Descricao'];
$arr[$i+1]['DataInicioPrevista'] = $dados_atividades[$i]['DataInicioPrevista'];
$arr[$i+1]['DataConclusaoPrevista'] = $dados_atividades[$i]['DataConclusaoPrevista'];
}
}
if(count($arr) == 0) {
$arr = array();
$arr[]['Descricao'] = 'N/A';
}
$json_string = json_encode($arr,JSON_UNESCAPED_UNICODE);
if ( json_last_error() > 0 ) {
file_put_contents('json_debug.txt', json_last_error_msg() );
} else {
echo $json_string;
}
exit;
It sounds like you are getting a Malformed UTF-8 characters, possibly incorrectly encoded error, so change this line like so
$json_string = json_encode($arr,JSON_UNESCAPED_UNICODE);

Categories

Resources