I have problems in receiving POST request in PHP. I'm using JavaScript to send data to a PHP page with POST request. The JavaScript is from OpenLayers.js, and the part that sends the request looks like this:
var postrequest = OpenLayers.Request.POST({
url: "http://localhost/index.php",
data: "success",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
});
In PHP, I'm using this code to see, what I'm getting:
<?php
print_r($_POST);
?>
This is what happens:
index.php receives POST request.
FireBug also informs that POST Parameters contain Success, the one that was sent.
print_r($_POST); in index.php just gives this: array() and doesn't change after the POST request from JavaScript.
So the data is sent and received, but my PHP code doesn't somehow understand it, or I'm not using the right PHP function.
Any suggestions, where to look, and what to try?
I think the "data" property needs to be an object containing key/value pairs.
eg:
var postrequest = OpenLayers.Request.POST({
url: "http://localhost/index.php",
data: {
userName: "myUsername",
password: "myPassword"
},
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
});
If this works when you print_r($_POST) you should see
array("userName" => "myUsername", "password" => "myPassword")
I guess you need include XMLHttpRequest.js library, you can download it from this link
https://github.com/ilinsky/xmlhttprequest
Related
I have setup a page that takes the data from a form, serializes into JSON and then uses AJAX to call a PHP file to process the form data and send it to an API via cURL.
How can I get the response from the API to come back as part of the AJAX's success function?
At the start of my project, I was able to accomplish this because I was using the php as an include. But cannot use that method because the file is being executed from the AJAX call not from an include.
I tried to follow this tutorial, but just kept catching errors.
I've also scoured, reviewed and attempted more suggestions from various posts on this site than I can even count. Now, I'm asking for some help.
Here is the pertinent ajax on my index.php file.
$.ajax
({
type: "POST",
dataType : 'json',
async: false,
url: 'save_application.php',
data: { filename: fileName, applicationData: jsonFormString, job: adid },
success: function () { console.log("done");},
failure: function() {console.log('error');}
});
And here is the relevant part of the save_application.php file.
$curl = curl_init();
curl_setopt_array($curl, array(
//stuff here
));
$applicantresponse = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
And lastly, the $applicantresponse that comes back is formatted like this:
{
"applicationId": 123456789,
"links": {
"link1": "https://thisisalinkforLINK1.html", //THIS IS THE VALUE I WANT
"link2": "https://thisisalink.html",
"link3": "https://thisisalink.html"
}
}
Ultimately, I want to set a variable to the value for links->resume (ex: var resumeLink = (something goes here); \\returns https://thisisalinkforLINK1.html) back on my index.php within the success function so I can use that response for some other to-dos.
You need to output $applicantresponse from your save_application.php file so that it's returned to your calling code, and you need to change the success function in your ajax code to then use that data. It'll look something like this:
$applicantresponse = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
echo json_encode($applicantresponse);
and then...
$.ajax
({
...
success: function (data) {
console.log(data.links.link1);
// do something with the data that was returned
},
...
});
One thing that is important is that your php code not output any other text to the client. All other echo, print, debugging calls, all of that stuff, has to be removed, because otherwise you're not sending back valid json encoded data that jQuery knows how to interpret.
It looks like save_application.php uses the data submitted by $.ajax for the curl request, and you need to send part of the curl response back to the client to be used in the success function.
The curl response is already JSON, so the simplest thing to do is just
echo $applicantresponse;
which will send the entire curl response back to the client.
If you only want to send one of the links of it, you'll need to decode it and extract the specific piece you want, then re-encode that piece.
$applicantresponse = json_decode($applicantresponse);
$link = $applicantresponse->links->link1;
echo json_encode($link);
I'm building API with the following structure:
method POST
uri /words.
body {"word":"example"}.
This request should add word to database and if I testing it by httpie everything is ok.
$ http POST localhost:8000/words word="new word2"
HTTP/1.1 200 OK
Access-Control-Allow-Headers: application/json
Access-Control-Allow-Origin: http://localhost:8080
Connection: close
Content-Type: application/json
Host: localhost:8000
X-Powered-By: PHP/7.0.12-1+deb.sury.org~xenial+1
{
"test": {
"method": "POST",
"input": {
"word": "new word2"
},
"post": []
},
"words": {
"id": "581f2f118b0414307476f7b3",
"word": "new word2"
}
}
In test I placed variable obtained in php by:
$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents('php://input'),true);
$post = $_POST;
We can see that $_POST is empty. If I use javascript:
$(form).submit(function(e) {
var url = "http://localhost:8000/words";
var data = {"word" : form.elements["word"].value };
$.ajax({
type: "POST",
url: url,
data: data,
dataType: 'json',
success: function(data)
{
console.log(JSON.stringify(data));
}
});
e.preventDefault();
});
I obtain the following console log:
{
"test":{
"method":"POST",
"input":null,
"post":{
"word":"word from form"
}
},
"words":{
"id":"581f34b28b0414307476f7b6",
"word":null
}
}
Now input is empty. Word is null because I am processing $input["word"], from php://input. My questions:
Should I process $_POST, or check both variable?
How about best practices of using these methods?
Can I send php://input from browser or $_POST from command line toll like httpie?
Your manually constructed example and your JavaScript example are not equivalent.
In the first you are sending JSON encoded data with an application/json content-type.
In the second, you are passing a JavaScript object to jQuery and allowing it to follow it's default behaviour, which is to encod it using the application/x-www-form-urlencoded format and use that as the content type (just like submitting a regular HTML form would do).
PHP supports application/x-www-form-urlencoded data in POST requests, but not JSON.
Should I process $_POST, or check both variable?
If you are sending application/x-www-form-urlencoded data or another format supported by PHP, then use $_POST. Otherwise you need to get the raw data from php://input and parse it yourself.
Can I send php://input from browser
See POST data in JSON format
$_POST from command line toll like httpie?
See the httpie documentation:
http --form POST api.example.org/person/1 name='John Smith'
I just created an JQuery ajax function to retrieve some json-encoded data from PHP, here's my code :
file name : bank.php
$('form').on('submit', function(){
var datatobesent = $(this).serialize();
$.ajax({
data: datatobesent,
url:'data.php',
type:'GET'
})
.done(function(data){
console.log(typeof(data));
});
return false;
})
and in data.php I wrote
if(isset($_GET)){
$data = $_GET;
echo json_encode($data);
header("Content-type:application/json");
}
the question is, when I delete the line of header("Content-type:application/json"); in data.php the console.log tell that the type of data returned by ajax is string.
And when I added dataType :json`` inside the ajax function in bank.php the type changes into object
so what is the function of header("Content-type:application/json"); actually?
The function header("Content-type:application/json") sends the http json header to the browser to inform it what kind of data it expects. You can see all the http headers for each request in your browser (If you are using chrome open developer tools, go to network, adjust the view and reload the page, you will see all requests made by your browser, if you click on any on any of these requests then click on headers you will see the headers of each request).
When you use this function you will notice the http header Content-Type:application/json in the response sent from the server. If you don't use it the server will send the default which most likely is Content-type:text/html; charset=UTF-8
As #Monty stated you don't need this function if you added dataType: 'json' to your AJAX as Jquery will handle the data even it is sent with text/html header.
See Also: jQuery AJAX Call to PHP Script with JSON Return
To read more about headers : http-headers-for-dummies
Im trying to make a request from one server to another with json and php.
my html page:
$.ajax({
type: "POST",
url: "https://api.domain.com/gateway/partners/create_account.ajax.php",
dataType: 'jsonp',
crossDomain: true,
data: { "name" : "Test name"},
success: function(data)
{
console.log(data.responseText);
}
});
My php looks like this:
$name = $_GET['name'];
$data = array("Hello", $name);
echo json_encode($data);
I want to receive on my console: Hello Test name
What did I do wrong?
You are:
Telling jQuery to process the response as JSONP
Writing PHP that will output JSON (not JSONP) … presumably with a text/html content-type.
Trying to make a POST request instead of a GET request. JSONP only supports GET.
Trying to treat the data returned by the request as if it were an XHR object.
The minimal example of a JSONP response would be:
<?php
header("Content-Type: application/javascript");
$name = $_GET['name'];
$data = array("Hello", $name);
echo $_GET['callback'];
echo "(";
echo json_encode($data);
echo ");";
Then you need to alter the JS so that type: "POST" becomes type: "GET" and console.log(data.responseText); becomes console.log(data);
Alternatively, you could use another technique to bypass the same origin policy and still use POST.
The jsonp is a old practice and a insecure one because any one can call to your script. To is very default tor retrieving errors when a jsonp call fails.
You can implement CORS headers in your request, and then you can use just a simple XHR call.
Addeding the header:
Access-Control-Allow-Origin: *
Will fix your issue, but is better use the exact domain instead of the wildcard.
I tried to send the request from jquery ajax with contentType as 'text/plain'. I am unable to access the values on the server side. I am accessing the values using $_POST array in php file. Why is this happening.
jQuery AJAX code:
$.ajax({
type: "POST",
data: {o_pass:o_pass,n_pass:n_pass},
url: "changepass",
success: function(response) { alert(response); }
});
Server side:
$old_pass = $_POST['o_pass'];
$new_pass = $_POST['n_pass'];
Because POST requests should have a content type of application/x-www-form-urlencoded or multipart/form-data so that the server knows what it is dealing with.
What is the reason for sending the request as plain text?
You shouldn't have to worry about the content type, when doing a standard post request.
Try changing your url: changepass to changepass.php. You probably have an html or htm file named changepass that your server is processing your post request.