Creating JavaScript variable within PHP retrieving in JavaScript - php

Basically what I have is, there is an index file, that links to a JS file, which then pulls in a PHP file.
So in the PHP file I have (along with other code) :
echo " <script type='text/javascript'>var paging = [ ";
echo "{";
echo "numrows:'" . number_format($numrows) . "',";
echo "pagenum:'" . number_format($pagenum) . "',";
echo "maxpage:'" . number_format($maxpage) . "',";
echo "record_min:'" . number_format($record_min) . "',";
echo "record_max:'" . number_format($record_max) . "'";
echo "}];</script>";
Then, in a JS file I use ajax:
req.open("GET", "server.php", true);
and within the readystatechange I need to retrieve that paging variable you see from the php file because it contains data from the database.
In the JS file I have tried using a variable instead of echo
var m=<?PHP echo $paging; ?>
but that doesn't work either.
Any suggestions or ideas how to get this to work?

I'd use JSON instead of JS. You should be able to pass a PHP array to the json_encode function. See: http://php.net/manual/en/function.json-encode.php
Also, on the PHP side, you may want to modify your response headers to indicate that the response message body is JSON:
header( 'Content-Type: application/json' );
Then, use jQuery to get the JSON from the server: http://api.jquery.com/jQuery.getJSON/

Another possible solution for you if you don't get direct JSON working (scaled down to two variables)
echo '<div id = "numrows">'. number_format($numrows) . '</div>';
echo '<div id = "pagenum">'. number_format($pagenum) . '</div>';
in the php file
req.onreadystatechange = function(){
if (req.readyState == 4 && req.status == 200){
document.getElementById('return').innerHTML = req.responseText;
}
}
req.open("GET", "server.php", true);
req.send();
n["numrows"] = document.getElementById("numrows").innerHTML;
e = document.getElementByID("numrows");
e.parentNode.removeChild(e);
n["pagenum"] = document.getElementById("pagenum").innerHTML;
e = document.getElementByID("pagenum");
e.parentNode.removeChild(e);
in the javascript
<div id = "return" style="display: none;"></div>
in the html
Not the most elegant solution, but fairly straightforward to follow if you can't get anything else working.

Ok because jQuery makes this easy, here is my example:
$paging = array(
"numrows" => number_format($numrows),
"pagenum" => number_format($pagenum),
"maxpage" => number_format($maxpage),
"record_min" => number_format($record_min),
"record_max" => number_format($record_max)
);
$output = json_encode($paging);
header( 'Content-Type: application/json' );
echo $output;
Then in your javascript page using jquery do this:
function myCallBackFunction(data){
alert(data.numrows);
}
$.getJSON('server.php',myCallBackFunction(data));
Hope this helps.
Edited to use array and json_encode

Related

Refresh one variable every second

