jQuery/JSON/PHP failing - php

I am trying to call a php script that accepts JSON data, writes it into a file and returns simple text response using jQuery/AJAX call.
jQuery code :
$("input.callphp").click(function() {
var url_file = myurl;
$.ajax({type : "POST",
url : url_file,
data : {puzzle: 'Reset!'},
success : function(data){
alert("Success");
alert(data);
},
error : function (jqXHR, textStatus, errorThrown) {
alert("Error: " + textStatus + "<" + errorThrown + ">");
},
dataType : 'text'
});
});
PHP Code :
<?php
$thefile = "new.json"; /* Our filename as defined earlier */
$towrite = $_POST["puzzle"]; /* What we'll write to the file */
$openedfile = fopen($thefile, "w");
fwrite($openedfile, $towrite);
fclose($openedfile);
echo "<br> <br>".$towrite;
?>
However, the call is never a success and always gives an error with an alert "Error : [Object object]".
NOTE
This code works fine. I was trying to perform a cross domain query - I uploaded the files to the same server and it worked.

var url_file = myurl"; // remove `"` from end
Arguments of error function is:
.error( jqXHR, textStatus, errorThrown )
not data,
You can get data (ie. response data from server) as success() function argument.
Like:
success: function(data) {
}
For more info look .ajax()
NOTE
If you're trying to get data from cross-domain (i.e from different domain), then you need jsonp request.

Your data object isn't valid; the key shouldn't be quoted:
data : { puzzle: 'Reset!' }
In addition, SO's syntax highlighting points out that you have missed out a " in your code:
var url_file = myurl";
Should be
var url_file = "myurl;

Related

having issue on Accessing Ajax Post data on PHP

I am having some issue on accessing Ajax Post data on server side. I have
var data = {
ox:'A',
oy:'B',
dx:'C',
dy:'D',
method:null
};
I have a jQuery event hamdler like
$("#route").on("click", function(){
var request = $.ajax({
type: "POST",
url: "assets/app.php",
data: data,
cache: false,
dataType: "JSON",
beforeSend: function() {
console.log(data);
}
});
request.done(function( data ) {
console.log(data);
});
request.fail(function( jqXHR, textStatus ) {
console.log( "Request failed: " + textStatus );
});
});
I am able to send the data correctly as it is logging out at beforeSend
{ox: A, oy: B, dx: C, dy: D, method: null}
On PHP side I have
$method = $_POST['method'];
$ox = $_POST['ox'];
$oy = $_POST['oy'];
$dx = $_POST['dx'];
$dy = $_POST['dy'];
now only accessing to one of the $_POST[] data is working like echo $ox; but when I try to access all $_POST[] data like
echo $ox;
echo $dy;
$startPoint = array($ox, $oy);
$endPoint = array($dx, $dy);
I am getting Request failed: parsererror error on .fail()
From the docs:
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:
So, your response isn't a valid JSON.
What you can do is to create an array, like you are doing:
$startPoint = array($ox, $oy);
$endPoint = array($dx, $dy);
Then encode into json and echo it
echo json_encode(['startPoint' => $startPoint, 'endPoint' => $endPoint]);
On the frontend (javascript) you will get and JSON like
{
'startPoint' : ['ox','oy'],
'endPoint' : ['dx','dy'],
}
the values of ox, oy, dx and dy, of course, will be the values sent before.

Ajax Internal Error, jqXHR: underfined

Ive butchered my code trying to find this bug. I have a Ajax post function working elsewhere on my code and it works fine.
For some reason this one does not want to cooperate.
Im going to reduce the amount of inputs so the code doesnt look too long.
Here is the php
<?php
// --------Connect to DB --->
include 'connect.php';
$conn = connect ();
//====================================================================>
//grab data
$this_id = $_POST('pid_num');
$this_start_date = $_POST('date_ammend');
$sql_update_query = "UPDATE Galaxy_jobs SET date ='$this_start_date' WHERE PID = $this_id";
//====================================================================>
mysqli_query ($conn,$sql_update_query);
//close
mysqli_close($conn);
?>
Here is my Ajax call.
function ammend_job()
{
pid = '2'; // test figures
start_date_ammended = '11-11-1111'; // test figures
var Data = {
pid_num : pid,
date_ammend : start_date_ammended,
};
$.ajax({
url:"ammend_job.php",
type: "POST",
dataType: 'text',
data: Data,
success: function(data){
if(data.status == 'success')
alert('Post has been uploaded to Database');
},
error: function(xhr,textStatus,err,jqXHR) {
console.log("readyState: " + xhr.readyState);
console.log("responseText: "+ xhr.responseText);
console.log("status: " + xhr.status);
console.log("text status: " + textStatus);
console.log("error: " + err);
console.log("Jquery error:" + jqXHR)
// alert('There is an error, screenshot this error and send to Admin : TextStatus: ' +textStatus+" - Error: "+errorThrown+" - XMLRequest: "+XMLHttpRequest+"- Response Text"+xhr.responseText);
}
});
}
Here are the error codes :
main.php:102 readyState: 4
main.php:103 responseText:
main.php:104 status: 500
main.php:105 text status: error
main.php:106 error: Internal Server Error
main.php:107 Jquery error:undefined
Any help will be greatly appreciated.
It took a while.
I wouldnt have found it if it wasnt for user : tereško who suggested to look closely at the errorlog on the server.
I found that when I replaced my code in php file
//grab data
$this_id = $_POST('pid_num');
$this_start_date = $_POST('date_ammend');
with the square brackets
//grab data
$this_id = $_POST['pid_num'];
$this_start_date = $_POST['date_ammend'];
The code didnt throw an error and worked.
I hope somebody else out there finds this post and figures out that this may be 1 reason for their error.

$.getjson data is not working, I have parseerror for textstatus

I have two files
Search.php is file 1, and it is finishing as below 2 lines of code
header("Content-type: application/json");
print(json_encode($places, JSON_PRETTY_PRINT));
file 2 is search function inside Javacript extension and I am using $.getjson to get those above JSON data my code is as follow
function search(query, cb)
{
// get places matching query (asynchronously)
var parameters = {
geo: query
};
$.getJSON("search.php", parameters)
.done(function(data, textStatus, jqXHR) {
// call typeahead's callback with search results (i.e., places)
cb(data);
console.log("bill");
})
.fail(function(jqXHR, textStatus, errorThrown) {
// log error to browser's console
console.log("mistake is: " + textStatus);
console.log("incoming Text " + jqXHR.responseText);
});
}
I am unable to get JSON data through .done, search function always fail.
Console.log shows parseerror for textstatus.
Anyone to help me to figure out why search function isn't working? Thanks!

$.getJSON seems to return as literal string with nested objects

Hello I am new to JSON and have run into some issues.
I am requesting some information using jquery's $.getJSON method like so:
function getPlayerPositions(type) { //left/top/move
var loadUrl = "../php/client_communication/relay_positions.php";
var playerPos = [];
$.ajaxSetup ({
cache: false,
async: false
});
$.getJSON( loadUrl, { type: type } )
.done(function( data ) {
useReturnData(data);
})
.fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ', ' + error;
console.log( "Request Failed: " + err);
});
function useReturnData(data){
playerPos = data;
alert("response: "+playerPos);
};
//reset to asynchronous ajax from now on
$.ajaxSetup ({
async: true
});
alert(playerPos[0]);
return playerPos;
}
And when my function is ran previously to this time I receive the correct JSON encoded data that I can then access via my "playerPos" array. (ie. alert(playerPos[4]))
But this time I am receiving data that contains multiple nested objects:
This is the ajax response alerted:
response: [{"Position":"LB","ID":" 2","x-offset":" 0","y-offset":" 0","Stats":{"ID":"2","IMG":"/images/player_avatars/player_test.png","First_Name":"Daniel","Surname":"Vernall","Nickname":"Tall Tree","number":"25","Fav_Pos_1":"LB","Fav_Pos_2":"CB","team":"A","SPEED":"100","AGILITY":"100","STRENGTH":"100","JUMP":"100","MARKING":"100","STAMINA":"100","LEADERSHIP":"100","ADAPTABILITY":"100","RESTRAINT":"100","INJURY_PRONE":"100","HEAL_TIME":"100","MORALE":"100","AGGRESSIVENESS":"100","PASSING":"100","SHOOTING_ACCURACY":"100","SHOOTING_POWER":"100","HEADING":"100","MISC_BODY":"100","POSITIONING":"100","FIRST_TOUCH":"100","LONG_DISTANCE":"100","STRONG_FOOT":"0","CONTROL":"100","CURLING":"100","CHIPPING":"100","VOLLEYING":"100","SET_PIECES":"100","THROW_INS":"100","REFLEXES":"100","ONE_ON_ONES":"100","AERIAL_ABILITY":"100","CATCHING":"100","COORDINATION":"100","THROWING":"100","coordX":0,"coordY":0,"yellowCards":0,"redCards":0,"shotsOnTarget":0,"shotsOffTarget":0,"goals":0,"assists":0,"completedPasses":0,"incompletePasses":0,"tackles":0,"timesTackled":0,"intercepts":0,"intercepted":0,"badReceive":0}},{"Position":"LCB","ID":" 3","x-offset":" 0","y-offset":" 0","Stats":{"ID":"3","IMG":"/images/player_avatars/player_test.png","First_Name":"Teddy","Surname":"Vernall","Nickname":"Bear","number":"11","Fav_Pos_1":"ST","Fav_Pos_2":"CAM","team":"A","SPEED":"100","AGILITY":"100","STRENGTH":"100","JUMP":"100","MARKING":"100","STAMINA":"100","LEADERSHIP":"100","ADAPTABILITY":"100","REST...,"SET_PIECES":"100","THROW_INS":"100","REFLEXES":"100","ONE_ON_ONES":"100","AERIAL_ABILITY":"100","CATCHING":"100","COORDINATION":"100","THROWING":"100","coordX":0,"coordY":0,"yellowCards":0,"redCards":0,"shotsOnTarget":0,"shotsOffTarget":0,"goals":0,"assists":0,"completedPasses":0,"incompletePasses":0,"tackles":0,"timesTackled":0,"intercepts":0,"intercepted":0,"badReceive":0}},{"Position":"GK","ID":" 12","x-offset":" 0","y-offset":" 0","Stats":{"ID":"12","IMG":"/images/player_avatars/player_test.png","First_Name":"Rumple","Surname":"Stiltskin","Nickname":"Rumpy Pump Stink","number":"29","Fav_Pos_1":"CDM","Fav_Pos_2":"LB","team":"A","SPEED":"100","AGILITY":"100","STRENGTH":"100","JUMP":"100","MARKING":"100","STAMINA":"100","LEADERSHIP":"100","ADAPTABILITY":"100","RESTRAINT":"100","INJURY_PRONE":"100","HEAL_TIME":"100","MORALE":"100","AGGRESSIVENESS":"100","PASSING":"100","SHOOTING_ACCURACY":"100","SHOOTING_POWER":"100","HEADING":"100","MISC_BODY":"100","POSITIONING":"100","FIRST_TOUCH":"100","LONG_DISTANCE":"100","STRONG_FOOT":"50","CONTROL":"100","CURLING":"100","CHIPPING":"100","VOLLEYING":"100","SET_PIECES":"100","THROW_INS":"100","REFLEXES":"100","ONE_ON_ONES":"100","AERIAL_ABILITY":"100","CATCHING":"100","COORDINATION":"100","THROWING":"100","coordX":0,"coordY":0,"yellowCards":0,"redCards":0,"shotsOnTarget":0,"shotsOffTarget":0,"goals":0,"assists":0,"completedPasses":0,"incompletePasses":0,"tackles":0,"timesTackled":0,"intercepts":0,"intercepted":0,"badReceive":0}}]
Javascript seems to not view these as individual objects:
When alerting playerPos[4] for example it will simply alert the 4th character in the string above.
I realise the above is very difficult to read but I wanted to show you an actual copy of the alert.
This is the bit from the php file it accesses:
if($type=="db_request"){
$team = new Team;
$team = $team->buildTeam(101, 'A');
ChromePhp::log($team);
$response = json_encode($team);
}
And my log above looks like this:
So you can see that the php file views "$team" as containing multiple nested objects
Any ideas?
Seems like you're double-encoding the object (with something like echo json_encode($response);). jQuery would then parse the JSON-encoded string to the JSON-encoded object string…
You can check for such serverside failure by inspecting the effective HTTP response in your browser's network inspector (Chrome devtools, Opera Dragonfly, Firebug).
"Stats":{
"ID":"3",
"IMG":"/images/player_avatars/player_test.png",
"First_Name":"Teddy",
"Surname":"Vernall",
"Nickname":"Bear",
"number":"11",
"Fav_Pos_1":"ST",
"Fav_Pos_2":"CAM",
"team":"A",
"SPEED":"100",
"AGILITY":"100",
"STRENGTH":"100",
"JUMP":"100",
"MARKING":"100",
"STAMINA":"100",
"LEADERSHIP":"100",
"ADAPTABILITY":"100",
"REST...,"SET_PIECES":"100",
"THROW_INS":"100",
"REFLEXES":"100",
"ONE_ON_ONES":"100",
"AERIAL_ABILITY":"100",
"CATCHING":"100",
"COORDINATION":"100",
"THROWING":"100",
"coordX":0,
"coordY":0,
"yellowCards":0,
"redCards":0,
"shotsOnTarget":0,
"shotsOffTarget":0,
"goals":0,
"assists":0,
"completedPasses":0,
"incompletePasses":0,
"tackles":0,
"timesTackled":0,
"intercepts":0,
"intercepted":0,
"badReceive":0
}
see the SyntaxError: Unexpected token S
Your SET_PIECES has broken out of the json making it invalid.
I know this is already answered but I noticed a few performance tips that may help quiet a bit. Avoiding nested functions when at all possible really can help speed up the application.
function getPlayerPositions(type) { //left/top/move
var loadUrl = "../php/client_communication/relay_positions.php";
var playerPos = [];
$.ajax( loadUrl, { type: type, async: false, cache: false, dataType: "json" } )
.done(function( data ) {
playerPos = data;
alert("response: "+playerPos);
})
.fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ', ' + error;
console.log( "Request Failed: " + err);
});
alert(playerPos[0]);
return playerPos;
}
More info here

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