Better way to response to AJAX from php - javascript

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.

Related

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

Send data from PHP script to jQuery Ajax request

I'm new to web development, so please pardon any silly mistakes!
I'm using the following code send a jQuery Ajax request:
var d = "email=" + email + "&password=" + password;
$.ajax({
url: 'login/c_login_form.php',
data: d,
dataType: "text", //expected type from server
type: "POST",
success: function(str, status) {
console.log(str + ": " + status);
},
error: function(obj) {
alert("Fatal error. Failed to send Ajax request.");
}
});
For simplicity, let us assume that login/c_login_form.php is currently blank (but has the php tags, of course) and is to return a set data every time.
I was under the impression that whatever I echo from the server will be passed to the success function, but it's not working that way. What is the way to send data from PHP script back to Ajax? Although I've used text datatype, I'd be happy if somebody can tell me how to return JS objects.
To summarize comments in a concrete answer:
<?php
header('Content-Type: application/json');
$data = array("status" => 1, "err" => "example_error_code");
echo json_encode($data);
?>
Please note, as Anthony Grist suggests, that you need, on your Javascript:
dataType: "json"
instead of:
dataType: "text"
See also jQuery ajax docs:
...
dataType (default: Intelligent Guess (xml, json, script, or html))
...
You can refer this answer for Ajax post request.
To send back data from PHP file to JS you need to use echo.
If you are passing more than one variable then you can use echo json_encode($array_of _variables);. If there is only one variable than please you can use just echo $variable.

Why is my Angular POST request to a PHP page not setting up the POST array?