I want to refresh two variables named profittext and sumtext which will be refreshed and echoed in the following places every few seconds. I know AJAX is needed to do this but how do i actually make it work ? The only way i found out was to refresh the content of the whole file. is there any way to refresh specific variables? Any answers will be greatly appreciated . Thank you very very much.
<table>
if($profitandloss<$zero) {
$profitText = "<div style=\"color: red;\">$profitandloss</div>";
} elseif ($profitandloss>$zero) {
$profitText = "<div style=\"color: green;\">$profitandloss</div>";
}
// for profit and loss counting
$sum+= $profitandloss;
//
echo "<tr><td>" . $row['trade_id'] .
"</td><td>" . $row['selection'] .
"</td><td>" . $row['date'] .
"</td><td>" . $row['type'] .
"</td><td>" . $row['size'] .
"</td><td>" . $row['bidprice'] .
"</td><td>" . $row['offerprice'] .
"</td><td>" . $row['stoploss'] .
"</td><td>" . $row['takeprofit'] .
"</td><td>" . $profitText .
"</td><td><a href ='delete.php?id=".
$row['trade_id']."'>X</a>
</td></tr>";
$profitandloss=0;
if($sum<$zero) {
$sumText = "<div style=\"color: red;\">$sum</div>";
} elseif ($sum>$zero) {
$sumText = "<div style=\"color: green;\">$sum</div>";
}
}
echo "</table><br>";
?>
<!DOCTYPE html>
<html>
<table style="border:1px solid black;">
<tr>
<th style="border:1px solid black;">Profit/Loss</th>
</tr>
<tr>
<td style="border:1px solid black;"><?php echo $sumText ;?></td>
</tr>
</table>
</html>
I struggled with the concept of how to structure such code when I first started too. Although it's not specific to your particular variables, here's a quick example for how to update a var through AJAX with jQuery/PHP.
Prologue: If this is something you're going to be doing often, you'll want to learn jQuery, rather than using normal javascript alone. There are lots of great, free, resources on how to learn jQuery. Alternatively, if you're not satisfied with the free tutorials online, this is an excellent book. I'll write the example in jQuery.
Design: Okay, so the way it works is this:
Set a timer in javascript to execute a particular function every X seconds (you DO NOT want to do it every second).
That function makes an AJAX call (with jQuery) to a .PHP file on the server, sending it the data necessary so that the .PHP code knows what to send back.
The .PHP code grabs the data required (e.g., with MySQL) encodes it in a JSON format, and exits.
A promise on the AJAX call is fired and the data sent from PHP is received. Process it as you will.
Repeat from step 2.
If you have any questions about what the code is doing, please ask.
AJAX.PHP
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$return_obj = array();
$request_obj = NULL;
// our AJAX call used "POST" as it's 'type', so we look in that
// variable.
if ( array_key_exists("func",$_POST) ) {
if ( $_POST['func'] === "get_update" ) {
if ( array_key_exists("which_var",$_POST) ) {
$which_var = $_POST['which_var'];
$which_var = $mysqli->real_escape_string($which_var); // should use prepared statements
// we sent 'num_people_logged_in' as our value here, so we'll be looking for a column/field
// with that value. this assumes that some other code, somewhere else,
// is regularly updating the table. it also assumes that there will only
// be a single row returned, which will hold the value.
$query = "SELECT '$which_var' FROM site_stats ";
if ( $result = $mysqli->query($query) ) {
if ( $row = $result->fetch_assoc() ) {
$request_obj[$which_var] = $row[$which_var];
}
}
}
}
}
$return_obj['request'] = $request_obj;
echo json_encode($return_obj);
die();
?>
MYCODE.JS
// this actually sends the AJAX request to the server.
function getUpdate() {
var jqXHR = $.ajax({
url : "ajax.php",
data : {
'func' : 'get_update',
'which_var' : 'num_people_logged_in'
},
dataType : 'json',
type : 'POST',
timeout : 10000
});
// attach 'promises' to the jqXHR object, which represents
// the AJAX call itself. 'promises' are, in this context,
// just events.
jqXHR.done(function(data,textStatus,jqXHR) {
// this executes if the AJAX call succeeded.
// the variable 'data' holds what the server
// sent us.
if ( ( data ) && ( data.request ) ) {
receiveUpdate(data.request);
}
});
jqXHR.fail(function(jqXHR,textStatus,errorThrown) {
// this executes if it failed
console.log("Fail: " + textStatus + " (" + errorThrown + ")");
});
jqXHR.always(function(a,textStatus,c){
// this executes either way, after .done or .fail
});
}
// this is called from jqXHR.done, on success
function receiveUpdate(request_obj) {
if ( request_obj.num_people_logged_in ) {
updateDOM(request_obj.num_people_logged_in);
}
}
function updateDOM(num_people_logged_in) {
if ( num_people_logged_in ) {
$("#mydiv > p.update").html("The updated value is: " + num_people_logged_in);
}
}
var timeoutID = null;
// setup our timer, to periodically make an
// AJAX call
function init() {
timeOutID = setInterval(function(){
getUpdate();
},5000);
}
// stop the timer
function cleanup() {
clearTimeout(timeoutID);
}
INDEX.HTML
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>AJAX practice</title>
<!-- <link href="mycss.css" rel='stylesheet'> if needed -->
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="mycode.js"></script>
<script>
$(document).ready(function() {
init();
$("#cleanup").on("click",function(){
cleanup();
});
}); // end ready
</script>
</head>
<body>
<div id='mydiv'>
<p>
How many people are online?
</p>
<p class='update'>
</p>
</div>
<button id='cleanup'>Stop updating!</button>
</div>
</body>
</html>
You will needd two PHP pages:
- one with HTML and JS, which periodicly makes ajax calls and puts the result to the HTML
- second with json (or even plain text) output of your dynamic data piece
Unfortunately, writing the full code in the answer is not someting that people do at stackoverflow, so just look at small example below, and try to figure out the missing parts.
http://jsfiddle.net/AMEqz/
var xhr = new XMLHttpRequest();
xhr.onload = function(r) {
// your render logic HERE
setTimeout(send, 1000);
}
function send() {
xhr.open("GET", "/", true);
xhr.send();
}
send();
p.s.: keep in mind that each ajax request will mean extra connection to your server, so make sure it can deal with the load ;)
Use a timer : https://developer.mozilla.org/en/docs/DOM/window.setInterval
setInterval(function(){
//update your var here
},1000);

