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);
Related
I stored a Javascript value to a PHP variable. When I use var_dump to print it, var_dump returns int(0). It should display int(10). I am using this code:
<script type="text/javascript">
var a = "Hello world: 12345";
var b = a.replace ( /[^\d.]/g, '' );
</script>
<?php
$identity = '<script type="text/javascript">document.write(b)</script>';
var_dump($identity);
echo "<br/>";
$identity = preg_replace('/[^\d]/', '', $identity ); //removes everything except digits
$ord = (int)$identity;
var_dump($ord);
?>
Where have I gone wrong?
Where have i gone wrong ?
JavaScript code doesn't evaluate inside a php script, pretty basic.
You're trying to convert a string to int but php won't allow you to do that when the string contains letters, or anything different from digits.
If you use:
$identity = '<script type="text/javascript">document.write(10)</script>';
$identity = preg_replace('/[^\d]/', '', $identity ); //removes everything except digits
$ord = (int)$identity;
var_dump($ord);
php will convert the string to int without errors.
I have this array ($test) in PHP
array (size=4)
1 => string 'test1#mail.example' (length=17)
2 => string 'test2#mail.example' (length=17)
3 => string 'test3#mail.example' (length=17)
4 => string 'test4#mail.example' (length=17)
And want to pass it to javascript. My goal is to use this in a AJAX query.
So I did the following
var test = "<?php echo json_encode($test); ?>";
$.post("../path/to/file.php",
{
test: test,
},
function(data,status)
{
...
});
But the following is triggering everytime
SyntaxError: missing ; before statement
var test = "{"1":"test1#mail.example","2":"test1#mail.
Don't enclose the json output in quotes. It's unecessary:
var test = <?php echo json_encode($test); ?>;
json_encode() will already be adding any necessary " characters, and your extra " are breaking the syntax, e.g.
php:
$foo = 'ab"c';
json_encode($foo) -> "ab\"c";
js:
var test1 = <?php echo json_encode($foo); ?>;
var test2 = "<?php echo json_encode($foo); ?>";
which comes out as:
var test1 = "ab\"c"; // this line is ok
var test2 = ""ab\"c""; // this line is fubar
^--start string
^--end string
^^---undeclared/undefined variable
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>";
}
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.