I have a method I'm trying to write that can post data to a php file and get the results and return the output in a variable. For some reason, my block of code is not working.
function post_get(){
var result = null;
$.post("modules/data.php", { "func": "getNameAndTime" },
function(data){
result = JSON.parse(data);
}, "json");
return result;
}
I get this error when using this method
SyntaxError: JSON Parse error: Unexpected identifier "undefined"
Ajax is Asynchronous.
Is your PHP returning valid JSON?
This is how your code should be written to take advantage of the asynchronous nature of ajax.
function post_get(){
return $.post("modules/data.php", { "func": "getNameAndTime" }, "json");
}
post_get().done(function(data){
// do stuff with data
console.log(data);
}).fail(function(){
console.log(arguments);
alert("FAIL.\nCheck the console.");
});
// Do not attempt to bring data from inside the above function to out here.
If your server returns proper JSON encoded output and sets the correct headers (Content-Type: application/json), you can use data immediately:
$.post("modules/data.php", {
"func": "getNameAndTime"
},
function(data){
console.log(data);
}, "json");
// btw, at this point in the code you won't have access to the return value
In fact, even if it didn't return proper data, the console.log(data) should provide you with enough information to figure out why it wasn't working in the first place.
Related
To try and be as short and sweet, yet as descriptive as possible i am having issues grabbing a PHP Object through Jquery Ajax.
I am a semi-new PHP developer and i have created an object containing some strings and variables as shown here:
calculation.php
$return = new stdClass;
$return->success = true;
$return->errorMessage = "Oops, something went wrong!";
$return->Score = number_format($scoreFromSheet,1);
$return->roi = number_format($roiFromSheet,1);
$return->dvScoreAnalysis = $scoreAnalysis;
$return->className = $className;
$json = json_encode($return);
echo $json;
I have constructed a very crude Ajax call to the PHP file to try to access the json_encoded object. As shown here:
finalPage.php
$(document).ready(function(){
var data;
$.ajax({
dataType: "json",
url: './dvs_calculation/calculation.php',
data: {data:data},
success: function (json) {
alert('working');
console.log(json[0].Score);
},
error: function(xhr, textStatus, errorThrown) {
alert( "Request failed: " + textStatus );
}
});
});
I have echo'd the object to the DOM to display the output of my object, and it looks pretty solid:
$json output
{
"success":true,
"errorMessage":"Oops, something must've gone wrong!",
"Score":"65.5",
"roi":"25.8",
"ScoreAnalysis":"High Deal Viability"
}
When using the Ajax function i receive a parse error and it prints out nothing from the success function. Not sure where i am going wrong. Any help or reference greatly appreciated.
Access the Score value from the json response as
json.Score //gives you the value of Score key from json
Also according to the code provided, you aren't passing anything to the php side as the data variable is just defined
So I'm grabbing the state of a jquery date picker and a dropdown select menu and trying to send those two variables to another php file using AJAX.
var_dump($_POST);
results in this on the webpage:
array(0) {
}
BUT, when I look at the Net panel in Firebug, I can see the POST and GET urls and it shows the Post, Response, and HTML all showing the variables that I sent to the PHP file, but when dumping, it shows nothing on the page.
I've been looking through other similar issues on SO that has led me to changing the php.ini file to increase the post size and to updating my ajax call to use json objects and then parse through it on the php side.
Currently I'm just trying to get passing a string to work, and my code looks like this:
AJAX:
$("#submit_button").click(function() {
// get date if selected
var selected_date = $("#datepicker").datepicker("getDate");
// get show id if selected
var selected_dj = $("#show-list").val();
// put the variables into a json object
var json = {demo : 'this is just a simple json object'};
// convert to json
var post_data = JSON.stringify(json);
// now put in variable for posting
var post_array = {json : post_data};
$.ajax({
type: "POST",
url: template_dir + "/get-show-logs.php",
data: post_array,
success: function(){
alert("Query Submitted");
},
error: function(xhr, ajaxOptions, thrownError){
alert(xhr.status);
alert(thrownError);
}
});
// clear div to make room for new query
$("#archived-posts-container").empty();
// now load with data
$("#archived-posts-container").load(template_dir + "/get-show-logs.php #get_logs");
});
Now this is the php that's running from the .load() call, and where I'm trying to access the $_POST variables:
get-show-logs.PHP:
<div id="get_logs">
<?php
if(isset($_POST["json"])){
$json = stripslashes($_POST["json"]);
$output = json_decode($json);
echo "im here";
var_dump($output);
// Now you can access your php object like so
// $output[0]->variable-name
}
var_dump(getRealPOST());
function getRealPOST() {
$pairs = explode("&", file_get_contents("php://input"));
$vars = array();
foreach ($pairs as $pair) {
$nv = explode("=", $pair);
$name = urldecode($nv[0]);
$value = urldecode($nv[1]);
$vars[$name] = $value;
}
return $vars;
}
?>
</div>
You can see that I'm trying just accessing the $_POST variable, and the isset check isn't passing, (the page isn't echoing "im here"), and then I'm also trying parsing through the input myself, and that is also empty.
the output on the page looks like this:
array(1){[""]=>string(0)""}
BUT, once again, the Firebug Net panel shows the following under the Response tab:
<div id="get_logs">
im hereobject(stdClass)#1 (1) {
["demo"]=>
string(33) "this is just a simple json object"
}
array(1) {
["json"]=>
string(44) "{"demo":"this is just a simple json object"}"
}
</div>
I'm not sure what could be causing the issue, the Firebug can see it, but the php file sees an empty array.
Now I'm very new at using ajax and $_POST and such, so if you read anything that you're not 100% sure about, don't assume that I know anything about it! Speak up! haha.
Also, I'm doing this with MAMP on Localhost, so I'm not sure if that leads to any issues.
Thanks for the help in advance!
You aren't using the response in your AJAX call currently. See this example which will output the returned response to the console.
$.ajax({
type: "POST",
url: template_dir + "/get-show-logs.php",
data: post_array,
success: function(response){
console.log(response);
},
error: function(xhr, ajaxOptions, thrownError){
alert(xhr.status);
alert(thrownError);
}
});
Success
Type: Function( Anything data, String textStatus, jqXHR jqXHR )
A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter or the dataFilter callback function, if specified; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object.
-http://api.jquery.com/jquery.ajax/
Also this might be a good page to read more about jQuery and AJAX, https://learn.jquery.com/ajax/jquery-ajax-methods/.
So, I am using jquery to make an ajax call to a php script on my server.
For some reason I cannot figure out, however, there is no querystring sent. Using var_dump() on the $_GET object shows that it is an empty string, and Chrome's network activity developer tool indicates no string is sent.
$.ajax({
"url":"../script/content.php",
"settings": {
"dataType":"html",
"type":"GET",
"data":{
"id":$(this).prop('id')
}
}
}).done( function(msg) {
//$('#debug').html(msg);
$('#dialog').html(msg);
$('#dialog').load(function() {
$('#close').click(function() {
$('#over').fadeOut(fadeTime);
});
if ($('#unique') > 0) {
$('#unique').load(function(){
$('#over').fadeIn(fadeTime);
});
}
else {
$('#over').fadeIn(fadeTime);
}
});
});
I had tried the ajax call without the quotes where they weren't necessary before hand, and the result was the same... I just put those in because I thought it might be the problem... though I think that in such notation the quotes don't make a difference unless one of the field values is supposed to be a string.
Is there anything clear in that code which might cause a querystring not to be sent? I guess there is a problem with my syntax... I just can't see it.
The #dialog load callback seems to never be called, either... but I guess that is another question.
Try this
$.ajax({
//The link we are accessing with params
url:'http://example.com/script/content.php'
+ '?id='
+ $(this).prop('id'),
// The type of request.
type: "get",
//The type of data that is getting returned.
dataType: "html",
error: function(){
//something here
},
success: function( strData ){
//something here
}
});
There have been some post with my similar problem: How do I iterate over a JSON array using jQuery/AJAX call from PHP? but not quite the same.
I'm getting and error from jquery:
a is null
It is because of the code I've added to loop through the json data:
$(function ()
{
$.ajax({
url: 'ajax_dashboard/api.php', //the script to call to get data
data: "",
dataType: 'json',
success: function(data)
{
$.each(data, function() {
$.each(this, function(k, v) {
$('#output').append("<b>key: </b>"+k+"<b> value: </b>"+v)
.append("<hr />");
});
});
}
});
});
And here is the php file (which I did verify gives valid JSON format):
$query_camera_name = "SELECT camera_name, camera_status, camera_quality, email_notice, camera_hash, camera_type FROM #__cameras WHERE user_id=".$user->id." AND camera_status!='DELETED'";
$db->setQuery($query_camera_name);
//get number of cameras so we can build the table accordingly
$db->query();
$num_rows = $db->getNumRows();
// We can use array names with loadAssocList.
$result_cameras = $db->loadAssocList();
echo json_encode($result_cameras);
?>
This returns this json formatted data:
[
{
"camera_name": "ffgg",
"camera_status": "DISABLED",
"camera_quality": "MEDIUM",
"email_notice": "DISABLED",
"camera_hash": "0d5a57cb75608202e64b834efd6a4667a71f6dee",
"camera_type": "WEBCAM"
},
{
"camera_name": "test",
"camera_status": "ENABLED",
"camera_quality": "HIGH",
"email_notice": "ENABLED",
"camera_hash": "6ab000ef7926b4a182f0f864a0d443fc19a29fdd",
"camera_type": "WEBCAM"
}
]
If I remove the loops the "a is null" error is gone. What am I doing wrong?
Your iteration code works just fine: http://jsfiddle.net/SuyMj/
The error is elsewhere.
Edit:
Try this to help debug.
success: function(data, textStatus, xhr) {
console.log(xhr);
...
}
xhr will contain a lot of information about the request being made. What does the responseText contain? What is the statusText?
Your code works fine:
http://jsfiddle.net/QSvNy/
So the error is not there.
I don't see that you set the Content-Type of your response from php. Possibly the mime type of your response is incorrect and so jQuery does not parse the response as json.
Try this in your php before you echo your json:
header('Content-Type: application/json');
I'm having a hard time figuring this one out. Seems like no matter what I try, PHP always ends up returning an empty array. Here's the code of my main file(index.php):
<script language="javascript" type="text/javascript">
$(document).ready(function(){
$(".ajaxlink").click(function() {
callServer();
return false; //Stop link from redirecting
});
});
var test = { "testName": "testValue" }
var testJSON = JSON.stringify(test);
function updatePage(data) {
document.getElementById("testDiv").innerHTML = data;
}
function callServer() {
$.ajax({
type: "POST",
url: "ajax/server.php",
data: testJSON,
success: function(data) {
updatePage(data);
},
//Upon error, output message containing a little info on what went wrong
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('An Ajax error occured\ntextStatus = ' + textStatus + '\nerrorThrown = ' + errorThrown + '\nstatus = ' + XMLHttpRequest.status);
}
});
}
</script>
<div id="testDiv">Something here</div>
Link! <br>
This basically runs the callServer() function when you click the "Link!". It then sends the test json data, that is { "testName": "testValue" } to server.php. Firebug reports that the json-data is indeed sent to the server.php.
My server.php looks like this:
<?php
print_r($_POST);
?>
This returns the following in the testDiv:
Array
(
)
The datatype in the .ajax function is not defined, so whatever output the server.php file spits out, it should be readable. All the necessary libraries(json, jquery) are included in my document as well. I'm running this on Apache 2.2 and PHP 5.3.1, but it shows the same on my webserver (which is a host for thousands of websites). The content-type used in the request-header is 'application/x-www-form-urlencoded; charset=UTF-8' so that should work correctly.
Thanks for your time.
Best regards
soren
I think you send the data in a wrong way. Either you send a string like testName=testValue or you assign the value in test directly to the data parameter of .ajax() and don't use the stringify method.
Because, if you use stringify, the actual sent data will be (I assume, I am not sure here):
'{ "testName": "testValue" }'
but this is not a valid parameter string.
It should be of form
'testName=testValue'
So use test directly, .ajax() will convert the object into an appropriate string:
function callServer() {
$.ajax({
type: "POST",
url: "ajax/server.php",
data: test,
success: function(data) {
updatePage(data);
},
//Upon error, output message containing a little info on what went wrong
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('An Ajax error occured\ntextStatus = ' + textStatus + '\nerrorThrown = ' + errorThrown + '\nstatus = ' + XMLHttpRequest.status);
}
});
}
I'm not sure your output from your PHP script is JSON formatted.
If you're using a newer version of PHP (which you are) you'll have access to the json_encode and json_decode functions. Instead of doing:
print_r($_POST);
Try:
print json_encode($_POST);
If your version of PHP doesn't have these functions you can use a library such as the Zend_Json class in the Zend Framework, in order to encode your PHP variables as JSON before outputting them.
And when it comes back, it'll be a JSON-formatted string. Setting the dataType in your jQuery.ajax call should evaluate it to a JS object. If not you would either have to call the Javascript eval function on it, or (preferably) use JSON.parse(data).
Use firefox and Live Http Headers extension.
With this you'll be able to see exactly where the problem lies,
Php or Js code.
live http headers