Unable to read POST'd data using $.ajax - javascript

I have a super simple JS code that POSTs to my local server. Both JS and PHP are on localhost so I'm not worrying about cross site issues at the moment. Here's my JS:
var ENDPOINT_BASE = '';
var ENDPOINT_USER_LOGIN = { url: '/user/login', method: 'POST'};
var ENDPOINT_USER_REGISTER = { url: '/user/register', method: 'POST'};
var toSend = {'credentials': { 'email':'1', 'password':'123'}};
$.ajax({
method: ENDPOINT_USER_LOGIN.method,
url: ENDPOINT_BASE + ENDPOINT_USER_LOGIN.url,
contentType: "application/json",
data: toSend
});
My PHP is simply:
<?php
print_r($_POST);
In the Chrome debugger I can see the network call be made, however the Response received in $_POST is always empty, ie it prints out Array().
If I add something like echo "abc"; in the PHP I can see it in the response, so it is hitting that URL correctly.
I'm using jQuery 2.1.4.
The JS console isn't printing out any error messages.
Any ideas what could be wrong? Thanks!

PHP is not populating $_POST as you expect because you are setting the header to JSON. I believe its default is url-form-encoded.
Either don't define the content type or if you wish to send actual JSON you could achieve that by doing something like:
$postdata = file_get_contents('php://input');
$request = json_decode($postdata);
$credentials = $request->credentials;

Related

AJAX sending data in GET request is not working

