Compare php array to javascript array same data - javascript

Scenario: I need to compare a database cell on the page load (php) against itself in an interval loop every x amount of minutes for changes.
My Initial load data looks like this:
var olddata = JSON.stringify(<?php echo json_encode($data1); ?>) + "~|~" +
JSON.stringify(<?php echo json_encode($data2); ?>) + "~|~" +
JSON.stringify(<?php echo json_encode($data3); ?>);
So on page load, I save the cells into a javascript variable with a "~|~" delimiter, where $data1, $data2, and $data3 are 3 different cells in the database (arrays of data).
And my interval loop data (ajax call) looks like this:
// PHP on the AJAX page
echo json_encode($data1)."~|~".json_encode($data2). "~|~".json_encode($data3);
// AJAX code that gets called every x Intervals
$.get("ajaxpage.php", function(data) {
if (data == olddata) {
console.log("Good!");
}
});
When I compare olddata against data they look almost identical except... data that has a / in it will look like \/ in the data variable and not in theolddata` variable.
Example:
"10":["10"],"11":["11 5\/25"] // data = return from the AJAX call
"10":["10"],"11":["11 5/25"] // olddata = what was originally echoed on page load.
How can I compare the two so that they will match perfectly? So that what I echo from the database and json_encode, will line up with what I get from the exact same thing echoed on a page and jason encoded from the json function return.
Note: If I remove the JSON.stringify then it will return [object Object]

You're using a very bad practice. Just use AJAX to get this:
var olddata = JSON.stringify(<?php echo json_encode($data1); ?>) + "~|~" +
JSON.stringify(<?php echo json_encode($data2); ?>) + "~|~" +
JSON.stringify(<?php echo json_encode($data3); ?>);
And store "olddata" in a JavaScript Global var, then compare the old data with the new data returned by $.get. This isn't the solution for your bug, but it's a better way to do what you're doing.
To fix the bug just declare the type of the return value in the your $.get function, like that:
$.get("ajaxpage.php", function(data) {
if (data == olddata) {
console.log("Good!");
}
}, 'text');
For more information about the return type, look the jQuery Documentation: jQuery $.get Documentation

Just change it to:
var olddata = '<?php echo json_encode($data1, JSON_HEX_APOS); ?>~|~<?php echo json_encode($data2, JSON_HEX_APOS); ?>~|~<?php echo json_encode($data3, JSON_HEX_APOS); ?>';
And the backend to:
echo json_encode($data1, JSON_HEX_APOS)."~|~".json_encode($data2, JSON_HEX_APOS). "~|~".json_encode($data3, JSON_HEX_APOS);
Now you're simply comparing two strings.

Related

Get JSON response in PHP using jQuery

Here is my code to call AJAX and get the response from another PHP file:
$.post('<?php echo get_site_url(); ?>/ajax-script/',{pickup:pickup,dropoff:dropoff,km:km},
function(data){
$('#fare').html(data);
$('#loading_spinner').hide();
});
ajaxscript.php file
$jsonData = '{"fare":30580,"actual_distance":1519,"city":"Islamabad","status":true}';
$json = json_decode($jsonData,true);
echo $json['fare'];
This code gives me the fare at the time of $('#fare').html(data);
But I need to extract the city from JSON, too, and for this I added an extra line in ajaxscript.php:
echo $json['city'];
After doing this, it gives me 30580Islamabad
How can I store these two values separately in JavaScript? I need them for future work.
You are doing everything backwards
Your PHP should be
$jsonData = '{"fare":30580,"actual_distance":1519,"city":"Islamabad","status":true}';
//$json = json_decode($jsonData,true);
echo $jsonData;
As you already have a JSONString to send to your javascript.
Then your javascript will recieve a javascript object in the data parameter of
$.post( '<?php echo get_site_url(); ?>/ajax-script/',
{pickup:pickup,dropoff:dropoff,km:km},
function( data ) {
$('#fare').html(data.fare);
$('#city').html(data.city);
$('#loading_spinner').hide();
}, "json");
Note the "JSON" at the end of the javascript to tell it to expect a JSON Object, it will then convert the JSONString to a javascript Object automatically for you so the data parameter will be an onbect
Add Special characters at the end of each value and in jquery, using jquery split, cut the variable and display
like below;
$jsonData = '{"fare":30580^^,"actual_distance":1519^^,"city":"Islamabad^^","status":true}';
$json = json_decode($jsonData,true);
echo $json['fare'];
in jquery
function(data){
var tdata = data.split("^^");
$('#fare').html(tdata[0]);
$('#loading_spinner').hide();
});

Pass a variable from JavaScript to PHP

I'm trying to pass the variable from a JavaScript function - selected text - to the same page using php post method:
if (isset($_POST['u_name']))
{
echo $_POST['u_name'] . '</p>';
}
echo "<script type='text/javascript'>";
echo "var var1 = 0; var range = window.getSelection ();";
echo "function gst () { var range = window.getSelection (); alert (range.toString ()); var1 = range.toString ();}";
echo "document.write('<form method=\'post\'>');";
echo "document.write('<p>selected area:<br />');";
echo "document.write('<button onclick=\'gst ()\' type=\'submit\' name=\'u_name\' value = \'' + var1 + ' \' />Button</button>');";
echo "document.write('</form>');";
echo "alert (interesting);";
echo "</script>";
after pressing the button the selected page text is correct: it is checked with alert (range.toString ()) , however, the initial value of var1 variable - 0 is posted.
What could cause it and how one can pass the value, obtained from the javascript function through post method ?
Anton
That's because you set value attribute on the page load.
You can change it dynamically on button click. Replace one of your rows to:
echo "document.write('<button onclick=\"this.setAttribute(\'value\', var1); gst()\" type=\'submit\' name=\'u_name\' value = \'' + var1 + ' \' />Button</button>');";
Note this.setAttribute.
If you want to pass JavaScript variables to PHP, you'll have to use an Ajax request.
PHP is server sided, whereas JavaScript is client sided. This means that all PHP code is done before any JavaScript is even triggered. You can manipulate JavaScript with PHP, but if you want to manipulate PHP with JavaScript, use an Ajax call.

Store database values in javascript array

I am making a kind of reservation page where you can reserve a location for a specific day, all the dates will be stored in a database for each location.
But I want to get all the dates from the database and store them in a javascript array so I can disable these dates from the datepicker on the page.
I know how to select the dates using php and mysql but I can't figure out a way to store the data in a javascript array.
This is the js code for the datepicker:
var disableddates = ["20-05-2015", "12-11-2014", "21-05-2015", "12-20-2014"];
function DisableSpecificDates(date) {
var string = jQuery.datepicker.formatDate('dd-mm-yy', date);
return [disableddates.indexOf(string) == -1];
}
$(function() {
$("#date1").datepicker({
beforeShowDay: DisableSpecificDates
});
});
I want the array to hold the dates from the database.
You need to fetch data from database and json_encode them
var disableddates = <?php echo json_encode($response)?> ;
You can't write JS code directly in you PHP script.
PHP runs on the server, JS runs on the client.
JS from PHP's point of view is just like HTML.
What you can do, is output this to tag.
Something like ($dates contain the disabled dates):
function outputDatePickerScript($dates) {
echo 'var disableddates = ["' . implode('","', $dates) . '"]';
echo .... // Rest of the JS script
}
Call this function before the end of your HTML Body output.
You have options like
1.to write jquery function in php scipt echo '<script></script' and store the date values in array by select & fetch statement e.g.
/*Your select statement for dates*/
while loop{
$dates .= '"'.$row["date"].'",'
}
$dates = rtrim($dates, ",");
var disableddates = ['.$dates.'];
2> Store db values in a hidden field on front html with an id and pass the value in javascript varaible by selecting id
That's only your js code, show a little of the php too.
if you're not using any fancy ajax you could use something like this:
<?php
$dates = "";
while () { //this while would be your database while
$dates .= '"'.$row["date"].'",';
}
$dates = rtrim($dates, ",");
?>
var disableddates = [<?php echo $dates; ?>];

JSONP - How The Heck Do I Use It?

Been trying to cook up some JSONP to get around Cross Domain issues. Used answer here: Basic example of using .ajax() with JSONP?
$.getJSON("http://example.com/something.json?callback=?", function(result){
//response data are now in the result variable
alert(result);
});
But not getting the desired result. My code:
jquery
var url = "http://wplivestats.com/stats/jsonp.php?callback=?";
$.getJSON(url, function(result){
//response data are now in the result variable
console.log(result);
});
php
<?php
include('init.php');
$pubid = $_REQUEST['pid'];
date_default_timezone_set ( 'America/New_York' );
$time = date('Y-m-d H:i:s',time()-$polling_minutes*60);
$count = $conn->prepare("select distinct ip from stats where timestamp >= '$time' AND Pubid = '$pubid'");
$count->execute();
$users['users'] = $count->rowCount();
echo "jsonCallback ( [";
echo json_encode($users);
echo "] )";
?>
The Error:
ReferenceError: jsonCallback is not defined
jsonCallback ( [{"users":0}] )
Where am I going wrong?
The problem is in your PHP script.
When you do a request using jQuery the question mark in the url will be replaced with a dynamic function name.
On the PHP side you need to use this dynamic function name to wrap your data instead of using "jsonCallback".
Your PHP code should look like this:
echo $_GET['callback'] . "(" . json_encode($users) . ")";

To pass argument from a php file to javascript file

I am facing some trouble in passing a simple variable from a php to javascript file.
I have a form which submits through a php file which basically updates the record at the server end. And if the updation is succesful, I just want to pass the message back to the javascript where I can update it on a certain section of the page.
My codes are:
Javascript code - abc.js
function expand_cards(project, SlNo)
{
name = project['project_name'];
j = "ShowForm-"+SlNo+"";
s = "<div class='edit_project_card'>";
s += "<form method='post' action='Edit_Project.php'><div class='project_form'>
// Form Contents
s += "<div class='Form_button'> <input type='submit'> </div>";
s += "</form></div>";
$("#"+j+"").html(s);
response = $.parseJSON(data);
$("#"+j+"").html(response);
}
PHP file - Edit_Project.php
<?php
//The updation stuff at the server end
if (!mysqli_query($connection,$sqlquery)) {
$response = "'Error in your code: ' . mysqli_error($connection)";
}
else {
$response = "1 record updated";
}
echo json_encode($response);
mysqli_close($connection);
?>
But the problem is the screen is printing $response variable as it is and not exactly passing it back to the javascript function as wished. I know I can use a $.post function which can can receive argument but it's a long form and passing parameters would be difficult in that.
Can anybody help me out here ?
Thanks
Dirty, but it will work:
<script type="text/javascript">
var my_var = <?php echo $some_variable; ?>
// Do something with the new my_var
some_func(my_var);
</script>
I wouldn't do too much detailed stuff with this though, if you can use AJAX that is better.
Note, this can only work on a .php file or one being read as such.
you'll want to do some variable handling in your php side because if the string is empty you'll end up with a
var my_var = ;
which will break the script. so something like:
var my_var = <?php echo "'" . $some_variable . "'";?>
if it's a string or if it's a number:
var my_var = <?php echo (empty($some_variable) ? null : $some_variable);
This is int specific, I'm sure you can come up with a function that will handle it better.
References:
empty function http://php.net/manual/en/function.empty.php
shorthand if http://davidwalsh.name/php-ternary-examples
Since you're submitting the form to the PHP file directly the browser loads the Edit_Project.php file as it would a normal page. If you want a json response to the already loaded page you'll have to use $.post or $.ajax
You can post the whole form simply by using serialize() like this:
$('#form_id').on('submit', function(e) {
// Stop the browser from posting the form
e.preventDefault();
// Post the form via Ajax
$.ajax({
url : 'Edit_Project.php',
type : 'POST',
data : $(this).serialize(),
success : function(response) {
// Here you do the HTML update
$("#"+j+"").html(response.reply);
}
});
});
The Edit_Project.php needs to be changed as well:
//The updation stuff at the server end
if (!mysqli_query($connection,$sqlquery)) {
$response = "'Error in your code: ' . mysqli_error($connection)";
}
else {
$response = "1 record updated";
}
mysqli_close($connection);
/*
* As SuperDJ suggested, you need to tell the browser that it's
* receiving a JSON ojbect although he did use the wrong content type:
*/
header('Content-Type: application/json');
/*
* According to php.net most decoders should handle a simple string as
* json object but to be safe always encode an array or an object since
* you can't know how the decoder will respond.
*/
echo json_encode(array('reply' => $response));

Categories