Ajax POST-request doesn't come through to PHP - php

I'm firing an HTTP POST request with Ajax to my php file, but I don't get the desired result. $_POST and $_GET are both empty. I think I'm overlooking something, but I have no clue what.
Here's my code for firing the request:
this.save = function() {
alert(ko.toJSON([this.name, this.description, this.pages]));
$.ajax("x", {
data: ko.toJSON([this.name, this.description, this.pages]),
type: "post", contentType: "application/json",
success: function(result) { alert(result) },
error : function(jqXHR, textStatus, errorThrown) { alert(textStatus + errorThrown)}
});
};
Note that I alert the JSON on line 3. That JSON is correct, so the input on line 5 is valid.
My test method in PHP:
header('Content-type: application/json; charset=utf-8');
echo json_encode(array_merge($_POST, $_GET));
exit;
The response I'm getting is an empty array.
I tested the input (see above);
I know the Ajax call itself succeeds, if I replace that second line in my PHP example with json_encode(array('success' => true)); I get that back in my page - so the URL is correct.
I tested it with both GET and POST, with similar negative results.

You are sending a JSON request, that's why both $_POST and $_GET are empty. Try sending the data like this:
$.ajax("x", {
data: { data: [this.name, this.description, this.pages] },
type: "post",
success: function(result) { alert(result) },
error : function(jqXHR, textStatus, errorThrown) { alert(textStatus + errorThrown)}
});
Now look inside $_POST["data"].
or if you need to use a JSON request then you need to deserialize it back in your PHP file:
$.ajax("x", {
data: { data: ko.toJSON([this.name, this.description, this.pages]) },
type: "post",
success: function(result) { alert(result) },
error : function(jqXHR, textStatus, errorThrown) { alert(textStatus + errorThrown)}
});
and then decode:
$json = $_POST['json'];
$data = json_decode($json);
and if you want to send pure JSON request in the POST body:
$.ajax("x", {
data: ko.toJSON([this.name, this.description, this.pages]),
type: "post",
contentType: 'application/json',
success: function(result) { alert(result) },
error : function(jqXHR, textStatus, errorThrown) { alert(textStatus + errorThrown)}
});
and then:
$data = json_decode(file_get_contents("php://input"));
Notice that php://input is a read-only stream that allows you to read raw data from the request body.

Related

How to check if there is data in JSON object in AJAX call

