JSONP - How The Heck Do I Use It? - javascript

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) . ")";

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();
});

Compare php array to javascript array same data

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.

use a global javascript variable in ajax php mysql

I have a variable 'user_cache' stored in local storage: Now I am doing a $.getJSON call
<script>
user_data = JSON.parse(localStorage.getItem("user_cache"));
$.getJSON("query.php", { productId: productId}, function(data) { /*do something*/});
</script>
Query.php does a php_mysql database query:
<? php
if( $_REQUEST["productId"] )
{
$productid = $_REQUEST['productId'];
/*Database connection*/
include_once("php_includes/db_conx.php");
$sql = "DELETE FROM USERPRODUCTCOLLECTION WHERE Product_ID = $productid";
if ($db_conx->query($sql) === TRUE) {
echo "Success";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$db_conx->close();
}
?>
My question is that I also want to use the object 'user_data' in the query.php file to do that database query but I dont want to pass 'user_data' in $.getJSON. Is it possible to use 'user_data' object inside 'query.php' file without having to pass it in the $.getJSON?
Unfortunately that will not be possible. You must pass the data to the php file in order to utilize it. Are you leaning away from passing the user data because it is passing it as a GET variable (in the URL)? If so, consider using a jQuery.post() call instead. This way the data will be posted instead of in the URL.
See : http://api.jquery.com/jquery.post/

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));

Javascript $.getJSON callback and parameter passing

I currently have a $.getJSON call which is working fine as shown below.
var jsonUrl = "http://www.somesite.co.uk/jsonusv.php?callback=?";
$.getJSON(jsonUrl,function(zippy){
...some code
}
However, I wish to pass a variable with it so that the PHP script can use its $_GET[''] value and tailor the data.
I tired the fooling but could not get things to work any ideas ?
var jsonUrl = "http://www.somesite.co.uk/jsonusv.php?callback=?&value=65";
The php page looks something like this this had been stripped down. I did try to detect the $_GET['value'] but it didn't work.
<?PHP
header("content-type: application/json");
$theSqlquery = "SELECT * FROM table ORDER BY timestamp DESC LIMIT 20";
$result131 = mysql_query($theSqlquery);
if ($result131)
{
//make up Json string in $temp
echo $_GET['callback'] . '(' . $temp . ');';
}
?>
I would suggest removing the callback=? from your jsonUrl
Try passing your parameters into the data parameter of the function call instead of query string:
var jsonUrl = "http://www.somesite.co.uk/jsonusv.php";
$.getJSON(jsonUrl, {
callback: "your callback val",
value: "65",
},
function(zippy){
...some code
});
http://api.jquery.com/jQuery.getJSON/
Then you can access them with $_POST
Note, echo sends the supposed json result back to your $.getJSON() method call, e.g., success() if it was successful. If you know the js method name in the success() method, and only need to pass it $temp, try this
var jsonUrl = "http://www.somesite.co.uk/jsonusv.php";
$.getJSON(jsonUrl, {
value: "65"
},
function(zippy){
callbackMethod(zippy[0]);
});
and in your php
$output = array();
$output[0] = $temp;
echo json_encode($output);
var jsonUrl = "http://www.somesite.co.uk/jsonusv.php?callback=?";
$.getJSON(jsonUrl,{lastdatetime: "",},function(zippy){....
Seems to work ...

Categories