Send multiple AJAX calls using JavaScript in a single request - javascript

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>

Related

pass global variable into ajax function, post to php, save to database

I have a global variable that I want to pass into Ajax. Ajax is very new to me and I've done some research and testing but I am stuck. I don't know if the variable is being passed into the Ajax function for my first question.
I'm not really interested in Json, however I did also make an attempt with that and it's not correct either.
I am not looking to get a response from the php back to the page, the page is updating using the existing js and html.
My second dilemma is that my php file is being activated when it should, however it's posting 0 into the database field. Another problem here too is that it's updating all users money to this same 0 entry so some how it's isset is not set correctly yet. I believe my bindValue is coded correctly, I am really unsure if I need to break down the POST to the php page and if so if I have to use the value, how would I do that? Also when I add WHERE userid = userid to UPDATE the game stalls completely.
Any help even a small fix would be greatly appreciated.
Here are the files. Thank you in advance for helping me get my head around Ajax.
game.js
money = 2000;
function updateMoney() {
if ( pot <= 0 ){
if ( money <= 0 ){
document.getElementById("aaa").innerHTML = "Lost? Here's A Loan !!!";
money = 1000 ;}
}
document.getElementById("money").innerHTML = money;
}
function enterWager(){ // doMath function inside here
var x=parseInt(document.getElementById('textbox').value,10); // Displays the textbox for placing a
wager
if (money <= 0) {
x = 0 ; }
document.getElementById("bet").innerHTML = parseInt(x,10);
if(isNaN(x)||x < 1 || x > 250)
{
document.getElementById("aaa").innerHTML = "You're Out Of Money!!!";
}
document.getElementById("textbox").style.display = 'none';
document.getElementById("button").style.display = 'none';
function doMath() { // PVPCoinTransaction() and
transferCoins() are off right now. Plus 4 tests failed
and
are also off at end of function.
if (pot == 0){
countWagers = 0;
}
if (money <= 0) {
money = 0 ; }
if (x > money) {
x = money ; }
money = money - x;
pot = pot + x;
}
doMath()
function updateDatabase() {
// POST test not working
// $.ajax({
// url: 'php/credits/credit.php', //
// type: "POST",
// dataType:'json', // add json datatype to get json
// data: ({money: 145}), Do I put div here and how?
// success: function(data){
// I dont need to return anything, just update db field!
// }
//});
// this section reaches php but posts 0 into database field
//data = money // I don't think this is working.
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xml = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
xml = new ActiveXObject("Microsoft.XMLHTTP");
}
xml.open("POST", "../php/credits/credit.php", true);
xml.setRequestHeader("Content-type", "application/x-
www-form-urlencoded");
xml.send(money);
}
updateMoney()
updateDatabase()
credit.php
<?php
session_start();
if(empty($_SESSION['userid'])) // check user login
{
header("Location: ../login/index.php");
}
include('../../login/database.php');
if (isset($_SESSION['userid'])) {
// $money = null;
// $money = $_POST['money'];
try {
$db = DB();
header("Content-Type: application/json");
$stmt = $db->prepare("UPDATE usersystem SET money=:money");
$stmt->bindValue(':money', $_POST['money'], PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
$db = null;
echo $e->getMessage();
}
}
?>
Your server expects a key called money in your $_POST array. This means that in order to receive the data properly you need to send the data with a key as well. In PHP this data looks like an associative array and in JavaScript as an object, both having keys and values.
The easiest way to accomplish a key-value structure is to create a string with a key=value structure. This is similar to how forms send their data to servers and requires no modification on the backend for receiving the data.
var package = `money=${money}`;
There is nothing wrong with XMLHttpRequest (there is with ActiveXObject ;) ), I would recommend to learn the Fetch API. It is an updated and simplified specification of making HTTP requests to and from the server. You've indicated that you don't need to receive a response, that means that a basic POST request with sending data looks like the example below.
fetch('../php/credits/credit.php', {
method: 'POST',
body: package
});
The first parameter is the URL, the second an options object. The method property speaks for itself. The body property is the data you're sending (comparable to xml.send(package);).
Now if your URL is correct then an HTTP request with the correct data should be send to your server.
// $_POST should have received data, and because you've send it as a
// key-value it will be represented as an associative array with,
// you guessed it, keys and values.
$money = $_POST[ 'money' ];
// $money will always be a string in this form, so you'll
// need to convert it if you need it to be a number.
$money_as_number = intval( $money );
To test if this works open the network tab in the developer tools of your browser. You can check if an HTTP request occurs and checkout if the correct payload has been sent.
Okay so this is what works in the console ...
function updateDatabase() {
var package = money;
console.log(package);
fetch('../php/credits/credit.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(package)
});
}
console log = 1975 game.js:1608:9
I just need the 1975 value to post to the database via my php now. it's still posting 0 into my database.
I solved it. Thank you for setting me on the right path!
<?php
session_start();
if (isset($_SESSION['userid'])) {
$money = json_decode(file_get_contents('php://input'), true);
$money_as_number = intval( $money );
$userid = $_SESSION['userid'];
try {
$db = DB();
$stmt = $db->prepare("UPDATE usersystem SET money=:money WHERE userid=:userid");
$stmt->bindValue(':money', $money_as_number, PDO::PARAM_INT);
$stmt->bindValue(':userid', $userid, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
$db = null;
echo $e->getMessage();
}
}
?>

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.

.post javascript with PHP to enable select statement return

.post javascript with PHP to enable select statement return
Okay I got this script that is working
$.post('2.php', { id: 12345 }, function(data) {
// Increment vote count, etc
});
This is what my 2.php looks like
$data = $_POST['id'];
$file = fopen("test.txt","w");
echo fwrite($file, $data);
fclose($file);
So I did a test, I run 1.php and saw test.txt was created with the data.
this prove the connection was successful.
Now is the difficult part.
I need to send id:12345 to 2.php, and 2.php need to
"select * from account where account_id='$data'";
And then the return result, I think of using MYSQL_ASSOC or MYSQL_BOTH
I not sure which is best.
Then get the result, be it 1 row result or many row result.
Return as an array and then use 1.php to perform
alert( ArrayReturnResult );
Assuming that my account table have this value
account_id, account_name, account_phone, account_email
How do I accomplish this?
Assuming you know how to establish a database connection (using PDO, of course), you could do something like this in 2.php:
if(!empty($_POST)) {
$data = (int) $_POST['id'];
// query the table
$stmt = $pdo->prepare("SELECT * FROM account WHERE account_id = :id");
$stmt->bindValue(":id", $data, PDO::PARAM_INT);
$stmt->execute();
// fetch results
$buffer = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$buffer[] = $row;
}
// output JSON string
echo json_encode($buffer);
}
Of course, this isn't tested... and probably isn't secure if dealing with personal details.
Don't forget to update your $.post method so that it can expect JSON-encoded data:
$.post('2.php', { id: 12345 }, function(data) {
console.log(data); // this will now be a JS object, from 2.php
}, 'json');

