I have the following code:
jQuery.ajax({
type: "POST",
async: true,
url: '/index/city',
data: {massiv: 'qweqwe'},
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (msg)
{ alert('success') },
error: function (err)
{ console.log(err.responseText);}
});
And the following code on php side:
var_dump($_POST);
When I run it I get blank $_POST array. However, with firebug I can clearly see that I send POST query massiv=qweqwe. IF I run query with GET type, I can see it in $_GET array without any problems.
There is nothing in nginx and php-fpm logs.
I have found workaround using $.post, instead of $.ajax
Related
I'm having a problem trying to implement an AJAX request into a pre-existing website that I didn't create.
I have no problems sending the data to PHP as a GET request, however POST requests and trying to access $_FILES is returning null.
Here is the AJAX:
var someData = 'test';
$.ajax({
url: "post-data.php",
method: "POST",
dataType: "JSON",
data: ({someData}),
success: function(data) {
console.log(data);
}
});
PHP:
<?php echo json_encode($_POST['someData']); ?>
I believe the cause of the issue might lie within the htaccess file or be related to some other redirect that is in place on the site. This website was built by a past staff member at the company, and I've had this same problem using AJAX POST with several other sites built by them.
As changing from POST to GET works fine I don't think there is any problem with my very simple code.
Is there some way I can test if the data is going missing due to a redirect, or could there be some other cause?
First check the browser dev tools ctr+shift+J and see if there is a redirect. If not then
You need to set your datatype to json and depending on what version of JQUERY you are using you might have to use "type" instead of "method" if your JQUERY version < 1.9.0
var someData = 'test';
$.ajax({
url: "post-data.php",
method: "POST",
dataType: "json",
data: ({someData}),
success: function(data) {
console.log(data);
}
});
PHP code:
header("Content-Type: application/json", true);
If that doesnt work then make sure your URL is absolutely correct. No extra slashes or spaces.
I have managed to figure this out, there is a 302 redirect in place for all .php extetensions to a url without the extension. There was also an error in my code.
Changing the URL in the AJAX to "post-data" without the .php extension allows me to see $_POST in PHP.
My other problem with not being able to access files came down to the way I was trying to send FormData with AJAX.
My original code to do this was:
var someData = 'test';
var fData = new FormData();
fData.append("images", $("input[name='fileUpload']").prop("files")[0]);
$.ajax({
url: "post-data.php",
method: "POST",
dataType: "JSON",
contentType: false,
processData: false,
data: ({someData, fData}),
success: function(data) {
console.log(data);
}
});
The problem being that you can't send FormData and other variables at the same time. Instead I have to append my other data to the FormData:
var someData = 'test';
var fData = new FormData();
fData.append("images", $("input[name='fileUpload']").prop("files")[0]);
fData.append("someData", someData);
$.ajax({
url: "post-data.php",
method: "POST",
dataType: "JSON",
contentType: false,
processData: false,
data: fData,
success: function(data) {
console.log(data);
}
});
I'm using jstree on a project and attempting to save my tree to a database.
I'm obtaining the tree data as follows:
var tmp = $('#tree').jstree(true).get_json();
console.log(tmp);
This produces a JSON object in the console as I'd expect:
However when I post this to a PHP script using jquery...
$.ajax({
type: 'POST',
url: '/saveTree',
data: {'tree': tmp},
success: function(msg) {
console.log(msg);
}
});
... It is showing a PHP array of my data:
The script which I have at /saveTree displays the POST data in the tree array post key:
var_dump($this->request->data['tree']);
I assumed since the data I'm posting to the script is in JSON format I'd need to json_decode() it at the other end? If not, why not?
I've also tried adding dataType: 'json', in the ajax request but that makes no difference.
What's happening here?
Please note the PHP script at /saveTree is running in CakePHP 2.x so the line of PHP above is equivalent to var_dump($_POST['tree']) in regular PHP.
If you want send the data as string you can JSON.stringify(tmp);
tmp = JSON.stringify(tmp);
$.ajax({
type: 'POST',
url: '/saveTree',
data: {'tree': tmp},
success: function(msg) {
console.log(msg);
}
});
i am sending data through ajax call to the php code my ajax code is this
var values = JSON.stringify({ dstring: dataString, ukey:ukey });
var page_path = server_url+"save_data.php";
$.ajax({
type: "POST",
url: page_path,
cache: false,
data: values,
dataType: "json",
success: function(msg){
},
error:function(xhr, status, error) {
}
});
and in the ajax it send data like this
{"dstring":{"q2":"11","q3":"22","q4":"33","q5":"44","q6":"55"},"ukey":"1"}
and in the php when i try to get it through REQUEST it dont show me data , i am bit confuse on how to handle this data in php
Don't stringify data on your ajax call. You should then be able to $_POST['dstring']on the PHP script. Also, you should add in some debug code at least into that error handler to know what's up. Last but not least, inspect the network calls.
You have to get file_get_contents("php://input") and run that through json_decode.
I have an ajax call like this:
$.ajax({
type: "POST",
url: "www.something.com/login.php",
cache:false,
dataType: "json",
data: {
username: $('#user').val(),
password: $('#pass').val()
},
success: function(response)
{
localStorage.setItem('user',response.results[0].user);
localStorage.setItem('company',response.results[0].company);
}
});
This is not working because I'm trying to connect to the script which is not on the same root as my files, this PHP file is located on the external server.
How do I need to use JSONP to get this script working?
Sure you can. The only difference between JSON and JSONP is that JSONP is wrapped with a function name;
{ "x": "hello" } // JSON
foo({ "x": "hello" }); // JSONP.
You need to pass the information through URL variables.
type: "GET",
url: "www.something.com/login.php?login="+username+"&password="+password,
Then on the server side:
$_GET["username"];
$_GET["password"];
But now that I've told you this, DO NOT DO THIS FOR PASSWORDS AND LOGINS! THIS IS VERY INSECURE!!!
Instead, create a local PHP file, that shares data with the other website on the backend. If you can't do this, then use iframes and use your original method.
Another way is to use cURL. cURL allows you to login just like you were on the page in your browser. It's not very fast, but it works very well on websites you don't have much control over and that don't have an API.
Using PHP CURL to login to a remote web site
Try this...
$.ajax({
type: "POST",
url: "www.something.com/login.php",
cache:false,
dataType: "jsonp",
crossDomain: true,
data: {
username: $('#user').val(),
password: $('#pass').val()
},
success: function(response)
{
localStorage.setItem('user',response.results[0].user);
localStorage.setItem('company',response.results[0].company);
}
});
As the answer to this question says, I have this block of code to query the best buy api:
$.ajax({
type: "GET",
url: "http://api.remix.bestbuy.com/v1/products(search=camera)?apiKey=" + apiKey + "&format=json&callback=?",
cache: true,
success: function(data) {
alert('success');
},
dataType: 'json'
});
The code runs fine, but returns an error message from best buy:
"Couldn't understand '/v1/products(search=camera)?apiKey=myApiKey&format=json&callback=jQuery16209624163198750466_1312575558844'"
If I leave out "callback=?" the url returns products just fine when I go to it on the browser, but in the code it throws a javascript error:
"XMLHttpRequest cannot load http://api.remix.bestbuy.com/v1/products(search=camera)?apiKey=myApiKey&format=json. Origin http://mysite.com is not allowed by Access-Control-Allow-Origin."
set dataType to jsonp
$.ajax({
type: "GET",
url: "http://api.remix.bestbuy.com/v1/products(search=camera)?apiKey=" + apiKey + "&format=json",
cache: false,
crossDomain:true,
success: function(data) {
alert('success');
},
dataType: 'jsonp',
});
Update: Found a solution, but it's not ideal. I'd rather not use php, but it works.
I have a php file that grabs the data:
$requestUrl="http://api.remix.bestbuy.com/v1/products(search=camera)?format=json&apiKey={$apiKey}";
$data=file_get_contents($requestUrl);
echo $data;
Then I grab that file with jquery:
$.ajax({
url: "js/getBestBuy.php",
dataType: "json",
success: function(data) {
alert('success');
}
});
The Remix query parser can't handle an underscore in the JSON Callback. If you have a callback without an underscore it should work. Keep in mind, the Remix cache ignores the value of the JSON callback, so if the query is identical except the callback has changed, you will get a cached response (ie. the "couldn't understand . . ." error). Change the query slightly and you will get a fresh response.