How to POST multiple Variable in JavaScript inside PHP?

I am trying to pass multiple variable using JavaScript and PHP, but not being able to do that.
echo "<a href=javascript:popcontact('btsdetails.php?uid=" . $row["bs_id_site"] . "&sid=" . substr($row['bs_id'], -1) . "')>" . $row['bs_id'] . "</a>";
Therefore, I am trying to POST "uid" and "sid" using & sign, but it is not working. It is only accepting the "uid".
Can anyone help me to solve this problem?
Here is the answer:
<script type="text/javascript">
function popcontact(uid, sid){
window.location = "btsdetails.php?uid="+uid+"&sid="+sid;
}
</script>
<?php echo $row['bs_id']; ?>
you can use http_build_query
<?php
$params = array("uid"=>$row["bs_id_site"], "sid"=>substr($row['bs_id'], -1));
$url = "btsdetails.php?".http_build_query($params);
?>
<?= $row['bs_id'] ?>

JSON escaping slashes in a file path, wont display image

I'm using PHP and a for loop to prepare data into proper html and output the data using JSON to be appended and displayed on the page. JSON slash escaping is causing the html to be viewed incorrectly by the browser.
This is my PHP for loop:
$json = '<div id="rsec3" class="rsec">';
for($i=0; $i<count($array); $i++)
{
$coverart = $array[$i]['cover'];
if(empty($coverart))
{
$coverart = "nocoverart.gif";
}
$json .= '<div><img="/video/cover/thumbs/' . $cover . '"></div>';
}
$json .= '</div>';
$json = json_encode(array('ok' => 'ok', 'html' => $json));
echo $json;
This is my javascript parsing and appending the json:
$.get('/index_get.php?iid='+this.id,function(data){
$('#indload').hide();
js=jQuery.parseJSON(data);
$('#indr').append(js.html);
});
This is what the browser is displaying, a bunch of useless jargon, and it is appending a </img="> on its own?
<img=" video cover thumbs img.png"></img=">
How can I prevent this from occuring, and having the image displayed properly?
I think problem could be invalid HTML tag <img> on the php code. In the <img> tag, src is missing and <img> tag was not closed.
Change the following
$json .= '<div><img="/video/cover/thumbs/' . $cover . '"></div>';
to
$json .= '<div><img src="/video/cover/thumbs/' . $cover . '" /></div>';
you need to close the image tag in your string
$json .= '<div><img="/video/cover/thumbs/' . $cover . '"/></div>';

Parse XML in Js for Website