How Could i fetch the data from Database in a Drop Down menu

I tried the following but id didn't work
//PHP CODE
$query = "SELECT kategorite FROM kategorite";
$data = mysql_query($conn, $query);
$makes = array();
while($row = mysql_fetch_array($data))
{
array_push($makes, $row["Lloji"]);
}
echo json_encode($makes);
//JAVASCRIPT CODE
$(document).ready(function () {
$.getJSON("getTipin.php", success = function(data)
{
var options = "";
for(var i=0; i < data.length; i++)
{
options += "<option value='" + data[i].toLowerCase() + "'>" + data[i] + "</option>";
}
$("#type").append(options);
$("type").change();
});
The code contains some little errors, in addition to those addressed in the other comments. For example you call change() on $('type') instead of $('#type'). Also, not all browsers take well not being supplied with JSON's content type.
In general this problem is made up of two parts:
Fetch the data and output JSON
// Here I strongly suggest to use PDO.
$dbh = new PDO('mysql:host=localhost;port=3306;dbname=database', 'user', 'password',
array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
$query = "SELECT kat_id, kategorite FROM kategorite WHERE kategorite LIKE :search";
$stmt = $dbh->prepare($query);
// Always check parameter existence and either issue an error or supply a default
$search = array_key_exists('search', $_POST) ? $_POST['search'] : '%';
$stmt->bindParam(':search', $search, PDO::PARAM_STRING);
$stmt->execute();
$reply = array();
while ($tuple = $stmt->fetch(PDO::FETCH_NUM)) {
$reply[] = array(
'value' => $tuple['kat_id'],
'text' => $tuple['kategorite'],
);
};
// See: http://stackoverflow.com/questions/477816/what-is-the-correct-json-content-type
Header('Content-Type: application/json');
// Adding Content-Length can improve performances in some contexts, but it is
// needless with any kind of output compression scheme, and if things go as they
// should, here we have either zlib or gz_handler running.
// die() ensures no other content is sent after JSON, or jQuery might choke.
die(json_encode($reply));
Populate combo box from JSON in jQuery
function fillCombo($combo) {
$.post('/url/to/php/endpoint',
{ search: '%' },
function(options) {
for (i in options) {
$combo[0].options[i] = {
value: options[i].value,
text : options[i].text
};
}
$combo.change();
}
);
}
fillCombo($('#comboBox');
In this case since the data returned is in the same format used by the comboBox, you could also shorten and accelerate things with:
function(options) {
$combo[0].options = options;
$combo.change();
}
In general you want the server to do as little work as possible (server load costs money and impacts performances), but also the client to do as little work as possible (client load impacts site's perception and responsivity). What data exchange format to use is something almost always worth thinking upon.
For very long lists without paging, for example, you might want to cut the data being sent, by only encoding the option's text. You will then send
[ 'make1','make2','make3'... ]
instead of
[ { "option": "1", "value": "make1" }, { "option": "2", "value": "make2" }, ... ]
and use a slower client cycle to fill up the combo box.

Categories

Resources