having issue on Accessing Ajax Post data on PHP - 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.

Related

WordPress ajax returns 404 bad request?

The error is below
POST http://localhost/...../wp-admin/admin-ajax.php 400 (Bad Request)
send # load-scripts.php?c=1…e,utils&ver=4.9.8:4 ajax # load-scripts.php?c=1…e,utils&ver=4.9.8:4 (anonymous) # my-ajax-handler.js?ver=0.1.0:24 i # load-scripts.php?c=1…e,utils&ver=4.9.8:2 fireWith # load-scripts.php?c=1…e,utils&ver=4.9.8:2 ready # load-scripts.php?c=1…e,utils&ver=4.9.8:2
K # load-scripts.php?c=1…e,utils&ver=4.9.8:2
$.ajax({
type: "POST",
url : my_ajax_handler_var.ajaxurl,
data : {
action: 'rc_generate_pa'// "wp_ajax_*" action hook
},
contentType: "application/json; charset=utf-8",
dataType: "json"
,success:function(data) {
//This outputs the result of the ajax request
var pass = JSON.parse( data );
$('#p').val(data);
alert( JSON.parse(data));
},
error: function(errorThrown){
console.log(errorThrown);
}
})
// .done( function( response ) {
// var pass = response;
// $('#p').val(pass);
// })
.fail( function() {
console.log("failed");
});
PHP code for enqueing script and handling request
add_action('admin_enqueue_scripts', 'enqueue_st_page_scripts');
function enqueue_st_page_scripts() {
wp_register_script('my-ajax-handler', $plugin_url .'js/my-ajax-handler.js', array('jquery'), '0.1.0', true );
wp_enqueue_script(array('my-ajax-handler'));
$vars = array('ajaxurl' => admin_url('admin-ajax.php'));
wp_localize_script('my-ajax-handler', 'my_ajax_handler_var', $vars);
}
add_action( 'wp_ajax_rc_generate_pa', 'rc_generate_p' );
function rc_generate_p(){
$pass = (string)wp_generate_password(8, true, false);
echo $pass;
header('Content-Type: application/json');
$results = json_encode($pass);
echo $results;
exit;
}
I have seen similar problems on this site and tried the solution,but no success. I am new to WordPress plugin development.
Main Issue
The problem is in the $.ajax() call, where you should've not set the contentType to JSON:
$.ajax({
url: my_ajax_handler_var.ajaxurl,
contentType: "application/json; charset=utf-8",
...
});
because that way (from the PHP side), the action (i.e. rc_generate_pa) is not available in $_REQUEST['action'] which WordPress uses to determine the AJAX action being called, and when the action is not known, WordPress throws the 400 Bad Request error.
So to fix the error, just remove the contentType property: (or use something other than the JSON type)
$.ajax({
url: my_ajax_handler_var.ajaxurl,
// Don't set contentType
...
});
Second Issue
In your $.ajax()'s success callback, don't use the JSON.parse( data ); and here's why:
When dataType is json, jQuery will automatically parse the response output into a JSON object — or it could also be a string; see point #2 below.
In the (PHP) rc_generate_p() function, the $pass is neither an array nor object/class; hence in the $.ajax()'s success callback, the data is actually an invalid JSON string and JSON.parse( data ) will throw a JavaScript syntax error.
So your $.ajax()'s success could be rewritten into:
success: function(data){
$('#p').val(data);
console.log(typeof data); // test
})
Third Issue
In your rc_generate_p() function, remove the echo $pass;, or you'll get a JavaScript syntax error — your AJAX call is expecting a JSON response, and yet that echo part invalidates the JSON.
I know you probably added that to debug the 400 error; but I thought I should just remind you about removing it.. :)
And you might want to consider using wp_send_json() like so, where you don't need to call exit, die, or wp_die():
function rc_generate_p() {
$pass = wp_generate_password( 8 );
wp_send_json( $pass );
}

unable to get proper data with AngularJS post method

