jQuery ajax not passing data JSON value - php

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.

Related

I can't get a response back from an Ajax call to a PHP page

This is my javascript for sending the request to the php page. But I can't get the response when I use the conditional if statement with the $_REQUEST variable
function getNumberOfShareHolders()
{
var dataString = "GNOSH";
alert(dataString);
$.ajax({
url: 'chartJs.php',
dataType: "json",
dataString,
cache: false,
success: function(data) {
if(data)
{
alert(data);
}
else {
}
}
});
}
Here's the php code
if(empty($_REQUEST['GNOSH'])) {
echo json_encode("request");
}
else
{
echo json_encode("No request");
}
You haven't specified a data property at all, so you aren't passing any data for jQuery to put in the HTTP request.
You've included a property named dataString in your options (which is ignored) and given it the value GNOSH.
You need a property called data with a value that is an object, then that object needs a property named GNOSH with some value. What that value is doesn't really matter as you are testing for truthfulness.
dataType: "json",
data: { [dataString]: 1 },
cache: false,

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.

Ajax get a return value from php?

I want to alert the return value from a php method, but nothing happens. Here is the ajax and php methods. Can anyone see what I am doing wrong?
--------------------------------------…
Ajax script
$.ajax({
type: 'get',
url: '/donation/junk/4',
data: datastring,
success: function(data) {
alert(data');
}
});
--------------------------------------…
php method
function junk($id)
{
return "works11";
}
in PHP, you can't simply return your value and have it show up in the ajax response. you need to print or echo your final values. (there are other ways too, but that's getting off topic).
also, you have a trailing apostrophe in your alert() call that will cause an error and should be removed.
Fixed:
$.ajax({
type: 'get',
url: '/donation/junk/4',
data: datastring,
success: function(data) {
alert(data);
}
});
PHP:
function junk($id)
{
print "works11";
}
You have an extra ' in there on the alert(data') line
This should work
$.ajax({
type: 'get',
url: '/donation/junk/4',
data: datastring,
success: function(data) {
alert(data);
}
});
And your PHP code should call the method also and echo the value
function junk($id) {
return 'works11';
}
exit(junk(4));
All you're doing currently is creating the method
ajax returns text, it does not communicate with php via methods. It requests a php page and the return of the ajax request is whatever the we babe would have showed if opened in a browser.

Passing Parameters in Ajax to JSON web service

I am using AJAX to request some information from a PHP built web service however the parameters I am passing doesn't seem to go to the web service my code is below:
$(document).on( "pageinit", "#player", function( e ) {
var passedId = (passDataObject.selectedHref != null ? passDataObject.selectedHref : window.location.href).replace( /.*id=/, "" );
alert(passedId); // test passedId has the correct value within it
var surl = "a working url";
$.ajax({
type: "GET",
url: surl,
data: "&Track="+passedId,
dataType: "jsonp",
cache : false,
jsonp : "onJSONPLoad",
jsonpCallback: "trackcallback",
crossDomain: "true",
success: function(response) {
alert('tracks function');
},
error: function (xhr, status) {
alert('Unknown error ' + status);
}
});
});
//callback function for player page
function trackcallback(rtndata)
{
alert(rtndata.track_name); // show up as undefined
}
The passedId has the correct value within it and the URL is fine however the web service does not produce a result even though the SQL statement is fine. I am assuming the issue is within this line within my php web service $id = $_REQUEST['Track']; as this gets the value from the JavaScript to execute the SQL.
Can anyone solve this issue?
See this code below, there is no "&" before the parameter name:
$.ajax({
url: homeUrl + "/Getsomething",
data: "parameterhere=" +$(element).attr('attrHere'),
type: 'GET',
contentType: "application/json",
dataType: "json",
cache: false,
success: function (result) {
//do stuff
},
error: function (xhr, ajaxOptions, thrownError) {
//error handling
}
});
What happens if you do you ajax get like the code above?

Jquery AJAX response not working

For some reason this jQuery function is not working properly. Here's my code... the response div is not updating with my response.
WHEN AJAX FUNCTION IS CALLED
if ($action == 'sort') {
echo 'getting a response';
return 0;
}
JQuery FUNCTION
function sort() {
$.ajax({
type: "POST",
url: "contributor_panel.php?action=sort",
data:"sort_by=" + document.getElementById("sort_by").value +
"&view_batch=" + document.getElementById("view_batch").value,
success: function(html){
$("#ajaxPhotographSortResponse").html(html);
}
});
}
DIV TO REPLACE
<div id="ajaxPhotographSortResponse"></div>
Move the action=sort into the data property of the $.ajax function. You're making a POST request, but appending data onto your query string like a GET request. Data only appends to the query string if it's a GET request.
Example:
$.ajax({
type: "POST",
url: "contributor_panel.php",
data: {action:'sort', sort_by: $('#sort_by').val(), view_batch: $('#view_batch').val()},
success: function(html){
$("#ajaxPhotographSortResponse").html(html);
}
});
http://api.jquery.com/jQuery.ajax/
Instead of concatenating the arguments you are passing to your server side script I would recommend you using the following syntax. Also if you already use jQuery you no longer need the document.getElementById function:
$.ajax({
type: "POST",
url: "contributor_panel.php?action=sort",
data: { sort_by: $("#sort_by").val(), view_batch: $("#view_batch").val() },
success: function(html){
$("#ajaxPhotographSortResponse").html(html);
}
});
or even shorter using the .load() function:
$('#ajaxPhotographSortResponse').load('contributor_panel.php?action=sort',
{ sort_by: $("#sort_by").val(), view_batch: $("#view_batch").val() });

Categories