Use Jquery AJAX to get PHP Object - php

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

Related

Trying to extract information throught a PHP file Undefined

I'm trying to extract the information with a XHR request (AJAX) to a php file (this php file gets the information throught json file with Get request too) so when I try to do console.log(Checker) on the console, it returns Undefined and if I put alert(Checker) it returns [object Object]. How can I solve it?
PHP:
<?php
headers('Content-Type', 'application/json')
$jsonContents = file_get_contents('../data/data.json');
echo $jsonContents
?>
JS:
function start() {
$.ajax({
type: 'GET',
url: 'api/domain/showall.php',
dataType: 'json',
success: function(data) {
alert(data)
displayTheData(data)
}
});
}
function displayTheData(data) {
Checker = data;
JSON.stringify(Checker)
console.log(Checker)
window.Checker = Checker;
}
JSON:
[{"name":"Google","url":"google.es","id":1}]
Here you are strigify data but not store value i any var.
function displayTheData(data) {
Checker = data;
var displayChecker = JSON.stringify(Checker) /// add displayChecker
console.log(displayChecker ) // print it
window.Checker = Checker;
}
There is not displayTheData() function so first call it and pass response params.
You need to echo the JSON Response ! Change return $jsonContents; to echo $jsonContents; it will work !!!
You must parse data into body (not returning it which has no meaning outside a function) and, optionnaly but much better, fill some headers. A very minimalistic approach could be :
<?php
headers('Content-Type', 'application/json');
$jsonContents = file_get_contents('../data/data.json');
echo $jsonContents // echo JSON string
?>

$_POST is empty even though I can see the $_POST data in firebug post, html, and response tabs

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

How to pass HTML via JSON from PHP to AJAX - properly

I'm still in AJAX stuff since morning so maybe thats the reason why some things does't work as they schould - let's forget about it. To sum up, my problem is coincident with passing HTML via JSON. An example of the PHP code:
$list = "<strong>This is test</strong>";
$response = array('success'=>true, 'src' => $list);
echo json_encode($response);
Basicly that's the main part of the code which is responsible for passing the HTML to AJAX. Now, let's have a look on part of AJAX code:
success: function(output)
{
alert(output);
json = $(output).find(".content").text();
var data = $.parseJSON(json);
if(data.success == true)
{
obj_a.parents(".row").append(data.src);
obj_a.attr("id", "rollBack");
obj_a.text("Roll back");
}
},
Some of you will ask what am I doing in this part:
json = $(output).find(".content").text();
The answer is: I retrieve the json string from the ".content" box, so when I alert variable "json: i get:
{"success":true,"src":"1. dsfasdfasdffbcvbcvb<\/span>Edytuj<\/span> <\/a>Usu \u0144<\/span><\/div>2. vbnvbnm454t<\/span>Edytuj<\/span><\/a>Usu\u0144<\/span><\/div>3. ndfhgndgfhndfhgndfhd<\/span>Edytuj<\/span><\/a>Usu\u0144<\/span><\/div><\/div>"}
The problem is that I do not get this HTML... I get only text witout any HTML tags, styles etc...
String which I get, rather than HTML:
"1. dsfasdfasdffbcvbcvbEdytujUsuń2. vbnvbnm454tEdytujUsuń3. ndfhgndgfhndfhgndfhdEdytujUsuń"
Please don't try to look for anything smart or gunius in the above string because u won't - it's only a test string.
Acording to the part of PHP code - in my case I get "This is test" rather than "This is test".
To sum up my question is, how to pass these HTML tags or whole HTML code via json from PHP to AJAX.
I think you're misunderstanding how jQuery.ajax() works. You just need to tell it that dataType: 'json' (meaning that you're expecting JSON output from the server), and it takes care of the rest. You don't need to use jQuery.parseJSON(). The success() method will be given a JavaScript object representing the server response.
success: function(output)
{
// output is a JS object here:
alert(output.success); // true
// ...
},
To get your HTML from that point, you would just access output.src.
You can specify dataType: 'json' in your ajax request and receive an object(i.e. json already parsed) in your success call. eg
$.ajax(url, {
dataType: 'json',
success: function(output)
{
if(output.success == true)
{
obj_a.parents(".row").append(output.src);
obj_a.attr("id", "rollBack");
obj_a.text("Roll back");
}
},
if you can't change dataType you would call $.parseJSON on output
function(output)
{
alert(output);
var data = $.parseJSON(output);
if(data.success == true)
{
obj_a.parents(".row").append(data.src);
obj_a.attr("id", "rollBack");
obj_a.text("Roll back");
}
},

How can I access my PHP variables when calling ajax in jQuery?

I am attempting to create a simple comment reply to posts on a forum using the AJAX function in jQuery. The code is as follows:
$.ajax({type:"POST", url:"./pages/submit.php", data:"comment="+ textarea +"& thread="+ currentId, cache:false, timeout:10000,
success: function(msg) {
// Request has been successfully submitted
alert("Success " + msg);
},
error: function(msg) {
// An error occurred, do something about it
alert("Failed " + msg);
},
complete: function() {
// We're all done so do any cleaning up - turn off spinner animation etc.
// alert("Complete");
}
});
Inside the submit.php file I have this simple if->then:
if(System::$LoggedIn == true)
{
echo "Yes";
} else {
echo "No";
}
This call works on all other pages I use on the site, but I cannot access any of my variables via the AJAX function. I've tested everything more than once and I can echo back whatever, but anytime I try to access my other PHP variables or functions I just get this error:
Failed [object XMLHttpRequest]
Why am I unable to access my other functions/variables? I must submit the data sent into a database inside submit.php using my already made $mySQL variable, for example. Again these functions/variables can be accessed anywhere else except when I call it using this AJAX function. After hours of Googling I'm just spent. Can anyone shed some light on this for me? Many thanks.
The PHP script that you have only returns a single variable. Write another script that that returns JSON or if you are feeling brave XML. below is a quick example using JSON.
In your javascript
$.ajax({
type: 'GET'
,url: '../pages/my_vars.php'
,dataType: 'json'
,success: function(data){
// or console.log(data) if you have FireBug
alert(data.foo);
}
});
Then in the php script.
// make an array or stdClass
$array = array(
'foo' => 'I am a php variable'
,'bar' => '... So am I'
);
// Encodes the array into JSON
echo json_encode($array);
First thing, you have a space in the Data Parameter String for the URL - will cause problems.
Secondly, your success and error functions are referencing a variable msg. It seems you are expecting that variable to be a string. So, the question then becomes - What is the format of the output your PHP script at submit.php is producing?
A quick read of the jQuery API suggests that, if the format of the response is just text, the content should be accessible using the .responseText property of the response. This is also inline with the response you say you are getting which states "Failed [object XMLHttpRequest]" (as you are trying to turn an XHR into a String when using it in an alert.
Try this:
$.ajax( {
type: "POST" ,
url: "./pages/submit.php" ,
data: "comment="+ textarea +"&thread="+ currentId ,
cache: false ,
timeout: 10000 ,
success: function( msg ) {
// Request has been successfully submitted
alert( "Success " + msg.responseText );
} ,
error: function( msg ) {
// An error occurred, do something about it
alert( "Failed " + msg.responseText );
} ,
complete: function() {
// We're all done so do any cleaning up - turn off spinner animation etc.
// alert( "Complete" );
}
} );

JSON data response from PHP server is empty

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

Categories