been trying to save my data from my while loop to script variables but no success. Did an example if how I want to save my php data to script variables. This doesn't work for me. Anyone have any idea? Don't want to save all data manually. Very greatful for answers! Ask if you don't understand :)
$id = 0;
while($rows = mysql_fetch_array($data)){
$id = $id + 1;
$data = $rows['data'];
echo "<script>";
echo "var data" . $id . " = " . $data . ";"; //???
echo "</script>";
}
The best thing to do here would almost certainly be to create an array (on the PHP side), and then output the entire array at once.
Assuming you've built an array in $array, here's how you would output it:
echo "<script>var data = " . json_encode($array) . ";</script>"
More on json_encode in the docs, but basically it encodes the PHP data as valid JSON. Since JSON is a subset of JavaScript object and array initializer syntax, you can safely output JSON text as the right-hand side of an assignment, as above.
In the client-side script, you'd access each item via data[0], data[1], etc. up through data[data.length - 1].
Separately, note what Nathan Loding pointed out in a comment on the question:
...[you're] calling mysql_fetch_array($data) and then [have] $data = $rows['data'] two lines further down, thus overwriting $data...
...which will tend to mess up your fetch loop.
You are duplicating the script tag on every iteration.
you also need to surround the data in double or single quotes.
But it is not so safe..
$id = 0;
$data = "";
$vars = "";
while($rows = mysql_fetch_array($data)){
$id = $id + 1;
$data = $rows['data'];
$vars .= "var data" . $id . " = \"" . addslashes( $data ). "\";"; //???
}
echo "<script>";
echo $vars;
echo "</script>";
}
Related
I am trying to convert a PHP function to javascript, but i cant read the following line of codes:
$sha_string .= "$key=$value$ipn_passphrase";
and
$sha_sign = strtoupper(hash("sha512", $sha_string));
Complete function:
function digistore_signature( $ipn_passphrase, $array)
{
unset($array[ 'sha_sign' ]);
$keys = array_keys($array);
sort($keys);
$sha_string = "";
foreach ($keys as $key)
{
$value = html_entity_decode( $array[ $key ] );
$is_empty = !isset($value) || $value === "" || $value === false;
if ($is_empty)
{
continue;
}
$sha_string .= "$key=$value$ipn_passphrase";
}
$sha_sign = strtoupper(hash("sha512", $sha_string));
return $sha_sign;
}
the $array is the body of a POST request.
the $passphrase is a string
.= in PHP is a simple concatenation. it is similar to the programming concept of +=. It's easy to understand with an example
<?php
$a = "hello";
$a .= " "; //now $a = "hello "
$a .= "world"; // now $a = "hello world"
"$key=$value$ipn_passphrase"; is called an in-place variable substitution in PHP. You can check the PHP Doc for more. You can simply consider it as the value $key, $values and $ipn_passphrase is replaced by the values of those variables accordingly and it forms a new string variable $sha_sign.
$sha_sign = strtoupper(hash("sha512", $sha_string)); is a simple statement where you pass the algorithm sha512 and $sha_string to the function hash() and store the result back in $sha_string variable.
I am stuck with this problem. Here is my code:
<?php
$arr = [
'from_name' => 'Rosresurs1.ru',
'from_email' => 'team#rosresurs.net',
'reply_email' => 'reply#rosresurs.net',
'subject' => 'Вас приветствует Росресурс!',
'reply_us' => 'Вопрос нам',
'charset' => 'UTF-8',
'headers' => ['List-Unsubscribe: <mailto:support#rosresurs.net?subject=Unsubscribe>, <http://rosresurs.net/escript/unsubscribe.php?token=$token>', 'Precedence: bulk']
];
echo 'Var dump array to encode: <br>';
var_dump($arr);
//Encoding
$done = json_encode($arr, JSON_UNESCAPED_UNICODE);
echo 'Echo encoded array to json: <br><br>';
echo $done . "<br><br><br><br>";
//Decoding
echo "Starting decoding from file: <br><br>";
$var = json_decode('mailconfig.json', true);
$json_errors = array(
JSON_ERROR_NONE => 'No error has occurred',
JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
JSON_ERROR_SYNTAX => 'Syntax error',
);
echo 'Last JSON error found: ', $json_errors[json_last_error()], PHP_EOL, PHP_EOL . '<br><br>';
echo 'Var dump variable: <br>';
var_dump($var);
And here is the output:
And here is JSON file, from which I tried to decode json:
{"from_name":"Rosresurs1.ru","from_email":"team#rosresurs.net","reply_email":"reply#rosresurs.net","subject":"Вас приветствует Росресурс!","reply_us":"Вопрос нам","charset":"UTF-8","headers":["List-Unsubscribe: , ","Precedence: bulk"]}
As you see my array contains UTF-8 symbols, so I have encoded them with JSON_UNESCAPED_UNICODE option. But when I try to decode(FROM FILE), it fails. But when I try to decode from encoded variable $done, it works perfectly.
My json file contains the same $done output(copied from the browser and pasted to file). json_last_error said it's a syntax error. But there is no one...
Also I pasted json string from file to online json syntax verify service and it returned "A valid JSON string".
P.S. I made a lot of echo helpers(see screenshot), so you can get into a problem fast(like starting encoding and decoding points).
According to the docs, json_decode() does not take a filename as a parameter, only a string.
If you want to decode JSON from a file you would need to do something like this:
$var = file_get_contents('mailconfig.json');
$var = json_decode($var);
Or, if you have to do this a lot, you could wrap the whole thing in a function:
function file_json_decode($path, $assoc = false){
if(file_exists($path)){
$json = file_get_contents($path);
$result = json_decode($json, $assoc);
} else {
$result = null;
}
return $result
}
And then call it like this:
$var = file_json_decode('mailconfig.json', true);
You are calling json_decode on a wrong parameter. The first parameter is the JSON data, not a filename! So if you want to parse the JSON from a file, you may write
json_decode(file_get_contents('mailconfig.json'), true);
I wrote this code:
$userAddresses = $database->getUsers("SELECT * FROM Users");
$address = array();
foreach($userAddresses as $user){
array_push($address, array("address"=> $user['address'],
"zipcode" => $user['zipcode']));
}
$locations = array(
"locations" => $address
);
$jsonLocations = json_encode($locations);
This code returns this json object:
{"locations":[
{"address":"Sneekermeer 25","zipcode":"2993 RL"},
{"address":"Boeier 13","zipcode":"2992 AK"}]}
I want to get the length of this array inside JavaScript. So I did this:
var address = '<?php echo $jsonLocations ?>';
After that I called console.log(address.length); to check the length but some how it counts all the chars (108 I think) in the address variable and returns that as length. address.locations.length also doesn't work.
Could someone help me out?
You can use JSON.parse()
var address = JSON.parse('<?php echo $jsonLocations ?>');
console.log(address.length); // will give you length;
Thats because the string needs to be decoded to an object. You can do this one of two ways.
Non recommended:
var address = <?= $jsonLocations ?>;
Or more correctly and safer:
var address = JSON.parse('<?= addslashes(json_encode($jsonLocations)) ?>');
Do not forget the call to addslashes to prevent any single quotes in your array from breaking the javascript string.
You can either remove the quotes around var address = '<?php echo $jsonLocations ?>'; (i.e var address = <?php echo $jsonLocations ?>;) or use JSON.parse to parse it as a string to an object.
I have tried the below and its working
var address = '{"locations":[{"address":"Sneekermeer 25","zipcode":"2993 RL"},{"address":"Boeier 13","zipcode":"2992 AK"}]}';
address = JSON.parse(address);
console.log(address.locations.length);
I have a PHP file that encodes Json data and when i view the JSON output when its a single data block i get a valid json code syntax this is an example :
single data block
But when the JSON results in a multiple data block it generates an invalid JSON format like this: multiple data blocks
This is my PHP code:
<?php
header('Content-Type: application/json; charset=utf-8', true,200);
DEFINE('DATABASE_USER', 'xxxxx');
DEFINE('DATABASE_PASSWORD', 'xxxxxx');
DEFINE('DATABASE_HOST', 'xxxxxxxxxxx');
DEFINE('DATABASE_NAME', 'xxxxxxxx');
// Make the connection:
$dbc = #mysqli_connect(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD,
DATABASE_NAME);
$dbc->set_charset("utf8");
if (!$dbc) {
trigger_error('Could not connect to MySQL: ' . mysqli_connect_error());
}
if(isset($_GET['keyword'])){//IF the url contains the parameter "keyword"
$keyword = trim($_GET['keyword']) ;//Remove any extra space
$keyword = mysqli_real_escape_string($dbc, $keyword);//Some validation
$query = "select name,franco,alpha,id,url,songkey,chord from song where name like '%$keyword%' or franco like '%$keyword%'";
//The SQL Query that will search for the word typed by the user .
$result = mysqli_query($dbc,$query);//Run the Query
if($result){//If query successfull
if(mysqli_affected_rows($dbc)!=0){//and if at least one record is found
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){ //Display the record
$data = array();
$data = $row;
echo $_GET[$callback]. ''.json_encode($data).'';
}
}else {
echo 'No Results for :"'.$_GET['keyword'].'"';//No Match found in the Database
}
}
}else {
echo 'Parameter Missing in the URL';//If URL is invalid
}
?>
It is because you are JSON-encoding a single line of the result set at at time. This is not a valid JSON structure if the calling client is expecting such.
Likely, you will want to put each row as an entry in an array, and then JSON-encode and echo the resulting array.
Like this:
if($result){//If query successfull
if(mysqli_affected_rows($dbc)!=0){//and if at least one record is found
$array = array();
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){ //Display the record
$array[] = $row;
}
echo json_encode($array);
}
}
ChkNewRspLive.php
<?php
$query3 = "SELECT msgid, id FROM rspnotificationlive WHERE username='{$username1}' ORDER BY id LIMIT 99";
$result3 = mysql_query($query3,$connection) or die (mysql_error());
confirm_query($result3);
$numrspmsg = mysql_num_rows($result3);
echo $numrspmsg . "|";
while($userinfo3 = mysql_fetch_array($result3)){
$rspmsgid= $userinfo3['msgid'];
$msgid= $userinfo3['id'];
echo $rspmsgid . ", ";
}
?>
index.html
<script type="text/javascript">
$.get("ChkNewRspLive.php?username=" + username, function(newrspmsg){
var mySplitResult = newrspmsg.split("|");
var rspMsgCount = parseFloat(mySplitResult[0]);
var rspMsgids =(mySplitResult[1]);
var Msgids = ??//how to get this result from ChkNewRspLive.php ?
});
</script>
As you can see, I used "|" to separate $rspmsgid and $numrspmsg. I also use "," to separate multiple $rspmsgid. How if I want to separate another data $msgid? How to do that?
If I use | to separate $rspmsgid and $msgid, there will be many sign of | because they both are in the while loop.
JSON encode your content.
In your php, change your code to something like:
$json = array();
while($userinfo3 = mysql_fetch_array($result3)){
$rspmsgid= $userinfo3['msgid'];
$msgid= $userinfo3['id'];
$json[] = array($rspmsgid,$msgid);
}
echo json_encode($json);
and then use $.getJson in your javascript.
You won't have to define the number of mysql_rows either, as you can just get that in javascript by using .length on the json data.
edit and escape your string before using it in your SQL!
You are already using the .split() method to seperate the other string. Apply it to the other part and let it split by ", " or just use another | instead of the , and you will have it split into three parts instead of two.
However I suggest you have a look at JSON. This should be the better solution if it gets more complicated.