I'm sending some data over with jQuery/Ajax. My code is marked as POST, but PHP is actually seeing it as GET. What gives?
$.ajax({
url: url,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (results) {
callback(results);
},
error: function (req, msg, obj) {
console.log('An error occured while executing a request for: ' + url);
console.log('Error: ' + msg);
}
});
I'm able to confirm it's coming in on the PHP side as GET by doing print_r($_GET) and print_r($_POST)
you r not sending any data in post. try add some data and check in server side.
JS
<script>
$.ajax({
url: url,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data : {
'sample' : 'sample_data'
},
success: function (results) {
callback(results);
},
error: function (req, msg, obj) {
console.log('An error occured while executing a request for: ' + url);
console.log('Error: ' + msg);
}
});
</script>
PHP
<?php
$sample = '';
if (isset($_POST['sample'])) {
$sample = $_POST['sample'];
}
echo $sample;
?>
// Output
sample_data
I think through the url you are passing values instaed of get if you want to post try like
$.ajax({
url: url,
type: "POST",
data:{'my_var':'gautam'},
-------------
and in php you can use like
<?php
print_r($_POST); //or you can print_r($_POST['my_var']);
?>
gives you 'gautam'...
Use $_SERVER['REQUEST_METHOD'] to check if its GET or POST
echo $_SERVER['REQUEST_METHOD'];
Use $_REQUEST[] for getting both POST and GET method values
<?php
print_r($_REQUEST);
extract($_REQUEST);
echo "sample : ".$sample;
?>
output:
sample : sample_data
Related
I am calling a PHP file from ajax but not getting any response from the PHP, I inspected there it showing No response available.
var str = "Hi";
$.ajax({
type: "POST",
url: "get_details.php",
data: str,
dataType: "json",
success: function(response) {
alert(response);
}
});
and my PHP file contains following.
<?php
echo "Hello";
?>
You should return JSON from get_details.php file, or change dataType attribute to html
I have an ajax post that looks like this: (Located in: post.php)
$.ajax({
type: "POST",
url: 'prize.php',
cache: false,
beforeSend: function(req) {
req.setRequestHeader("Accept", 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8');
},
data: {sw: screen.width, sh: screen.height, saw:screen.availWidth, sah: screen.availHeight, scd: screen.colorDepth, tz: (new Date().getTimezoneOffset()), bp: sbp, hf: have_flash},
success: function (data, textStatus, xhr) {
if(data=="success"){
$('#status').text("You won: $<?php echo $data['prize'] ?>!");
}else {
$("#m_error_msg").html(data);
}
},error: function (){
}
});
The above ajax call, posts to this page: prize.php That looks like this:
if($_POST){
$data = array("data"=>"success","code"=>"100","prize"=>"$prize","type"=>"$text");
die($data['data']);
}
My question is.. How can I pass the $data['prize'] or $data['type'] to the:
if(data=="success"){}
code?
Add dataType:'json' to your $.ajax() handler to declare you wish to receive a json encoded result back from the server:
type: "POST",
url: 'prize.php',
cache: false,
dataType:'json',
Then in your response from the server, send back a json_encodeded array.
echo json_encode($data);
die();
Then in your success function, let's check:
success: function(data){
if(data.data == 'success'){
}
}
I am working on my site and i have a jquery request to the server
$.ajax(
// do an ajax to send value to the database...
{
url:"pages/welcome_get.php",
type: "POST",
dataType: "json",
cache: false,
data: { wm_val: wel}
})
How can I get a response as a json data from which is not a html data and how do I parse the json response from the server to the html file?
You write the PHP to emit JSON.
<?php
# Some code to populate $some_associative_or_non_associative_array
header("Content-Type: application/json");
echo json_encode($some_associative_or_non_associative_array);
?>
You need to use the parseJSON function in the js.
Here is the Php code:
function send_reply(){
echo json_encode(array('reply'=>'here is my reply'));
exit;
}
Here is the js code:
$.ajax({
url:'myajax.php',
data:{'func':send_reply},
type:'POST',
dateType:'json'
}).success(function(data){
data=$.parseJSON(data);
alert(data.reply);
}).error(function(jqxhr,error,status){
alert('Error sending reply');
});
As #Quentin said, you need to output JSON in your PHP result. Then you need to use done() to receive the data on the client side and work with it from there:
$.ajax({
url:"pages/welcome_get.php",
type: "POST",
dataType: "json",
cache: false,
data: { wm_val: wel}
}).done(function( json ) {
// do something with json here
});
You need to add the "JSON" header to your "pages/welcome_get.php" file:
header("Content-Type: application/json");
And also in your AJAX call remember to add the "success" and "error" callback:
jQuery.ajax({
url:"pages/welcome_get.php",
type: "POST",
dataType: "json",
cache: false,
data: { wm_val: wel}
success: function(response) {
//Do stuff with response here
}
error: function(){
//Display error msg or something like that
}
});
lets say you are checking user in your welcome_get.php
then in your welcome_get.php
use this
if(isset($_GET['wm_val'])){
$wm_val = $mysqli->real_escape_string($_GET['wm_val']);
$check_user = $mysqli->prepare("SELECT email FROM members WHERE username = ? LIMIT 1 ");
$check_user->bind_param('s', $wm_val);
$check_user->execute();
$check_user->store_result();
$check_user->bind_result( $email);
$check_user->fetch() ;
if ($check_user->num_rows == 1) { $datas['msg']= "failed" ;}
else{$datas['msg']= "success" ;}
$check_user->close() ;
echo json_encode($datas);
}
and your ajax
$.ajax(
// do an ajax to send value to the database...
{
url:"pages/welcome_get.php",
type: "POST",
dataType: "json",
cache: false,
data: { wm_val: wel},
success: function(msg) {
if (data.msg == 'success'){
// do what you like here example
$('#mydata').html("<span >you welcome ! </span>").delay(4000).fadeOut('fast');
}else{
//do something else example
$('#mydata').html("<span >failed ! </span>").delay(4000).fadeOut('fast');
}
})
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)
I am sending to the server this call:
var Message = {};
Message['islands'] = '1-15-13';
Message['newMessageText'] = 'this is test message';
$.ajax({
url: "sendnote.php",
type: "POST",
data: Message,
dataType: "json",
contentType: "charset=utf-8",
success: function (data) {
alert(data["result"]);
},
error: function (data) {
alert(data["result"]);
}
});
and on server (sendnote.php) I have
print_r($_POST);
just to check do I receive anything, but after cchecking response in Firebug I see that this array is empty.
What am I doing wrong in sending data?
Thanks in advance!
PS I've checked previous post on this subject, but still have problems with it.
The problem is the contentType
Try this:
jQuery
$(document).ready(function(){
var Message = {};
Message['islands'] = "1-15-13";
Message['newMessageText'] = 'this is test message';
$.ajax({
url: "sendnote.php",
type: "POST",
data: Message,
dataType: "json",
success:function(data) {
alert("Islands: "+data.islands+", Message: "+data.newMessageText);
},
error:function(data) {
alert('error');
} });
});
php
<?php
echo json_encode($_POST);
?>
print_r($_POST) does not give a JSON response. do you even know what the actual reply of the request looks like when not using AJAX?
try echo json_encode($_POST); - this should print out a valid JSON.
or might i add that you might have forgotten PHP's <?php ?> opening and close tags