Javascript $.getJSON callback and parameter passing - javascript

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 ...

Related

ajax get empty array from json_encode()

So I have this php class where i have a function that get users from a PSQL database but the AJAX keep loging empty array in the console:
public function getUsers(){
$query = pg_query(self::$DBH, "select id, name, email, admin from users order by name;");
$result = array();
$i = 0;
while ($row = pg_fetch_row($query)) {
$result[$i] = $row;
$i++;
}
return $result;
}
I use a phphandler file to call the function from ajax
:
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/bdd.php';
require_once 'modele_backend.php';
$module = new Modele_Backend();
echo json_encode($module -> getUsers());
?>
and finaly there is the AJAX call
$(document).ready(function(){
$("#user_email").on("input", function(){
// Print entered value in a div box
$.ajax({
url: 'modules/mod_backend/backendHandler.php',
type: 'post',
dataType: 'json',
success: function(response) { console.log(response); }
});
});
});
The problem is that js keep showing empty array in the console.
The json_encode works fine as json_last_error = 0.
I Tried replacing the return of my getUsers() function by
echo json_encode($result);
to test if the function manage to encode my array and it did show up like a JSON on the page so this is not a encoding of my array problem. Still when AJAX get the result of the json_encode function it display an empty array.
Thanks for any help !
Necro.
Solution 1
You have to set content type of header in your php file before echo
header('Content-type: application/json');
Solution 2
change dataType in your ajax code to html
or remove it to return default dataType (default: Intelligent Guess (xml, json, script, or html))
and then convert returned string to json using javascript JSON.parse() method .
It turned ou the problem was not json_encode at all, it was a problem with my static DB class wich I was includong twice with the AJAX call.
Thanks anyway for the support

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

how to use javascript variable in php inside a javascript function

i am trying to fetch JavaScript variable "i" in my PHP Code within a JavaScript function in the below code, I find problem in retrieving records, either first record or the last record repeats instead of all records in database.. can you guys help me out ?
Thanks
<?php
$query21 = $mysqli->query("SELECT * FROM register");
$nr = mysqli_num_rows($query21);
while ($row = mysqli_fetch_assoc($query21)) {
$results[] = $row;
}
?>
<script language="javascript" type="text/javascript">
var intervalID = 0;
var time = 10;
MsgPop.displaySmall = true;
MsgPop.position = "bottom-right";
$(document).ready(function(){
var test = MsgPop.open({
Type: "success",
AutoClose: true,
Content: "Welcome to MsgPop!"});
MsgPop.live();
});
function showMessages(){
var n = '<?php
echo $nr;
?>';
var i = 0;
while (i < n){
var name = '<?php
echo $results[i]['name'];
?>';
MsgPop.open({
Type: "success",
Content: name,
AutoClose: false});
i++;
}
</script>
First you have to create a php file which return same array. File contain
$query21 = $mysqli->query("SELECT * FROM register");
$nr = mysqli_num_rows($query21);
while ($row = mysqli_fetch_assoc($query21)) {
$results[] = $row;
}
echo json_encode($results);
exit;
Now you have to call this file using ajax from your javascript code.
$.ajax({
type: "POST",
url: "sql.php", //your file url
})
.done(function (data) {
//you get your array data(json format)
});
now you get that array in ajax response in json format and you can do anything with this data.
Impossible: PHP is a server side language that runs only at server. but javascript is a client side script it only run at your browser only. Php only gives response depends on your requests. The roll of php is end at server. But the javascript work with your response only, that is javascript can work at browser only.
You could try using AJAX, or else it isn't happening. Like said PHP is server-side only... Good luck!
PHP cannot fetch javascript variables. You should try another strategy.
At the server side (PHP), try to store $resuts in a javascript variable.
var results = '<?php echo json_encode($results); ?>';
Then at the browser side, try to access the data with javascript functions.
var name = results[i]['name'];

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