AJAX sending data in GET request is not working - javascript

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!

Related

PHP MVC & AJAX - AJAX does not call function from controller

So I am trying to learn AJAX requests, and in testing purposes, I am trying to use it in my personal project. I set up some test functions here and there, to test out how I can use AJAX in my project, and I got on an issue.
I'm making an AJAX call from script tags in my html, but it appears to just return all the html of that page.
AJAX call code is:
$.ajax({
URL: "<?php echo URLROOT;?>tasks/setcompleted",
type: "GET",
data: {id:'3'},
contentType: "application/json; charset=utf-8",
success: function(res){
console.log(res);
}
});
PHP Tasks controllers method setcompleted() code is just a simple echo of data passed from AJAX request via GET:
public function setcompleted(){
if(isset($_GET['id'])){
echo $_GET['id'];
}
}
I did some research, and found similar questions here, that suggested to check the URL that is passed to AJAX request. I did that, the URL that is passed in AJAX request is correct and works, if I manually write it into browser and add necessary parameters for the GET.
Can anyone suggest what am I doing wrong here?
Your function returns nothing.
public function setcompleted()
{
if(isset($_GET['id']))
{
$output = json_encode($_GET['id']);
}
return $output;
}

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);
}

Unable to read POST'd data using $.ajax

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;

Implementing Ajax calls for a REST API

I have built a back end REST API using Slim Framework and followed the REST format as close as I could.
Once I started working on the Front End I realized that AJAX works great with parameters and not paths
(param file?param=value , paths file/object/method/id)
I am planning on out sourcing or building an APP with xamarin or other 3rd party to consume the API, but for now a Alpha test will be done with HTML and AJAX calls.
Example call example.com/user/test or example.com/advertiser/2
So how do I query the API, do I just concat URL strings?
.ajax({ ... url : 'example.com/user/'+user ...});
EDIT:
Yes I know AJAX is domain sensitive, and Yes I am using verbs GET,POST,PUT and DELETE.
What is going on is the following :
When passing variables in an AJAX request they get appended as
PARAMS example.com/users/?user=Pogrindis
in an REST API at least as far as I read it goes
example.com/users/Pogrindis that's a path
reference parse.com/docs/rest#general-quick
Ajax has set definitions how to do this : https://api.jquery.com/jQuery.ajax/
Your passing user as a param, over get // post method and you are specifying what you expect back.
If i understood the question correctly you are looking at something like:
$.ajax({ url: 'example.com/user/',
data: {user: user}, // Params being sent
type: 'post',// Or get
dataType: 'json' // Or whatever you have
success: function(output) {
//.. do what you like
}
});
There should be no problem.
The data being passed into it will append to the url for GET-requests, i think thats what you mean.. Your data object can be constructed before sending via ajax.
There needs to be a route to query for data. Unless you define some flag on the server to point to the correct location, then you could pass through a route param but you need to have a pointer URL. Building the route can be painful, and subsequent calls will be more challenging but you can do it ?
After doing some research here is a solution used
FRONT END
$.ajax({
url: '/user/'+getid,
data: getdatastring,
type: 'GET',
datatype: 'json',
cache: false,
success: function(data) {
data = JSON.parse(data);
}
});
BACK END
SLIM PHP FRAMEWORK
$app->put('/user/:id', function($id) use ($app,$_pdo) {
$obj = new dbModel($_pdo);
$objApi = new Controller($obj);
$arrParams = json_decode($app->request()->getBody(),true);
$arrUser= $objApi->getUserInfo($id,$arrParams);
print json_encode($arrUser);
});

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