this is my 1st time with AngulerJS. I'm trying to POST data to the server.
AngularJS Code
var app = angular.module("myApp", []);
var BASE_URL = "http://localhost/project/api/Data/";
var GET_DATA = BASE_URL+"get_data";
console.log(GET_DATA);
app.controller('myCtrl', function($scope, $http) {
var inputs = { "user_id": "3"};
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
}
$http.post(GET_DATA , inputs, config)
.success(function (response, status, headers, config) {
$scope.content = response.error;
$scope.statuscode = response.status;
$scope.statustext = response.statusInfo;
console.log(response);
})
.error(function (data, status, header, config) {
$scope.ResponseDetails = "Data: " + data +
"<hr />status: " + status +
"<hr />headers: " + header +
"<hr />config: " + config;
});
});
This code is posting data to the server, but with something wired format. Below is my print_r($_POST); result :
Array
(
[{"user_id":"3"}] =>
[0] =>
)
this is wrong result, I am expecting something like
Array
(
user_id => 3
)
Note : I'm using CodeIgniter framework at server side.
You can send your post data in json:
$http.post(GET_DATA , {"user_id": "3"})
.success(function (response, status, headers, config) {
$scope.content = response.error;
$scope.statuscode = response.status;
$scope.statustext = response.statusInfo;
console.log(response);
})
.error(function (data, status, header, config) {
$scope.ResponseDetails = "Data: " + data +
"<hr />status: " + status +
"<hr />headers: " + header +
"<hr />config: " + config;
});
});
And in the server side you can get the post data like this:
$postdata = json_decode(file_get_contents('php://input'));
print_r($postdata);
You have to encode your data in the post body in urlencoded format when the request content type is application/x-www-form-urlencoded`. Which should be like this:
var inputs = 'student_id=3';
Though it is not the right practice to write answer of old question but I want to post this answer so that others can take help whenever they required.
Firstly, understand the reason why such thing is happening. The reason is, AngularJS doesn’t serialize the data ( parameters ) passed to the POST request automatically. Therefore we have to serialize the data with$httpParamSerializerJQLike which is available as AngularJS Service . Also the default content-type of the posted data is application/json. Therefore we need to override the Content-type headers of the post request to application/x-www-form-urlencoded in order to access the the posted values via $_POST.
Now in angular there is also provided $httpParamSerializer service but the difference $httpParamSerializerJQLike is something object also containing another object so if former is used, then internal object won't be serialized i.e. all nested objects won't be serialized with $httpParamSerializer but it is not the case with $httpParamSerializerJQLike.
You can check the difference here: AngularJS $httpParamSerializer service DOC
Now, rather than json encode and decode data in php, we can do that in Angular JS itself by using $httpParamSerializerJQLike service in angular JS in this way:
$http({
url: myUrl, //post your url here
method: 'POST',
data: $httpParamSerializerJQLike({ 'user_id': '3'}),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
And in codeigniter you can get that posted data by normal syntax i.e. $this->input->post('user_id');
For more information...you can refer the above link mentioned...
Hope it might help you....

How to make an AJAX request and fetch a PHP script on the same page?

For some reason, I need to pass an ID via AJAX to a PHP function on the same page and run a query and return the result back to AJAX which would then append the final result into a div.
As I did some research, I came across this solution, but there are some shortcomings with it.
function1($_GET['id']);**//not getting the id's value**
echo "This is function 1 AND id=".$param;**//this string must be
passed back to the previous ajax request.**
AJAX request (efund.phtml)
$.ajax({
type:'GET',
url:'efund.phtml',
data:"function_to_call=0?id"+cl[3],
success: function(data){
// alert('successful');
}
});
PHP (efund.phtml)
switch ($_GET['function_to_call']) {
case 0:
function1($_GET['id']); // not getting the id's value
break;
case 1:
function2();
break;
default:
break;
}
//And your functions.
function function1($param) {
echo "This is function 1 AND id=".$param; // This string must be passed back to the previous AJAX request.
}
function function2() {
echo "This is function 2";
}
The most common way to communicate between server/client tends to be to use XML or JSON, for your case I recommend you use JSON:
$.ajax({
method: "GET",
url: "efund.phtml",
data: { function_to_call: 0, id: cl[3] }
})
.done(function( msg ) {
var obj = jQuery.parseJSON( msg );
alert( "ID obtained from server is " + obj.id );
});
And then in the server get them using:
$_GET['function_to_call'] // To obtain 'function_to_call' param
$_GET['id'] // To obtain 'id' param
To send information back as response from the server I recommend you, use the same approach and use json_encode for parse an array as JSON and return it using:
in your case for function1 it would be:
function function1($param) {
return json_encode(array ( "id" => $param ) );
}
Also, maybe you should consider if you should use GET or POST for the Http request. You can see more information about it here:
www.w3schools.com/tags/ref_httpmethods.asp
Edit:
If you have problems with the ajax request and you want to check if the ajax request is executed correctly modify the Ajax code like this:
$.ajax({
method: "GET",
url: "efund.phtml",
data: { function_to_call: 0, id: cl[3] }
}).fail(function() {
alert( "error" );
}).always(function() {
alert( "complete" );
}).done(function( msg ) {
var obj = jQuery.parseJSON( msg );
alert( "ID obtained from server is " + obj.id );
});
Change
data:"function_to_call=0?id"+cl[3],
to
data: {function_to_call: 0,id : cl[3]},
in this case data work as object and it is easy to fetch value.
According to your only first condition called every time because you are passing function_to_call=0

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

jQuery/JSON/PHP failing

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;

Categories