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.
Related
An api is sending back data in this format x[[seconds:cost[[x i'm using php and javascript, how do I retrieve the seconds only, than retrieve the cost only
so for example they would send back something like this
x[[16413:2.60[[x
how can i get the values of seconds/cost without all that extra x[[ stuff included?
i want just the seconds
than i want just the cost
Use regular expression to parse the string.
In JavaScript:
var s = 'x[[16413:2.60[[x';
var parts = s.match(/([.0-9]+):([.0-9]+)/);
var seconds = parts[1];
var cost = parts[2];
alert(seconds);
alert(cost);
In PHP:
$s = 'x[[16413:2.60[[x';
preg_match('/([.0-9]+):([.0-9]+)/', $s, $parts);
$seconds = $parts[1];
$cost = $parts[2];
echo $seconds . "; " . $cost;
enter code here
I'm trying to get out ID from link:
www.imdb.com/title/tt5807628/ - > tt5807628
My code in javascript:
var str = "www.imdb.com/title/tt5807628/";
var n = str.search("e/tt");
var res = str.substring(n+2, n+30);
var ukos = res.search("/");
var last = res.substring(0, ukos);
I would like to get the same effect in PHP, how to do it?
Based off my comment here, the following code will just give you the ID:
$id = explode("/", "www.imdb.com/title/tt5807628/")[2];
We use the explode(delimiter, string) function here to break the string at each of the slashes, which creates an index of strings that looks like this:
array (
0 => "www.imdb.com"
1 => "title"
2 => "tt5707627"
)
So, as you can see array index 2 is our ID, so we select that after we break the string (which is the [2] at the end of the variable declaration), leaving us with a variable $id that contains just the ID from the link.
edit:
You could also use parse_url before the explode, just to ensure that
you dont run into http(s):// if the link changes due to user input.
- Keja
$id = explode("/", parse_url("www.imdb.com/title/tt5807628/", PHP_URL_PATH))[2];
With explode function then you can see each part by looping through the array
$varArray = explode( '/', $var );
You can use preg_match as well:
preg_match('~www\.imdb\.com/title/([^/]*)/~', 'www.imdb.com/title/tt5807628/', $matches);
$id = $matches[1];
I have a very simple PHP array
$array = [];
$array['a'] = '1';
$array['b'] = '2';
$array['c'] = '3';
PHP
If I dd($array); out I got
array:3 [▼
"a" => "1"
"b" => "2"
"c" => "3"
]
If I decode dd(json_encode($array));, I got this
"{"a":"1","b":"2","c":"3"}"
JS
I want to be able to access this variable in my Javascript, So I've tried
1
console.log($array);
I got
$array is not defined
2
I'm using Laravel. {{ }} == echo
console.log('{{$array}}');
I got
500 Internal Error
htmlentities() expects parameter 1 to be string, array given (View: /Users/bheng/Sites/portal/resources/views/cpe/index.blade.php)
3
console.log('{{ json_encode($array)}}');
I got
The page to load, but the data is very bad looking
{"a":"1","b":"2","c":"3"}
4
console.log(JSON.parse('{{ json_encode($array)}}'));
I got
Uncaught SyntaxError: Unexpected token & in JSON at position 1
5
console.log(JSON.parse('{{ json_decode($array)}}'));
I got
json_decode() expects parameter 1 to be string, array given
6
console.log('{{ json_decode($array)}}');
I got
json_decode() expects parameter 1 to be string, array given
GOAL
I just want to be able to access my array as Javascript Array or JSON in the Javascript.
Can someone please fill me in on this ?
In Blade, {{ $variable }} will output an escaped version of the string, passed through htmlentities() to make it safe for use in HTML. You want an unescaped version. You can use {!! $variable !!} for that:
console.log({!! json_encode($array) !!});
You don't need to add quotes around it, json_encode() outputs a valid javascript object. It will add quotes where necessary, if you add them yourself you will get the JSON string in your javascript, instead of the JSON object.
In Laravel you can use {!! !!} to skip entity escaping
console.log({!! json_encode($array) !!});
Just echo it as json data and use it in javascript.
<?php
$array = [];
$array['a'] = '1';
$array['b'] = '2';
$array['c'] = '3';
?>
<script>var jsArr = <?=json_encode($array);?>;
alert(jsArr);</script>
EDIT because of clarification that you're using blade. Then it should be:
<?php
$array = [];
$array['a'] = '1';
$array['b'] = '2';
$array['c'] = '3';
?>
<script>var jsArr = {!! json_encode($array) !!};
alert(jsArr);</script>
{ ... } is an escaped version of your string. But you need the unescapt string. This can be achieved by using {!! ... !!}.
First, you have to understand that PHP run on server side and javascript on client side, as PHP make the response you should print a script like this:
echo "<script>
var sheison = JSON.parse(".dd(json_encode($array)).");
console.log(sheison);
</script>";
I didn't test the code, is just the idea.
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);
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>";
}