I am not able to check if the JSON data given by my PHP page has data in it or if it is empty. I have the following AJAX call. In this I want to check if the JSON data returned by my PHP page has data or not.
I am using if (!$.trim(data)) but it is not working. Am I doing something wrong?
$.ajax({
type: "post",
url: "../web/cpnoselected.php",
dataType: "text",
data: {
'cpno': value
},
success: function(data) {
if (!$.trim(data)) {
alert("No Data Found");
} else {
document.getElementById("cpno").innerHTML = value;
$("#jobdetailform").submit();
}
},
error: function(jqXhr, textStatus, errorThrown) {
console.log(errorThrown);
console.log(jqXhr);
console.log(textStatus);
}

Ajax POST method not working in PHP, but GET is working

I am trying to send using Ajax a POST request to php.
If I use GET it works fine, but with POST the data I receive in php is empty.
I'm sending data as a json.
This is what the js code looks like:
$.ajax(
{
type: 'POST',
url: 'php/GiveItBack.php',
contentType: "json",
data: {
word: 'abc'
},
success: function (json) {
alert(json);
},
error: function (jqXHR, textStatus, errorThrown) { alert('ERROR: ' + errorThrown); }
});
This is the php/GiveItBack.php file
<?php
$x = $_GET['word'];
echo 'Get: ' . $x;
$x = $_POST['word'];
echo '; Post: ' . $x;
$x = $_REQUEST['word'];
echo '; Request: ' . $x . ';';
?>
With this code, the message in the alert window looks like this:
Get: ; Post: ; Request: ;
If I replace type: 'POST' in the js file with type: 'GET' this is the result I get in the alert window (as I was expecting to see):
Get: abc; Post: ; Request: abc;
I can't see what I'm missing here.
Is something wrong in the code or is any special setting I need to do for this to work.
By the way I am using: jquery-2.2.4.min and php v5.6 and XAMPP v3.2.2.
Thank you.
The content type was not correct, need to use contentType: "application/x-www-form-urlencoded" OR 'Content-Type': 'application/json'
$.ajax(
{
type: 'POST',
url: 'php/GiveItBack.php',
contentType: "application/x-www-form-urlencoded",
data: {
word: 'abc'
},
success: function (json) {
alert(json);
},
error: function (jqXHR, textStatus, errorThrown) { alert('ERROR: ' + errorThrown); }
});
contentType: "json",
You content type is wrong here. If you want to receive it the way you are trying, you should use application/x-www-form-urlencoded.
If you still want to stick within JSON, you will have to json_decode your PHP input:
$json = file_get_contents('php://input');
$obj = json_decode($json, TRUE);
$.ajax(
{
method: 'POST',
url: 'php/GiveItBack.php',
data: {
word: 'abc'
},
success: function (json) {
alert(json);
},
error: function (jqXHR, textStatus, errorThrown) { alert('ERROR: ' + errorThrown); }
});
Remove contentType: json and you should be able to use the $_POST superblogal array. If you use contentType: json the object containing the parameters is converted into a string and sent over to the server. To get the string you will need to use
file_get_contents('php://input');
This happens because $_POST only contains data sent along with the following headers:
application/x-www-form-urlencoded
multipart/form-data-encoded
When you set contentType: json, jQuery adds the application/json header to the request which is not supported by $_POST so the JSON string is treated as raw input and therefore you need to use the php://input stream to retrieve it
Ajax Data
Remove the contentType: json:
$.ajax(
{
type: 'POST',
url: 'php/GiveItBack.php',
data: {
word: 'abc'
},
success: function (json) {
alert(json);
},
error: function (jqXHR, textStatus, errorThrown) { alert('ERROR: ' + errorThrown); }
});

How to get JSON vars from PHP script

I have a problem:
I have a JS function which sending data to php script, then PHP script returning JSON data from database QUERY and I want to get values returned from PHP script.
<script type="text/javascript">
<!--
jQuery('#wysz2').submit(function() {
var myData = {
"rodzaj_konta": jQuery('#rodzaj_konta').val(),
"miejscowosc": jQuery('#miejscowosc').val()
};
jQuery.ajax({
url: 'http://somescript.php?action=results',
type: 'GET',
data: myData,
dataType: 'json',
beforeSend: function() {
jQuery('#loading').html('<p>loading...</p><img src="loading.gif" />'); //Loading image during the Ajax Request
},
error: function(xhr, textStatus, errorThrown) {
alert("Error: " + (errorThrown ? errorThrown : xhr.status));
},
contentType: "application/json; charset=utf-8",
success: function(data) {
alert(data);
}
});
return false;
});
//-->​
</script>
The PHP script returning data in proper format using:
header('Content-Type: application/json');
echo json_encode($data);
When I'm trying to alert(data), I get always a null.
How to get this returned JSON data ?
EDITED:
It's strange, because I have changed sending method to POST.
PHP returning JSON:
[{"nazwa":"Test","nazwa_firmy":"Testowa","ulica":null,"numer_domy":"2A","numer_mieszkania":"11","kod_pocztowy":"00-189","miejscowosc":"Warszawa","telefon":"213-123-132","nip":"112-312-31-31","regon":"231232133","adres_www":"http:\/\/www.gogl.epl","rodzaj_uzytkownika":"serwis"}]
But my JQUERY AJAX Script still returning null.
So my script now looks like this:
<script type="text/javascript">
<!--
jQuery('#wysz2').submit(function() {
var myData = {
rodzaj_konta: jQuery('#rodzaj_konta').val(),
miejscowosc: jQuery('#miejscowosc').val()
};
jQuery.ajax({
url: 'http://somedomain.com/skrypt.php?action=wyniki_wyszukiwania',
type: 'GET',
data: myData,
dataType: 'json',
contentType: "application/json; charset=utf-8",
jsonp: "jsoncallback",
beforeSend: function() {
jQuery('#loading').html('<p>ładowanie...</p><img src="loading.gif" />');//Loading image during the Ajax Request
},
error: function (xhr, textStatus, errorThrown) {
alert("Error: " + (errorThrown ? errorThrown : xhr.status));
},
success: function (data) {
alert(JSON.stringify(data));
console.log(data);
}
});
return false;
});
//-->
</script>
Any ideas ?
you are constructing your variables while sending in a wrong way semicoluns for object names is not there according to definitions
try this
var myData = {
rodzaj_konta: jQuery('#rodzaj_konta').val(),
miejscowosc: jQuery('#miejscowosc').val()
};
and while alerting your json data try
alert(JSON.stringify(your_json_obj));
Try to alert the object of the result...
Means if json in the format {"responseCode":"001","responseMsg":"success"}
Then alert data.responseCode
In success of your ajax function try something like this
var objParams1 = $.parseJSON(data);
console.log(objParams1);
alert(objParams1.Testowa)

jQuery posting to an external php file not working

I am not sure why but the post to my external PHP file is not working. The post request is not being received by the PHP file as nothing is being outputted.
Here's my jQUery;
$.post("AJAX/get_track_info.php", { url: "uploads/19c9aa51c821952c81be46ca9b2e9056.mp3"}, function(info){
$('#loadInfo').html(info);
});
And in the PHP file is just a
$trackurl = $_POST['url'];
Try something more like this
$.ajax({
type: 'POST',
url: 'AJAX/get_track_info.php',
data: { url: "uploads/19c9aa51c821952c81be46ca9b2e9056.mp3" },
dataType: 'text',
success: function (data, textStatus, jqXHR) { },
error: function (data, textStatus, errorThrown) { }
});

blank custom request header on the server side

I am sending request header using ajax jquery as follows
$.ajax({
url: "http://www.example.com/index.php",
dataType: "json",
type: "GET",
beforeSend: function(xhr) {
xhr.setRequestHeader("X_REST_USERNAME", "XXXX");
xhr.setRequestHeader("X_REST_PASSWORD", "XXXX");
console.log(xhr);
},
success: function(data, textStatus, XMLHttpRequest) {
alert(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest);
}
});
i can see the above request header in firebug ,but at the server end on a php page when i try to access following variables it gives me blank , i tired dumping and printing variable in php but there isnt any entry for it
$_SERVER['HTTP_X_REST_USERNAME']
$_SERVER['HTTP_X_REST_PASSWORD']
$_REQUEST['X_REST_USERNAME'];
$_REQUEST['X_REST_PASSWORD'];
In case of apache, use apache_request_headers.
$headers = apache_request_headers();
echo $headers['X_REST_USERNAME'];
echo $headers['X_REST_PASSWORD'];

Categories