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