Ajax call returning empty data - php

I send an ajax call on the following URL and just echoing the response but unable to see in success function.
Where am i wrong ?
html file
$.ajax({
url: '{$PLUG_DIR}/cb_memcached/admin/ajax.php',
data: {
mode: 'videos'
},
type: 'post',
success: function(xhr) {
alert(xhr);
}
});
php file
<?php
echo "asasas";
?>

Your code seems OK. Please double check your URL. Hit your URL from browser to see response. This issue is only because of your PATH.

Issue seems to be some where in {$PLUG_DIR}. Still Call error and complete function to debug it.
$.ajax({
url: '{$PLUG_DIR}/cb_memcached/admin/ajax.php',
data: {
mode: 'videos'
},
type: 'post',
success: function(xhr) {
alert(xhr);
},
error: function(error) {
alert(error);
}
});

If you need to send data structure :
JS
$.ajax({
url: '{$PLUG_DIR}/cb_memcached/admin/ajax.php',
data: {
mode: 'videos'
},
type: 'post',
success: function(xhr) {
var param1 = xhr.param1;
alert(param1);
}
});
PHP
<?php
$response = array();
$response["param1"] = "param1";
echo json_encode($response);
?>

Please check below scenarios:
Make sure you include jquery plugin.
URL path should be correct.(In your case this may be wrong)
To check the error from ajax call please open inspect element from chrome and check the response in network tab.

Related

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.

Cross Domain jQuery Ajax call - Syntax missing error

I couldn't access the webservice call from cross domain. Please advice. I have pasted my source here.
PHP: webservice response
$data['response'] = 2;
header('Content-type: application/json');
echo json_encode($data);
jQuery Ajax Call:
$.ajax({
type: 'GET',
url: cross-domain-url,
data:{ param1:'123', param2:'123' },
dataType:'jsonp',
crossDomain: 'true',
async: true,
success:function (data) {
alert('success');
},
error:function(){
alert('error');
}
});
Cross Domain URL response:
{"ResultCode":2}
Always I am getting Error only. I don't know why. I can see the following message in Firefox inspect area.
SyntaxError: missing ; before statement
{"ResultCode":2}
Please help me.
Solution:
Modify the line like,
echo 'someCallBackString('.json_encode($data).');';
instead of echo json_encode($data);
Created the function someCallBackString and proceeded my implementations.
You are telling jQuery to make a JSON-P request (dataType:'jsonp'), but your server is returning JSON.
Consequently the browser is trying to execute a JSON text as if it was a JavaScript program (and it can't because it isn't).
Either:
Remove the dataType property from the object so that jQuery will use the HTTP Content-Type to determine that it is JSON and add access control headers to permit your site to access the data on the other domain or
Return JSON-P instead of JSON
Ok the problem is in the JSONP data, when you send a request the JSON response would send a response as
callbackFunctionName(jsonData)
You do not have anything as such so is the issue you need to format the code as below
$(document).ready(function() {
$.ajax({
type: 'GET',
url: 'your cross domain file',
dataType:'jsonp',
crossDomain: 'true',
jsonpCallback: 'MyCallback',
async: true,
success:function (data) {
console.log(data);
},
error:function(data){
console.log('error');
}
});
function MyCallback(data) {
}
});
Now in the response the data needs to be formatted as
$data['response'] = 2;
header('Content-type: application/json');
$json_data = json_encode($data);
echo "MyCallback" . '(' . $json_data . ');';
You can now check your console and see the data is coming through
You can check more on this here http://remysharp.com/2007/10/08/what-is-jsonp/
change your ajax to this code:
Solution
$.ajax({
type: 'GET',
url: cross-domain-url,
data:{ param1:'123', param2:'123' },
dataType:'JSON',
success:function (data) {
alert('success');
},
error:function(){
alert('error');
}
});
Hope it will work....

jQuery ajax not passing data JSON value

I am having some issues with the jQuery Ajax function and PHP.
I am checking the existance of the nav key in the $_REQUEST variable in PHP with code such as this:
if ($_REQUEST['nav']) {
// do something
} else {
echo 'Please specify NAV.';
}
However the above expression never evaluates as nav is never passed to it and always outputs 'Please specify NAV.'
console.log('paramList: ' + paramList);
$.ajax({
type: 'POST',
url: '/admin/nav_builder/edit.php?act=save&nav_id=<?php echo $nav_id; ?>',
data: {'nav':paramList},
dataType: 'json',
error: function(xhr, err) {
loadLayout();
hideLoader();
hideLoaderPalette();
},
success: function(data){
$('.errorMsg').html(data.html);
hideLoader();
hideLoaderPalette();
}
});
Using the Firefox Firebug plugin I can see that paramList does indeed hold a value, this is:
paramList:
{"section0":{"elem0":{"nav_palette":"text","nav_name":"fdgfdgdfg","nav_url":""},"elem1":{"nav_palette":"category","c_id":"226"}}}
I can't see for the life of my why nav is not being passed to the URL provided to the ajax function.
Try to print first if the "nav" parameter if it has a value.
echo $_REQUEST['nav'];
The other one is that you have used two method in one request.
Just try the following.
$.ajax({
type: 'POST',
url: '/admin/nav_builder/edit.php',
data: {act:'save', nav_id:'<?php echo $nav_id; ?>', nav:paramList},
dataType: 'json',
error: function(xhr, err) {
loadLayout();
hideLoader();
hideLoaderPalette();
},
success: function(data){
$('.errorMsg').html(data.html);
hideLoader();
hideLoaderPalette();
}
});
Try $_POST instead. As you're posting the nav contents.

Difficulty displaying error message using AJAX jQuery API and PHP.

I'm using the jQuery AJAX function in order to retrieve data from my mySQL database without having to refresh the page. I have everything in working order, my query's are retrieving the correct data from my database. However, I am struggling to echo out an error message when no data can be retrieved based on the users input. I have a php file that provides the user interface for the user to search from, it also contains the following Scripts in the document head. Here is what I have so far:-
<script type="text/javascript">
$(function(){
$('#users').keyup(function(){
var inpvalue= $('#users').val();
});
});
</script>
<script type="text/javascript">
$(function(){
$('#users').keyup(function(){
var inpval=$('#users').val();
$.ajax({
type: 'POST',
data: ({p : inpval}),
url: 'data.php',
success: function(data) {
$('#output_div').html(data);
}
});
});
});
</script>
Any help would be greatly appreciated, sorry if I haven't explained myself very well.
Thankyou.
Modify your .ajax() call so you can detect error conditions:
$.ajax({
type: 'POST',
data: ({p : inpval}),
url: 'data.php',
success: function(data) {
$('#output_div').html(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
This is just to get you started: see http://api.jquery.com/jQuery.ajax/ for more details on what you can do with the error handler.
Of course, it's possible that you're getting a good HTTP status from the call, but this defensive programming will make sure.
A tool like Firebug running in your browser can also help you detect bad HTTP status code returns.
In data.php you have to output the error when the data is invalid.
The error setting for $.ajax will only get called if the actual ajax request has a problem like if the server returns a 404. You would have to return an error in your json and check for it like this:
$('#users').keyup(function(){
var inpval=$('#users').val();
$.ajax({
type: 'POST',
data: ({p : inpval}),
url: 'data.php',
success: function(data) {
if(!data.error) {
$('#output_div').html(data);
}
else {
// show error
}
}
});
});
And then you would return your normal json when the data is fine and then something like this for the error:
{"error": "Oh NOES!"}

Sending json data to php web service

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

Categories