Sending json data to php web service - php

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

Related

No response from php after calling ajax

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 need to read an ajax post with PHP

I am attempting to update a database using ajax and PHP. Right now, i am just testing to see if my receiving PHP file is getting the POST data by echoing it, but all I get back is an 'undefined index' error.
Here's my sending code:
var content = $(".homeContent").html();
var dataString = "homepage|content|"+content;
//var
$.ajax(
{
type: "POST",
url: "Update.php",
data: "dataString="+dataString,
success: function (result) {
console.log(dataString);
}
});
and here is my receiving file (Update.php):
<?php
echo $_REQUEST['dataString'];
?>
Try this:
Ajax (JavaScript):
$.post( "Update.php", { dataString: "some String" } );
PHP:
<?php
echo $_POST['dataString'];
?>

Ajax post not appending data to URL

I am trying to get my search bar working, however I am having issues with an ajax post.
For whatever reason, none of the data is being appended to the URL. I have tried various things with no success. I am attempting to send the data to the same page (index.php).
Here is my jquery:
$(function(){
$(document).on({
click: function () {
var tables = document.getElementsByTagName("TABLE");
for (var i = tables.length-1; i >= 0; i-= 1) {
if (tables[i]) tables[i].parentNode.removeChild(tables[i]);
}
var text = $('#searchBar').val();
var postData = JSON.stringify({ searchTerm: text });
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: postData,
success: function() {
alert("Test");
}
});
}
}, "#searchButton");
});
And here is the php which I have with index.php:
<?php
require('course.php');
if(isset($_POST['searchTerm'])) {
echo $_POST['searchTerm'];
}
?>
No matter what I try, I am unable to get anything to post. I have checked the network tab in chrome, and I'm not seeing anything that indicates it's working correctly.
Any ideas?
EDIT:
I've changed my code to this, and it seems I'm getting closer:
$(document).on({
click: function () {
$("TABLE").remove()
var text = $('#searchBar').val();
$.ajax({
type: 'GET',
url: 'index.php',
dataType: 'text',
data: { searchTerm: text },
success: function() {
alert("Test");
}
});
}
}, "#searchButton");
And:
<?php
require('course.php');
if(isset($_GET['searchTerm'])) {
echo $_GET['searchTerm'];
}
?>
Now I am getting ?searchTerm=theTextIEnter as expected, however it's still not being echoed in index.php.
Do not use JSON.stringify() to convert object to string. data passed to $.ajax must be an object and not JSON.
For whatever reason, none of the data is being appended to the URL.
You are making a POST request. POST data is sent in the request body, not in the query string component of the URL.
If you change it to a GET request (and inspect it in the correct place, i.e. the Network tab of your browser's developer tools and not the address bar for the browser) then you would see the data in the query string.
This will work for you use data: { postData } on place of data:postData and you will receive your data in $_POST['postData']
$(function(){
$(document).on({
click: function () {
var tables = document.getElementsByTagName("TABLE");
for (var i = tables.length-1; i >= 0; i-= 1) {
if (tables[i]) tables[i].parentNode.removeChild(tables[i]);
}
var text = $('#searchBar').val();
var postData = JSON.stringify({ 'searchTerm' : text });
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: { postData },
success: function(data) {
alert(data.searchTerm);
}
});
}
}, "#searchButton");
});
In index.php
<?php
if(isset($_POST['postData'])) {
echo $_POST['postData'];
die;
}
?>
If you want to send data via the URL you have to use a GET request. To do this, change the type of the request to GET and give the object directly to the data parameter in your jQuery, and use $_GET instead of $_POST in your PHP.
Finally note that you're not returning JSON - you're returning text. If you want to return JSON, use json_encode and get the value in the parameter of the success handler function.
Try this:
$(document).on({
click: function () {
$('table').remove();
$.ajax({
type: 'GET',
url: 'index.php',
dataType: 'json',
data: { searchTerm: $('#searchBar').val() },
success: function(response) {
console.log(response.searchTerm);
}
});
}
}, "#searchButton");
<?php
require('course.php');
if(isset($_GET['searchTerm'])) {
echo json_encode(array('searchTerm' => $_GET['searchTerm']));
}
?>
Remove dataType: 'json', from your AJAX. That is all.
Your response type is not JSON, yet by setting dataType: 'json' you're implying that it is. So when no JSON is detected in the response, nothing gets sent back to the method handler. By removing dataType it allows the API to make an educated decision on what the response type is going to be, based on the data you're returning in the response. Otherwise, you can set dataType to 'text' or 'html' and it will work.
From the manual:
dataType: The type of data that you're expecting back from the server.
This is NOT the type of data you're sending/posting, it's what you're expecting back. And in your index.php file you're not sending back any JSON. This is why the success() method is not satisfying. Always set the dataType to the type of data you're expecting back in the response.
With POST Request:
Please comment below line in your code:
//var postData = JSON.stringify({ searchTerm: text });
And use below ajax code to get the post-data:
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: { searchTerm: text },
success: function() {
alert("Test");
}
});
With GET Request:
You can convert your data to query string parameters and pass them along to the server that way.
$.ajax({
type: 'GET',
url: 'index.php?searchTerm='+text,
dataType: 'json',
success: function(response) {
alert(response);
}
});
In response, You can get the data with alert, so you may get idea about the same.

how do i get a response from a jquery ajax request

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');
}
})

jquery ajax POST but PHP seeing GET?

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

Categories