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.
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);
}
});
Hi I'm using jquery ajax function with php. Here is the my problem;
Firstly I'm using datatype:"html" my problem is php variables not returning.
js
$.ajax({
type: "POST",
dataType: "html",
url: ajaxurl,
data:dataajax,
success:function(data) {
var $data = $(data);
$(".list").append($data);
},
error : function(jqXHR, textStatus, errorThrown){
}});
php
echo "<div>".$_POST['value']."</div>";
if I use like this it's working but when I remove the html tags ajax return nothing.
broken php
echo myfunction($_POST['value']);
echo $_POST['value'];
How can I fix this or can I use return $output with jquery ajax?
The problem is with your success callback function.
data is a html string, and as such you don't need to wrap it in jquery.
Use this.
$.ajax({
type: "POST",
dataType: "html",
url: ajaxurl,
data:dataajax,
success:function(data) {
$(".list").append(data);
},
error : function(jqXHR, textStatus, errorThrown){
}});
Ajax uses JSON data for your request and response. what you are going to want to do is return a JSON variable so that the javascript response function can access elements properly.
Luckily php is designed to do just that thing.
$ajaxData = $_POST['value'];
echo json_encode(array('response' => $ajaxData));
what are you actually trying to do with this data? if all you need to do is wrap some html in a div you can use functions like wrap() in javascript and you wont actually have to send an ajax to the server.
Either way you should really consider your data needs and try to send a json object in the ajax request so that there are actual variables to send. html markup is probably not going to be useful for the php code.
I have tried tons of thing to get json data from another url with jQuery. I have working code in php, but dont have any idea how to do it in jquery.
PHP:
$skin = rawurlencode($market_hash_name);
$skin2 = str_replace('%0A', '', $skin);
$link = "http://steamcommunity.com/market/priceoverview/?country=EU¤cy=3&appid=730&market_hash_name=".$skin2;
$json2 = file_get_contents($link);
$obj2 = json_decode($json2);
$mediumPrice = $obj2->median_price;
Example of jQuery that i have tried:
$(document).ready(function () {
$.ajax({
type: 'GET',
url: 'http://steamcommunity.com/market/priceoverview/?country=EU¤cy=3&appid=730&market_hash_name=AWP%20%7C%20Worm%20God%20(Factory%20New)',
dataType: 'jsonp',
success: function (data) {
alert(data.median_price);
}
});
});
Typically a easy way around that is to create a Proxy, that is just a fancy word for saying have something else send and receive the data between the end points.
This can be as simple as using ajax to a PHP file on your server, from that PHP file using CURL to your endpoint, back to the output through echoing the return of the CURL script.
That way you can get around the restrictions on JavaScript. You mention
I have working code in php
So it should be relatively trivial to pipe the ajax call through that code and back.
Ok so instead of doing this
$.ajax({
type: 'GET',
url: 'http://steamcommunity.com/market/priceoverview/?country=EU¤cy=3&appid=730&market_hash_name=AWP%20%7C%20Worm%20God%20(Factory%20New)',
dataType: 'jsonp',
success: function (data) {
alert(data.median_price);
}
});
Do this
$.ajax({
type: 'GET',
url: 'http://yoursever.com/proxy.php/?country=EU¤cy=3&appid=730&market_hash_name=AWP%20%7C%20Worm%20God%20(Factory%20New)',
dataType: 'json',
success: function (data) {
alert(data.median_price);
}
});
Then in proxy.php or whatever you chose to name it, use your working php code to make the call then simply return that data to the client through JSON as per normal AJAX. Then you are technically calling the remote sever using PHP and don't have the cross domain issue. But because you are using your sever as a Proxy you can still do it in real time.
Okay I think I am going mad because I have done this a million times before and now I can't make it work. I am doing an ajax post to a PHP script with some simple JSON and then returning the JSON from my PHP, however it is currently showing $_POST as an empty array.
Here is my js:
$.ajax({
type: "POST",
url: "/account/book-promo.php",
data: '{"firstName":"Peter" , "lastName":"Jones"}',
success: function(response) {
console.log(response);
}
});
And my PHP:
<?php
var_dump($_POST);
exit;
Firebug shows that my request is using POST as it is supposed to and my data is being sent as JSON yet I am getting a response of:
array(0) {
}
The only thing I can think is that there is some kind of server settings that are preventing this from working, however I cant think why there would be. Maybe I have missed a bracket or something, it is driving me mad!
Any and all suggestions welcome!
send it like if you want to send it as json.
data: { data : '{"firstName":"Peter" , "lastName":"Jones"}' },
and if you want to send it as POST just remove quotes '
data: {"firstName":"Peter" , "lastName":"Jones"},
You have to do this:
$.ajax({
type: "POST",
dataType: "json", // <---------------its required if response is json
url: "/account/book-promo.php",
data: {"firstName":"Peter" , "lastName":"Jones"}, //<---instead of string send the object this way
success: function(response) {
console.log(response);
}
});
You said in your post retuning the JSON from my PHP:
so you need to use dataType:"json" and the data you are sending to your php should be sent as object (which is usually to be pair of key and values separated by : like {key:value}) as of your code you are sending a string.