Mysqli(or PDO) and PHP to Javascritpt array through JSON - javascript

I have researched this question thoroughly. I know there are similar posts but there is simply something wrong with the code. I am fetching all rows from my database through PHP/PDO script (have also tried the similiar MYSQLI version). I then use json_encode to send the results back to the javascript/jquery.
What ever it is, i can send any other type of data through the json and print it through the javascript. But I can't seem to get the array stored in $arr stored in the javascript allArray.
I have tried JSON.parse(allArray) with no luck.
getAllData.php
<?php
header('Content-Type: application/json;');
$a = "bob";
$b = "george";
$arr = [];
/* Connect to a MySQL database using driver invocation */
$dsn = 'mysql:dbname=guessthe_bob;host=localhost';
$user = 'guessthe';
$password = '***';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sth = $dbh->prepare("SELECT id,title FROM questions2 ORDER BY id");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
//print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
$arr = $result;
echo json_encode($arr);
// Free result set
$sth = null;
$dbh = null;
?>
.js
$.getJSON("functions/getAllData.php", function(data) {
var allArray = data;
$.each(allArray, function(index, value){
$('.testSpot').append(index + ": " + value + '<br>');
});
}
null

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.eyJmbHgiOnsicGF0aCI6Ii9mbGV4L3YxL3Rva2Vucz9mb3JtYXRcdTAwM2RKV0UiLCJkYXRhIjoiOFZ6WnhyUHd2b1dRb1I0QTVTRWNteEFBRUliNlJsT1YzdGU4UUxGdmEwb08wTEliWkhtWmE4Z2ZqT0lSWklmS1FaUElRYmhaZHVlRFNwQzZZZllUanF0cU94d2xtUVlQa1FzZUcrL05WUGlBbUZUdGtUNjlUbXAyb3pEOWJqT0NyVFlQIiwib3JpZ2luIjoiaHR0cHM6Ly90ZXN0ZmxleC5je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fe6XeJw8-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.

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

Php, Sql query won't let me pass in a variable, i keep getting an empty Array

So i am trying to run a Select query to my database but the query won't work when i pass in a pre defined variable. but it work only when i explicitly type it in For Example 'username', but won't let me pass in variable for example '$username'
So i have a a function in my angular file that is posting information to my php file.
Here is my php file:
<?php
require "loginConnect.php";
if($conn)
{
$gotIt = json_decode(file_get_contents('php://input'));
$username = mysqli_real_escape_string($conn, $gotIt->{"username"});
$password = mysqli_real_escape_string($conn, $gotIt->{"password"});
$myquery = "SELECT Email, Firstname, Lastname, Username, Password, ConfirmPassword FROM Myusers WHERE Username = '$username'";
// creating var to store the server's results
// passing in $conn for connection and $myQuery
$request = mysqli_query($conn, $myquery);
if ($request)
{
echo "the request was made successfully";
}
else
{
echo "the request failed";
}
// declaring an array to store the results objects in
$data = array();
// using the foreach loop to loop thu object in results
foreach ($request as $i) {
$data[] = $i;
}
// closing the connection and display the data
mysqli_close($conn);
echo json_encode($data);
}
else //otherwise connection failed come here
{
echo "sorry bad connection";
}
?>
so when i pass in the $username variable in my query i get nothing even thought i should be getting something, but when i type the username like 'theblackmamba' get what i want. even though the variable containers the same string, the variable is just not working. Please help i am super STUCK!

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

Passing JSON object built from SQL from PHP to JavaScript

I am trying to pass a JSON object from PHP to Javascript. the object is being filled from an SQL Database here is the PHP code I am using.
<?php
$conn = mysql_connect("localhost","root","");
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('db') or die( 'Error'. mysql_error() );
$query = "SELECT * FROM products;";
$results = mysql_query($query, $conn);
$return = array();
while($result = mysql_fetch_assoc($results))
{
$mount = array('product_code' => $results['product_code'], 'colour' => $results['colour'], 'price' => $results['price']);
array_push($return, $mount);
}
return json_encode($return);
?>
I have changed a few of the variable names but the same functionality is there.
now when I try to do an AJAX Get to this .php file it crashes at the JSON.Parse part code shown below:
$.get("JSON.php", function(data) {
var JSONdata = JSON.parse(data);
alert(JSONdata[0].colour);
});
My alert is there just for testing.
I Understand the problem may lie in my building of the $return array. Rather new to JSON, any help would be greatly appreciated.
EDIT: taking all the information from below I have corrected my PHP code to look as such.
<?php
$conn = mysql_connect("localhost","root","");
$error = array("result" => false, "error" => mysql_error());
if(! $conn )
{
die(json_encode($error));
}
mysql_select_db('db') or die(json_encode($error));
$query = "SELECT * FROM products;";
$results = mysql_query($query, $conn);
$return = array();
while($result = mysql_fetch_assoc($results))
{
$mount = array('product_code' => $result['product_code'], 'colour' => $result['colour'], 'price' => $result['price']);
array_push($return, $mount);
}
echo json_encode($return);
?>
I'm Looking into changing the mysql_* functions to new more compatible versions
You are using 'return' at the end of the php script, echo the json encoded string :
echo json_encode($return);
Also, it might be a good idea to set the contenttype header to application/json.
Edit:
If you script fails, you use die('error'.mysql_error());
This will also be a response to the ajax call, but not json, and the parse function will throw an exception.
I would recommend returning a json object instead, like:
$error = array("result" => false, "error" => mysql_error());
die(json_encode($error));
Also as stated in comments, do not use mysql_* functions, they are deprecated in later php versions and will be gone from php all together in future releases.
Check out mysqli or even better, PDO.

Categories

Resources