I have an AJAX function running from my frontend looking like this:
//api.js
function getTransactions(authToken) {
$.ajax({
type: 'GET',
data: {
'authToken':
'ACE8166BCD0F5B8FB5FF693F3B4056160D957A0E57FC9912EE70E9231D03166B9661BCB96BD678F3BD65CFD6DA651F1E5B5D28E294CA88C0EEE2B3C7093699EAA731409A1F8DA5C772E2335EC67ED410E20ED9FBB35B6918804879BE3D3FE1329F2348F1FB83B9BC4992F7EA75D1ED4A4F9A684371CB0D0CF09E131ADAB905CAE4454C4C9D81A9A48B05AA77B4D6F7D7C5A596C021DA368F6E356A5750EB2D117C8E02782731F7641526ACBA061EEDDB2339EABB3B179F39738D8AEF4510E612A2D11BCC74D67C3C4D989A86BB9EE710342042D2A71A364B0D17D799E28D51458AD44F53F3930E31387FF52BAD141D4AA467384282226AB2B1B55A5B45CCAF5F61DDAD770E3BA9210BBE7B926BD594F52F17F053B6C0366B4CDC4F2F147648A545ABDDD854FF778F4EA0A2672E0D249B',
},
crossDomain: true,
dataType: 'JSON',
url: 'http://localhost:8000/transactions',
}).done(function (data) {
.....
I have been trying to pass the authToken parameter to the data object, and then retrieve it in the PHP backend using (case transactions):
//index.php
$request = $_SERVER["REQUEST_URI"];
switch ($request) {
case "/login" :
require __DIR__ . "/login.php";
$userEmail = $_POST["userEmail"];
$userPassword = $_POST["userPassword"];
echo login($userEmail, $userPassword);
break;
case "/transactions" :
require __DIR__ . "/transactions.php";
$authToken = $_GET["authToken"];
getTransactions($authToken);
break;
}
If I hardcode the authToken into the getTransactions function inside case "/transactions", it works fine.
(EDIT: even if I hardcode the token in index.php, if I also hardcode it into the AJAX function (which shouldn't matter), the whole process doesn't return any data).
But there's something, either in the $_GET() in index.php, or in the AJAX function that it preventing the data from getting into the getTransactions function in index.php.
I have tried putting strings around the authToken key in the data object, also using the authToken parameter, as well as JSON.stringify-ing the data object. Further, I have changed/removed the dataType, and exhausted every other method suggested by stack overflow and other websites.
This is especially difficult because it's my first time using PHP, and I don't know how to show echos in my terminal, so I can't see any output from the PHP files.
Any help would be appreciated.
as #CBroe said, the authToken query parameter was messing with the routing for /transactions. What I did was add this code to my $request variable:
$request = strtok($_SERVER["REQUEST_URI"], "?");
the strtok() function allowed me to strip off the end of the URI before the ?, and the /transactions case was read properly.
Thanks CBroe!

jQuery AJAX PUT request data submission not working

I have a PHP file which contains the following:
if ($_SERVER['REQUEST_METHOD'] === 'PUT') {
echo '{ "response": "' . $_REQUEST['id'] . '" }';
}
Now I want to make an AJAX call to this file via jQuery:
var send = {
id: 10
};
$.ajax({
data: send,
method: 'PUT',
url: "myphpfile.php",
success: function(responseData) {
console.log(responseData.response);
}
});
This should return 10 as a response, however the output is empty. In the PHP file I also tried writing the id to a text file, which turned out to be empty as well. This means that my PHP code isn't the problem here, it's JavaScript.
When I change the AJAX url to myphpfile.php?id=10 however, the response is correct and 10 is logged to the console.
I have tried a lot of things to fix this, nothing worked. This includes setting contentType: 'application/json; charset=utf-8', dataType: 'json' and data: JSON.stringify(send). I can't find any more forum questions or articles on this and the ones I found didn't work.
Any help is appreciated.
You cant access the data from a PUT request via $_REQUEST. You'd need something like:
if ($_SERVER['REQUEST_METHOD'] === 'PUT') {
parse_str(file_get_contents("php://input"),$sent_vars);
echo json_encode(['response'=>$sent_vars['id']]); // use an array and json_encode to avoid messy string concatenation
}
See also Accessing Incoming PUT Data from PHP
So there are a couple of issues here:
PUT requests handle data parsing differently to POST, which is how you've formatted your request. So Delighted's response for more details.
You return a json string but don't convert it into a js object. You need something like $.parseJSON(...) for the object to return properly. So something like:
success: function(responseData) {
var r = $.parseJSON(responseData);
console.log(r.response);
}

JQuery $.ajax request returns me "Error 404" even if the resource exists

I'm developing an app with TideSDK and I need to send some data to a PHP script that will create a file to store it on the pc. I'm pretty new to AJAX and to send data I do:
var jsonString = JSON.stringify(GW2.items);
$.ajax({
url: "/assets/scripts/save.php",
type: "post",
dataType: "json",
data: { jsonString: jsonString }
}).done(function(data){
console.log(data);
});
Where GW2.items is a JSON object, "save.php" is my script and jsonString is the variable I want to send.
But, when I try to execute the program it returns me:
POST http://127.0.0.1:52432/assets/scripts/save.php 404 Not Found
And the answer is: Cannot POST /assets/scripts/save.php
This is the PHP script:
<?php
$jsonString = $_GET['jsonString'];
return {};
?>
I checked the path and it's correct so why it can't find my file?
Did you try your path with POST or just GET? It could be exist for GET requests (pasting the url on a browser) but probably not for POST or other HTTP verbs.
You can use REST clients like Postman to be sure, which is also a Chrome extension.

Executing cross domain javascript never hits code in .done

#People downvoting this issue: what's wrong with it? Which info am I not providing?
I'm trying to do a cross-domain service call via javascript from domainA to domainX, but somehow the line console.log('OK'); is never hit. The line console.log('1'); is hit.
How can I make sure the line console.log('OK'); is executed?
www.domainA.com/test.aspx
<script type="text/javascript">
(function () {
var ttScript = document.createElement('script'); ttScript.async = true;
ttScript.src = '//www.domainX.com/js/test.js?v=1';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ttScript);
})();
</script>
www.domainX.com/js/test.js
(function () {
console.log('1');
$.ajax({
url: "//www.domainX.com/iplookup.php",
data: null,
type: 'GET',
async: false,
crossDomain: true,
dataType: 'jsonp'
}).done(function (data) {
console.log('OK');
});
})();
I tried jsonp and json as dataType. But when setting it to json or setting crossDomain to false I get:
XMLHttpRequest cannot load http://www.domainX.nl/iplookup.php?callback=jQuery1102023322901595383883_1419031985295&_=1419031985296. Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers.
www.domainX.com/iplookup.php
I tried with and without Access-Control-Allow-Origin
<?php
header('content-type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
$data = json_encode($_SERVER['REMOTE_ADDR']);
echo "jsonp_callback($data);";
//print json_encode($_SERVER['REMOTE_ADDR']);
?>
With the above configuration I get NO errors in my Chrome console.
Under network I see that the test.js is loaded succesfully when requesting page www.domainA.com/test.aspx
I checked under Net tab under the Response tab and I see the call being made to //www.domainX.com/iplookup.php" which returns the value I'd expect, in this case an IP address.
What more can I do?
When using jsonp you are atually requesting a file like this:
jsonp_callback(yourDataHere);
And this file is included into your document making the values accessible when the function is called.
So your php-file has to echo something like this:
<?php
$data = json_encode($_SERVER['REMOTE_ADDR']);
echo $_GET['jsonp_callback']."($data);";
?>
Note that you have to add the jsonp-function to the $.ajax:
$.ajax({
url: "//www.domainX.com/iplookup.php",
async: false,
jsonp: 'jsonp_callback',
dataType: 'jsonp'
}).done(function(data){
console.log(data);
});
Btw: Why would you do that call syncronous?
Edit: I wrote kinda crap. I updated my answer. The file you are requesting is just calling a function with your data as parameters. The callback is then the function itself. Jquery should normally handle that for you and make the data available in .done().
Read through the manual here!

Get Ajax POST data on php via Javascript call

First I am conface that I am Newbie to php,
I am using jquery(knockout js) at client side & PHP at server side. my code.
Client side: I am using knockout js(Javascript). to call my PHP service.
My Code:
self.VMSaveEditUserMode = function () {
try {
var params = { "ClientData": [controllerVM_.ClientID(), controllerVM_.VMList[0].ClientName(), controllerVM_.VMList[0].ShortName(), controllerVM_.VMList[0].Address(), controllerVM_.VMList[0].CreatedBy(), controllerVM_.VMList[0].CityName(), controllerVM_.VMList[0].PostalCode(), controllerVM_.VMList[0].ContactEmail(), controllerVM_.VMList[0].ContactPhone(), controllerVM_.VMList[0].IsCorporate()] };
$.ajax({
type: "POST",
url: URL + "index.php/phpService/SaveClient/" + controllerVM_.TokenKey(),
data: JSON.stringify(ko.toJS(params)),
contentType: "application/json",
async: true,
dataType: 'json',
cache: false,
success: function (response) {
},
error: function (ErrorResponse) {
if (ErrorResponse.statusText == "OK") {
}
else {
alert("ErrorMsg:" + ErrorResponse.statusText);
}
}
});
}
catch (error) {
alert("Catch:" + error);
}
}
Server Side My Code, I am using this PHP code to connect with DB.
PHP Code:
public function SaveClient($userToken)
{
$value = json_decode($Clientdata);
echo $value->ClientData[0];
}
*My Question *:
I am not clear on how to POST data in PHP ? I tried with $_POST[''] method as well as many more.
I am using eclipse as a php framework. so, not able to debug it when i post the data.Normally mode i am able to debug my code.but not from remotely.for that i made changes on php.ini file also.
How to get Response of Post Data on php code ?
How to debug via remote post ?
My Request sample:
suppose i use:
For, data: params, only at that time my request format is.
ClientData%5B%5D=4&ClientData%5B%5D=kamlesh&ClientData%5B%5D=KAM&ClientData%5B%5D=Junagadh&ClientData%5B%5D=me&ClientData%5B%5D=SANTA+ROSA&ClientData%5B%5D=76220&ClientData%5B%5D=kamlesh.vadiyatar%40gmail.com&ClientData%5B%5D=9998305904&ClientData%5B%5D=false
For, data: JSON.stringify(ko.toJS(params)),
{"ClientData":["4","kamlesh","KAM","Junagadh","me","SANTA ROSA","76220","kamlesh.vadiyatar#gmail.com","9998305904",false]}
If I understand correctly you need to create a PHP service which is able to receive REST-like requests from client.
In order to do thad you need to access raw POST data. In PHP its being done like this:
$ClientData = file_get_contents('php://input');
You can read more about php://input in the wrappers documentation.
Of course from the client's side the data need to be sent using the POST method and as raw data, i.e. as a string. You can obtain a string from object using JSON.stringify() which you already do.
If you pass an object, it will be converted to string internally by jQuery using query-string format. More on that in the jQuery documentation for $.ajax (the most importatnt options being data and processData).
Just pass the ajax data param as an object, don't convert it into JSON. Then in PHP use $_POST directly.
Use firebug or chrome dev tools to analyze the ajax request and see which data is sent
Use this simple jquery function to accomplish your task
$.ajax({
type: "POST",
url:"scripts/dummy.php",
data:"tbl="+table,
dataType:"json", //if you want to get back response in json
beforeSend: function()
{
},
success: function(resp)
{
},
complete: function()
{
},
error: function(e)
{
alert('Error: ' + e);
}
}); //end Ajax
in PHP use:
if(isset($_POST['ClientData'])){
$client_data = $_POST['ClientData']
}
now $client_data variable should contain the array.
For debugging purpose you can use php's built-in print_r() function. It's pretty handy.
here's is an example:
//make sure it's post request
if(isset($_POST)){
//now print the array nicely
echo "<pre>";
print_r($_POST);
echo "</pre>";
}

Categories

Resources