Hy!
I am very new in Web-Dev. I have a mysql db and the controller is made with PHP.
I give the data formated in php back to the html.
My Quest:
How to parse the xml in js right for the HTML based view?
If there are better solutions for the data transfair between PHP and HMTL, please let me know.
I don't wont the have HTML code in the php
Example PHP:
<?php
$id = $_GET['id'];
if (is_numeric($id))
{
include 'db_connect.php';
$sql = "Select * from RECIPES WHERE recipes_id=".$id;
$result = mysql_query($sql,$db) or exit("QUERY FAILED!");
while($row = mysql_fetch_array($result))
{
echo "<RECIPE>";
echo "<ID>" . $row['recipes_id'] . "</ID><br />";
echo "<TITLE>" . $row['text'] . "</TITLE><br />";
echo "<TEXT>" . $row['text'] . "</TEXT><br />";
echo "<COUNT_PERSONS>" . $row['count_persons'] . "</COUNT_PERSONS><br />";
echo "<DURATION>" . $row['duration'] . "</DURATION><br />";
echo "<USER_ID>" . $row['user_id'] . "</USER_ID><br />";
echo "<DATE>" . $row['date'] . "</DATE><br />";
echo "</RECIPE>";
}
}
else
{
echo "<ERROR>ID ERROR</ERRORR>";
}
mysql_close($db);
?>
thx
If you just want to transfer data between the browser and the server then it's simpler to use the JSON format. For PHP there are two built in function to decode and encode JSON: json_decode and json_encode.
Modern browser support JSON by default: JSON.parse and JSON.stringify.
I agree with styrr, but if you must use XML then you can use jQuery.parseXML() or simply use jQuery.ajax() with correct type eg.:
$.ajax({
url: "script.php?parameters=abc",
dataType: "xml",
success: function(responseDocument){
var all_ids = responseDocument.getElementsByTagName('ID');
var all_ids_jquery_way = $('ID', responseDocument);
}
});
You can use any othe AJAX framework or even write your own function. Browsers can parse XML and create a document which you can then change as the main document (with DOM functions).
Again with most data JSON is a bit simpler to use and is lighter.

JavaScript & JSON

I am new to JS & JSON.I am struggle with converting JSON array to JavaScript array.How to do that? Here is my code:
var data = {
items: [
<? $i=1; foreach($query->result() as $row){ ?>
<? if($i!=1){ ?>,<? } ?>
{label: '<?=$row->district_name;?>', data: <?=$row->countid;?>}
<? $i++; } ?>
]
};
how to get the JSON array value to JavaScript Array.
i just tried but it doesn't work. please some suggestions.
here is my javascript array
for(i=0;i<5;i++){
chartData[i]=data.items[i].label+";"+data.items[i].data;
}
As the others already said, be careful when talking about JavaScript and JSON. You actually want to create a JavaScript object and not JSON.
Don't mix PHP and JavaScript like this. It is horrible to maintain. Create an array beforehand, encode it as JSON* and print it:
<?php
$results = $query->result(); // get results
function m($v) { // a helper function for `array_map`
return array('label' => $v->district_name,
'data' => $v->countid);
}
$data = array('items' => array_map('m', $results));
?>
var data = <?php echo json_encode($data); ?>
*: Here we use the fact that a JSON string is valid JavaScript too. You can just echo it directly in the JavaScript source code. When the JS code runs, it is not JSON, it is interpreted as JavaScript object.
You really oughtn't think too hard about this. PHP does a fine job of serializing arrays as JSON.
var data = {
items: <?php
$arr = array();
foreach($query->result() as $row) {
$arr[] = array('label' => $row->district_name,
'data' => $row->countid);
}
echo json_encode($arr);
?>
};
[insert same disclaimer as above about how you're really trying to create a JavaScript object]
This is JSON:
var foo = "{bar: 1}";
This is not JSON:
var foo = {bar: 1};
Your code snippet is not using JSON at all and my educated guess is that you don't even need it. If you are using PHP to generate some JavaScript code, you can simply tweak your PHP code to print text that will contain real JavaScript variables. There is no need to encode stuff as plain text!
Now it's clear we don't need JSON, let's use a dirty trick. PHP has json_encode() and we can abuse the fact that a JSON strings resemble JavaScript variables. All we have to do is call json_encode() on our PHP variable and forget to quote the result:
<?php
$foo = array(
'bar' => 1,
'dot' => FALSE,
);
echo 'var JSONString = "' . json_encode($foo) . '";' . PHP_EOL;
echo 'var realVariable = ' . json_encode($foo) . ';' . PHP_EOL;
Compare:
var JSONString = "{"bar":1,"dot":false}";
var realVariable = {"bar":1,"dot":false};
Edit: Yep, my JSONString is not a valid string... but we get the idea <:-)

Categories