Can a Jquery Ajax Call Accept an Object on Succes from PHP? - php

I'm writing a simple ajax function and looking to populate two text input fields with the 'success' results. I'm wondering what my php syntax has to be to return an object.
Here is my Javascript function
function editModule(a){
data = {moduleNum:a}
$.ajax({
type: 'POST',
data: data,
url: 'includes/ajaxCalls.php',
success: function(data) {
alert(data['title']); // <-- This is where I'm not sure what to return from php
}
});
}
Here is my php doc (so far, this is where I need to know how to return an object)...
<?php
$data = array('title'=>'this');
echo json_encode($data);
When I run the function I just get the alert "undefined".
Suggestions?
Thanks,
-J

Try this. You can specify that you're expecting a JSON object and then you can interpret data accordingly.
function editModule(a){
data = {moduleNum:a}
$.ajax({
type: 'POST',
data: data,
dataType: 'json',
url: 'includes/ajaxCalls.php',
success: function(data) {
alert(data.title);
}
});
}

I have returned JSON data from the server via a jQuery Ajax call, not in PHP but it should be the same. As long as you set the content-type of your response to application/json jQuery should consider the responseText as a JSON string. Alternatively you can also set dataType: "JSON" in your Ajax call which tells jQuery that you expect JSON.

Your php page returns: {"title":"this"} in this case.
So you can reference the result with:
alert(data.title);

You may need to specify the data type:
function editModule(a){
data = {moduleNum:a}
$.ajax({
type: 'POST',
data: data,
url: 'includes/ajaxCalls.php',
dataType: 'json',
success: function(data) {
alert(data['title']); // <-- This is where I'm not sure what to return from php
}
});
}

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.

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.

AJAX jQuery PHP Return Value

I am new to AJAX and am kind of confused by what PHP passes back to the jQuery.
So you have an AJAX function like this:
$.ajax({ url: '/my/site',
data: {action: 'test'},
type: 'post',
success: function(output) {
alert(output);
}
});
(I took this from ajax another StackOverflow page.)
But on various other resources they will have the success section look like this:
success: function(data) {functionfoocommandshere}
I am just confused as to what dictates the naming of this variable? If the PHP ultimately echoes an array:
echo $myVar;
How can I get this from the AJAX?
An Ajax-Requests fetches a whole site. So you'll not get any data in variables, but the whole site in the data-parameter. All echos you made together will be in this parameter. If you want to retrieve an array, you should transform it to json before.
echo json_encode($myArray);
Then you can receive it via Ajax in this way
$.ajax({ url: '/my/site',
data: {action: 'test'},
dataType: 'json',
type: 'post',
success: function(output) {
alert(output);
}
});
In you PHP file, use json_encode to turn the array into a more convenient format for use in Javascript. So you would have something like:
echo json_encode($myArray);
Then, in your JavaScript, the data variable of the success method will hold the JSON. Use jQuery's parseJSON to convert this to a JavaScript object, which will then be very easy to manipulate. I don't know what you array contains, but you might do something like this:
$.ajax({ url: '/my/site',
data: {action: 'test'},
type: 'post',
success: function(data) {
var obj = jQuery.parseJSON(data);
alert(obj.name[0] === "John");
}
});
Again, the data variable here will contain anything your PHP outputs, but JSON is a common and convenient way to transfer data back to your JavaScript.
<script type="text/javascript">
$.ajax({
url: '/my/site',
data: {action: 'test'},
type: 'post',
success: function(output) {
alert(output);
}
});
</script>
<?php
$action = $_POST['action'];
echo $action;?>
Any output that is printed/echoed will be returned to the success function. This is handy when you want to fill an html container with something that you need to run in real time.
Once you get the hang of this, another option is to use JSON to return variables with values.
The data that's returned from the PHP AJAX function, can be retrieved from the success block. Here's the manual
$.ajax({ url: '/my/site',
data: {action: 'test'},
type: 'post',
dataType: 'json',
success: function(output) {
//output is the data returned from PHP AJAX function in JSON format
alert(output);
}
});

pass php array to jquery

Can someone please give me a simple example how should jquery $.ajax syntax look like in order to pass array from php to jquery.
On server side I have:
$a=array(1,2,3,4,5);
echo json_encode($a);
So, I'd like get this to js and have:
js_array=[1,2,3,4,5];
I'd really appreciate any help, cause I've been trying for some time now and no luck.
Thank you!
$.ajax({
method: 'GET', // or POST
url: 'yourfile.php',
dataType: 'json',
data: {}, // put data to be sent via GET/POST into this object if necessary
success: function(response) {
// response is your array
}
});
you can either use:
$.ajax({
url: 'url',
dataType: 'json',
success: function(data){
//do something with data
}
});
or:
$.getJSON('url', function(data) {
do something with data
})

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