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

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!

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.

How to Pass PHP Array to Javascript as JSON Array

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.

Naming PHP object and SQL issue.

In a php file called: loadPosts.php
I am connecting to a database and retrieving a VARCHAR, VARCHAR, TEXT, TEXT, and VARCHAR. Each of them have an undefined length and I am trying to put the data into an object. Here is my php code.
<?php
//Creates an array to keep track of all information being past back to java script
$info = array();
$i = 0;
$j = 0;
//If server sends a post method then execute script
if ($_SERVER["REQUEST_METHOD"] == "POST"){
requestPosts($info);
//Encode the array to be sent to the java script with all the return messages and the state
echo json_encode($info);
}
function requestPosts(&$info){
//Set name of server, username, password, and database to access
$servername = "";
$username = "";
$passwordSQL = '';
$dbname = "";
//Create database connection
$con = new mysqli($servername, $username, $passwordSQL, $dbname);
//Check connection
if ($con->connect_error)
{
die("Connection failed: " . $con->connect_error);
$info["message"] = "failed";
}else{
$info["message"]= "You're Connected!";
}
//Create a query for account name
$sqlQuery = "SELECT * FROM posts;";
//Send query and assign to result
$result = $con->query($sqlQuery);
//If result is set
if($result){
//If result has rows found
if ($result->num_rows > 0)
{
//Loop through result
while($row = $result->fetch_assoc())
{
$info[$i][$j] = $row;
$j += 1;
}
$i += 1;
}
}
}
?>
Here is my javascript for calling and retrieving the data:
$(function(){
$.ajax({
type: 'POST',
url: 'assets/php/loadPosts.php',
success: function (msg) {
//Console log the message
console.log('msg', msg);
//Create an object from the message
var obj = JSON.parse(msg);
console.log('obj', obj);
},
error: function (msg) {
alert('Form Error' + msg);
}
});
});
When I retrieve the data from my java script I get this:
Return Code in Console
I would like to know if it is possible to name the object element in the array that contains all the children objects, as well as having the first object inside the parent object having the name of 0 instead of "".
Thanks in advance for any help or thoughts! I'm sure it's simple and I am just being dumb, but I would love the help! Thanks :)

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);

Javascript and PHP Data Feed Usage

I am trying to grab data from php
This is my function in php
function getEvent($eventId){
$ret = array();
$ret['events'] = array();
try{
$db = new DBConnection();
$db->getConnection();
$sql = "select a.contact_name,a.userid from `contact` a where a.Id='$eventId'";
$handle = mysql_query($sql);
while ($row = mysql_fetch_object($handle)) {
//$ret['events'][] = $row;
$ret['events'][] = array(
$row->contact_name,
$row->userid
);
}
}catch(Exception $e){
$ret['error'] = $e->getMessage();
}
return $ret;
}
So I did the following at my javascript
var eventId = '2';
var DATA_FEED_URL = "datafetcher.php";
var param = [{ "name": "eventId", value: 9}];
$.post(DATA_FEED_URL + "?method=getEvent",
param,
function(data){
if (data.IsSuccess) {
alert(data.Msg);
//CloseModelWindow(null,true);
}
else {
alert("Error occurs.\r\n" + data.Msg);
}
}
,"json");
The problem is that nothing happens when I run it.
I want to able get the return result of my php, and then set
var contactName = Return Result contact name element under the $ret array from the datafeed
var contactId = Return result contact id element under the $ret array from the datafeed
Is there anything that I am doing wrong?
Have you tested your PHP if you get in function getEvent($eventId) at all?
Also double check that you are passing the $_POST['value'] to $eventId
Your javascript are expecting a json back from the PHP, so in your PHP you need to print the return result as a json, are you doing that somewhere?
ex echo json_encode($ret);

Categories

Resources