jQuery AJAX PUT request data submission not working - javascript

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

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!

How to post to php with ajax, I consistently get error 400 bad request?

I am trying to send a "POST" request to my backend PHP code, which resides in functions.php in Wordpress. I get a readystate:4 and bad request(400 status) error when I run the code, if I change the "POST" to "GET" it works.
This is not the first time I encounter this, but previously it has been in my spare time projects, this time it is for work. as mentioned above I can "solve" it by changing the method to "GET", but that is not the method you are supposed to use when you add to your database. I've tried to comment out the lines with "dataType", "contentType", and "processData", but it doesn't make a difference I still just get a bad request(400) error. I have several "GET"s that work fine elsewhere in functions.php and urlen is pointing directly to functions.php.
JS
function AddToTable(){
Data={"action":"CreateProduct","Password":Password.value,"Varenr":Varenr.value,"Produkttype":Produkttype.value,"Navn":Navn.value,"Billede":Billede.value,"BilledeAlt":BilledeAlt.value,"Farve":Farve.value,"Tykkelse":Tykkelse.value,"Pris":Pris.value};
jQuery.ajax({
type: "POST",
url: urlen,
dataType: "json",
contentType: "application/json",
processData: false,
data: JSON.stringify(Data),
success: successfunction,
error: errorfunction,
});
function successfunction(data){
RefreshTable();
}
function errorfunction(data, status) {
alert("error: "+status+" Content: " + JSON.stringify(data));
};
}
Functions.php
<?php
function CreateProduct(){
exit;
}
add_action('wp_ajax_CreateProduct','CreateProduct');
add_action('wp_ajax_nopriv_CreateProduct','CreateProduct');
?>
I expect it to send the data to the server function, so I can do more with it there. But I get a readystate:4 and state 400 errorcode.
UPDATED: to include the Functions.php part of the code.
I guess your data to be posted is malformed.
You have prepared it like
Data={"action":"CreateProduct","Password":Password.value,"Varenr":Varenr.value,"Produkttype":Produkttype.value,"Navn":Navn.value,"Billede":Billede.value,"BilledeAlt":BilledeAlt.value,"Farve":Farve.value,"Tykkelse":Tykkelse.value,"Pris":Pris.value};
Variables to be posted should not be in quotes so your code there should begin like
Data={action:"CreateProduct",Password: Password.value,Varenr: Varenr.value, .....
and so on
A GET request to a URL will simply tell you whether or not it exists, in basic terms. If you send a GET request to cnn.com it will respond with a 200, if send a GET to cnnbootyshort.com, you will get no response.
In your case, rather than using exit, you could try using die(), along with an echo of what you want to send back to the browser.
<?php
function CreateProduct(){
echo "200";
die();
}
add_action('wp_ajax_CreateProduct','CreateProduct');
add_action('wp_ajax_nopriv_CreateProduct','CreateProduct');
?>
And your JS
function successfunction(data){
console.log(data); // for debugging
RefreshTable();
}
function errorfunction(data, status) {
console.log(data); // for debugging
alert("error: "+status+" Content: " + JSON.stringify(data));
};
Alternatively you can use wp_die() if you want to use a Wordpress specific function. Here is some documentation regarding its use.
<?php
function CreateProduct(){
wp_die();
}
add_action('wp_ajax_CreateProduct','CreateProduct');
add_action('wp_ajax_nopriv_CreateProduct','CreateProduct');
?>

Better way to response to AJAX from php

I have one javascript file which sends AJAX request to php file, which fetch some data from database. If php finds any data it return it as json object in response, but when it does not find any recrod in database based on query, it return a message something like "not match found".
It means javascript either get string message in "not match found" or json object.
I am trying to check if xmlhttp.responseText is json object or a string, but have not been succedeed. Any idea about how to solve this problem?
Should I convert "not match found" string into a json and send back to javascript and then parse it or there is any better way to solve this?
Thank you
BR
I don't think you need to parse your error message "No match found". There's two options: either create an if/else statement in the PHP file that the ajax calls, or you can attempt to encode the JSON in the php file and if it's unsuccessful, you can just write out a "No match found" message in the error part. I highly recommend using the $.ajax call because it can handle the responses better.
JS
$.ajax({
url: "myFile.php",
dataType: "json",
success: function(data) {
var myNewJsonData = data;
alert(myNewJsonData);
},
error: function() {
alert("No match found.");
}
});
PHP (myFile.php)
<?php
//Do your query business and stuff here
//Now let's say you get back or store some array that looks like this for example
$myArray = array('name' => 'Mike', 'age' => 20);
/* Now attempt to create a JSON representation of the array using json_encode() */
echo json_encode($myArray);
?>
When you echo it out, it gets sent back through either the $.ajax's call success or error function as a parameter (which I named data), depending on whether or not there was an error reported back. If there was not, then success is called, and if there is an error, well then you can guess which one gets called. json_encode will create a JSON representation of the array of data that you get back from your query.
Maybe I'm not understanding your question, can't you just print out an error using something like this:
$.ajax({
url: "myphpfile.php",
dataType: "json",
success: function(data){
alert(data.info);
},
error: function(xhr, status, error) {
alert(status);
alert(xhr.responseText);
alert(xhr);
}
});
Then do something inside of the error block?
Even though I totally agree with Patrick Q's comment, there is another option that has not been mentioned. You could also set the Content-Type of the response to indicate if it's json or text:
#header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) );
and
#header( 'Content-Type: text/plain; charset=' . get_option( 'blog_charset' ) );
or even,
#header( 'Content-Type: text/html; charset=' . get_option( 'blog_charset' ) );
Then you could check the response's content type to make a decision:
$.ajax({
type: "POST",
url: "xxx",
data: "xxx",
success: function(response, status, xhr){
var ct = xhr.getResponseHeader("content-type") || "";
if (ct.indexOf('html') > -1) {
//do something
} else
if (ct.indexOf('json') > -1) {
// handle json here
}
}
});
A.

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

Ajax request returns 200 OK, but an error event is fired instead of success

I have implemented an Ajax request on my website, and I am calling the endpoint from a webpage. It always returns 200 OK, but jQuery executes the error event.
I tried a lot of things, but I could not figure out the problem. I am adding my code below:
jQuery Code
var row = "1";
var json = "{'TwitterId':'" + row + "'}";
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'json',
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
function AjaxSucceeded(result) {
alert("hello");
alert(result.d);
}
function AjaxFailed(result) {
alert("hello1");
alert(result.status + ' ' + result.statusText);
}
C# code for JqueryOpeartion.aspx
protected void Page_Load(object sender, EventArgs e) {
test();
}
private void test() {
Response.Write("<script language='javascript'>alert('Record Deleted');</script>");
}
I need the ("Record deleted") string after successful deletion. I am able to delete the content, but I am not getting this message. Is this correct or am I doing anything wrong? What is the correct way to solve this issue?
jQuery.ajax attempts to convert the response body depending on the specified dataType parameter or the Content-Type header sent by the server. If the conversion fails (e.g. if the JSON/XML is invalid), the error callback is fired.
Your AJAX code contains:
dataType: "json"
In this case jQuery:
Evaluates the response as JSON and returns a JavaScript object. […]
The JSON data is parsed in a strict manner; any malformed JSON is
rejected and a parse error is thrown. […] an empty response is also
rejected; the server should return a response of null or {} instead.
Your server-side code returns HTML snippet with 200 OK status. jQuery was expecting valid JSON and therefore fires the error callback complaining about parseerror.
The solution is to remove the dataType parameter from your jQuery code and make the server-side code return:
Content-Type: application/javascript
alert("Record Deleted");
But I would rather suggest returning a JSON response and display the message inside the success callback:
Content-Type: application/json
{"message": "Record deleted"}
You simply have to remove the dataType: "json" in your AJAX call
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'json', //**** REMOVE THIS LINE ****//
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
I've had some good luck with using multiple, space-separated dataTypes (jQuery 1.5+). As in:
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'text json',
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
This is just for the record since I bumped into this post when looking for a solution to my problem which was similar to the OP's.
In my case my jQuery Ajax request was prevented from succeeding due to same-origin policy in Chrome. All was resolved when I modified my server (Node.js) to do:
response.writeHead(200,
{
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "http://localhost:8080"
});
It literally cost me an hour of banging my head against the wall. I am feeling stupid...
I reckon your aspx page doesn't return a JSON object.
Your page should do something like this (page_load)
var jSon = new JavaScriptSerializer();
var OutPut = jSon.Serialize(<your object>);
Response.Write(OutPut);
Also, try to change your AjaxFailed:
function AjaxFailed (XMLHttpRequest, textStatus) {
}
textStatus should give you the type of error you're getting.
I have faced this issue with an updated jQuery library. If the service method is not returning anything it means that the return type is void.
Then in your Ajax call please mention dataType='text'.
It will resolve the problem.
You just have to remove dataType: 'json' from your header if your implemented Web service method is void.
In this case, the Ajax call don't expect to have a JSON return datatype.
See this. It's also a similar problem. Working I tried.
Dont remove dataType: 'JSON',
Note: Your response data should be in json format
Use the following code to ensure the response is in JSON format (PHP version)...
header('Content-Type: application/json');
echo json_encode($return_vars);
exit;
I had the same issue. My problem was my controller was returning a status code instead of JSON. Make sure that your controller returns something like:
public JsonResult ActionName(){
// Your code
return Json(new { });
}
Another thing that messed things up for me was using localhost instead of 127.0.0.1 or vice versa. Apparently, JavaScript can't handle requests from one to the other.
If you always return JSON from the server (no empty responses), dataType: 'json' should work and contentType is not needed. However make sure the JSON output...
is valid (JSONLint)
is serialized (JSONMinify)
jQuery AJAX will throw a 'parseerror' on valid but unserialized JSON!
I had the same problem. It was because my JSON response contains some special characters and the server file was not encoded with UTF-8, so the Ajax call considered that this was not a valid JSON response.
Your script demands a return in JSON data type.
Try this:
private string test() {
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize("hello world");
}

Categories

Resources