I have a angular post that sends to my php file, but in the PHP file, I cannot access anything from the post variable. It returns my SUCCESS string, but nothing after that, so my return on the post is "SUCCESS - - - - - " where the data should be between the dashes.
JSON/JS object:
DESCRIPTION: "123321"
LOCATION: "ab_calgary_eighth_ave_pl"
NAME: "123321"
QUANTITY: 123321
TYPE: "cycle"
Angular POST Code:
$scope.insertNewInventoryItem = function()
{
if(typeof ($scope.newItem.LOCATION) == 'undefined')
alert("LocationCannot Be Empty. Please Select An Option From The Drop Down.");
else if(typeof ($scope.newItem.TYPE) == 'undefined')
alert("Type Cannot Be Empty. Please Select An Option From The Drop Down.");
else
{
$http.post("dataaccess/addnewinventory.php", $scope.newItem).then(onAddNewComplete, onAddNewError);
}
}
PHP Page attempting to find the posted values:
<?php
$con = mysqli_connect("localhost", "dbadminuser", "password", "database_demo_inventory");
// Check connection
if (mysqli_connect_errno())
{
echo "FAIL - Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
echo "SUCCESS - " . $HTTP_POST_VARS['newItem.NAME'] . " - " . $HTTP_POST_VARS['TYPE'] . " - " . $HTTP_POST_VARS["QUANTITY"] . " - " . $HTTP_POST_VARS . " - " . $_POST[0];
}
mysqli_close($con);
?>
Picture of the Request from GOOGLE developer tools:
Picture of return data from the request (see PHP code for where SUCCESS is coming from):
Why can I not access the post variables? Am I missing something here?
By default, Angular transmits data using the Content-Type: "application/json" and PHP can't parse the JSON data into the $_POST natively. You could follow these two steps to resolve this issue:
Step 1: Change the default value of header Content-Type:
angular.module("myApp",[], function($httpProvider){
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
})
Step 2: Convert the JSON data into key=value pair serialized data. (I'm using jQuery $.param function to convert the data)
$http({
method:"POST",
url: "post.php",
data: $.param($scope.newItem)
}).success(function(data, status, headers, config){
console.log(data);
}).error(function(data, status, headers, config){
console.log(status);
});
Note: $HTTP_POST_VARS is not a super global variable and it has been completely deprecated in PHP 5. I think you could use $_POST.
while chickenrice's answer is true and solves the issue, I'd prefer to use the JSON data as the payload at least for few reasons.
suits if your objects are complicated, contains nested structures.
It allows you to send any kind of object e.g. [[1,2],[3,4]] -
Array(array,array..) This is just impossible to send in uri-encoded
string.
It's not comfortable if you send simple "name=egor&type=lulzsec"
since it will look "verbose".
You CAN omit CSRF tokens with this!
To get this in PHP make use of file_get_contents("php://input"); to get the request body directly.
You would need to have a small wrapper around this. Moreover you might need to whitelist the content type headers to mitigate the CSRF.
EDIT
if (0 === strpos($_SERVER['CONTENT_TYPE'], 'application/json')) {
$input_json = file_get_contents('php://input');
$input= json_decode( $input_json, TRUE ); //convert JSON into array
}
My backend is Apache22/PHP5.4. I've been banging my head against the wall on this issue for days. Just now, I finally cracked it.
Setting content-type to application/x-www-form-urlencoded didn't get the data into input:// or $_POST. Then I came across this thread: https://groups.google.com/forum/#!topic/angular/MBf8qvBpuVE
Not setting Content-Type will make the underlying XHR browser implementation add a correct header
The keys is to set content-type: false. This is my working code, and I don't even have to get the data from input:// it goes directly to $_POST.
var serialized = $httpParamSerializer($scope.formData);
return $http({
method : 'POST',
url : 'your-url-here',
data : serialized,
headers : { 'Content-Type': false }
}).then(
function(response) {
return response;
},
//Network or server error
function(data, status, headers,config,statusText) {
console.log('AJAX failure: status='+status+', statusText='+statusText);
}
);
I am very new to AngularJS, and so I have no idea why setting the header didn't work for me.
For decoding the PHP, I used the following code, which gave me direct access into the POST data, which in my case was JSON. Apparently JSON is a unsupported data structure, so PHP failed to parse it automatically into the POST array:
$jsonText = file_get_contents('php://input');
$decodedText = html_entity_decode($jsonText);
$myArray = json_decode('[' . $decodedText . ']', true);
Explanation:
Line 1 gets the raw data that was sent over from the request (in this case it was from the Angular Controller posted in the OP.
Line 2 decodes the JSON array grabbed in step one, correctly forming it to parse later. Note that in this case, steps one and two both return the exact same looking object.
Line 3 takes the formatted JSON data and decodes it into a PHP array. Now you can use the following to access parts of the array:
$myvar = $myArray[0]["SOME_VARIABLE"];
Thanks for the answers guys!

Using AJAX to call a php function keeps failing

im having a problem trying to get an ajax call to trigger a php function and then return successfully. As far as i can see my syntax is correct.
But all i get back is failed! Any ideas?
EDIT
I have changed my AJAX request to send without using data, just to rule out that being a problem and i have implemented some of the things people suggested below but to no avail, heres what my 2 files look like now:
ship.js:
function set_ship()
{
//var datastring = {'ship':'true'};
$.ajax({
type:'POST',
url:'soap/classes/class.ship.php',
success: function(success){
alert('success');
},
error: function(fail){
console.log(fail);
}
});
}
And my PHP class.ship.php:
<?php
var_dump("hello");
header('Content-type: application/json');
echo json_encode(array("result"=>"true"));
From the var_dump on my PHP script i can see that the class.ship.php isnt even being called for some reason.
Thanks
Please try this
json_encode(array("result"=>"true"));
because
json_encode(true) // will return just "true" which is not a valid json
Also try serializing the dataString , by doing
data: datastring.serialize();
lowercase JSON_ENCODE
success: function(success), error: function(fail)
check what is returned in network tab of firebug.
You need to set the content header to json header('Content-type: application/json'); and make sure you request return only json coz ajax is waiting only for "JSON" and it will throw parse error
if(isset($_POST['ship']) && $_POST['ship'] == "true"){
$result = "result";
header('Content-type: application/json');
echo json_encode(true);
}
I would suggest that you check what it being actually returned by the server.
The error callback receives one argument representing the xhr object, so you can inspect that directly by placing a breakpoint or using console logging, like this
error: function(xhr) {
console.log(xhr);
}
Likewise, the success callback receives three parameters: the status, the returned data and the XMLHTTPRequest Object, so you can check those in the very same way:
success: function(status, data, xhr) {
console.log(status, data, xhr);
}
You should look for the response status code and the response text in the xhr object to understand what is going wrong. If you're seeing a 200 OK response status, the data returned from the server is probably not being interpreted correctly as JSON data, so you should try setting the response header server side to application/json.
An error might occur also if something else is appended or prepended to your response. This happens especially when warnings occur in the code before returning and you have error reporting set to ON.

JQuery gives JSON syntax error when using PHP's json_encode

I have an application that uses JQuery $.ajax to send JSON encoded data to server where I process it and then send back the results also JSON encoded. The problem is that JQuery gives a parse error when I want to process the response. (As if PHP's json_encode function outputs an invalid JSON format).
Here comes the code:
The Javascript code:
$.ajax({
type: 'POST',
url: URL+'pages/processListUIAjaxRequest',
data:{filters: filters, rebuild_params: $('#rebuild_params\\['+unique+'\\]').val()},
dataType: 'json',
success: function(response){
alert(response);
},
error: function(request, status, error){
alert('Unable to update table contents');
console.log(request);
console.log(status);
console.log(error);
}
});
This is a piece of the PHP code which outputs the response:
$response->addResult($uFilters);
header('Content-Type: application/json');
$response->toJSON(true);
The $uFilters is a simple array, and the toJSON method of the $response object is here:
public function toJSON($output = false){
$out = array();
if($this->hasErrors()){
$out['has_error'] = true;
$out['errors'] = $this->getErrors();
} else $out['has_error'] = false;
$out['result'] = $this->_result;
if($output){
echo json_encode($out);
}else{
return json_encode($out);
}
}// toJSON
Every time I run the code i get the 'Unable to update table contents', and on JavaScript console I have:
'SyntaxError: JSON.parse: unexpected character'
despite I defined dataType: as 'json' and the output is json_encode'd by PHP. On the JavaScript console I can see that the response text is:
"{"has_error":false,"result":{"page_id":"xxx"}}"
Tried copy this and validate with online JSON validator tools, the interesting thing is it was valid a few times and it was invalid a few times (without any consistency) Im a bit confused.
Tried to use other headers like:
header('Content-Type: text/json');
header('Content-Type:javascript/json');
header('Content-Type: application/json');
or with no header, but nothing.
If I edit the JQuery ajax request's dataType to 'text' (despite the output is JSON formatted and and even the header says it is a JSON content), then the success handler runs and I got the response correctly. In this case the same problem comes when I try to $.parseJSON(response).
What went wrong? Is my JSON string really invalid?
Debug your response to see what characters are there that is making it not valid. Set the dataType to text and escape the text that is returned.
dataType: 'text',
success: function(response){
console.log(escape(response));
},
You will see the characters that are returned, there is probably some weird return character that is cauing the problem.

Categories

Resources