Reading from a PHP array in JQuery - php

I seem to have trouble with getting data from a php array, I've looked at various examples of how to do this but I must be missing something because I can not get my code to work.
PHP method
function getLatestActivity(){
$messages = array(
array('id'=>'01', 'value'=>'blah'),
array('id'=>'02', 'value'=>'Oil'),
array('id'=>'03', 'value'=>'Spark')
);
echo json_encode($messages);
return;
}
AJAX get functiom
function getLatestActivities(){
$.ajax({
type: "GET", url: "include/process.php",
data:{
getLatestActivity: "true",
toUser: "4",
ignoreMessages:"1",
dataType: "json"
},
success: function(data){
$.each(data, function (i, elem) {
alert(data.id);
});
}
});
}
The alert prints out the message "undefined", any help would be appreciated thank you.

Try with - it's your single object now:
alert(elem.id);

It is quite likely that data isn't what you're expecting. You aren't setting any headers in your response, and as hinted at by #Sudesh dataType isn't in the right place. The result is that data is most likely a string because jquery will not parse it as json.
You're also referring to the wrong variable. data.id cannot exist with the data you are returning from php. you would need elem.id or if you prefer data[i].id if data did contain what you're expecting. As an aside - using $.each instead of a for loop is relatively inefficient.
You can check if that's the case with code such as:
function getLatestActivities(){
$.ajax({
type: "GET", url: "include/process.php",
data:{
getLatestActivity: "true",
toUser: "4",
ignoreMessages:"1",
dataType: "json"
},
success: function(data){
console.log(data); // <- look at the response
$.each(data, function (i, elem) {
// alert(data.id); don't debug using alerts
console.log(elem);
});
}
});
}
If data is a string (or simply, not what you're expecting) this should get you closer:
function getLatestActivity(){
....
header('Content-type: application/json');
echo json_encode($messages);
}
with
function getLatestActivities(){
$.ajax({
url: "include/process.php",
data:{
getLatestActivity: true,
toUser: 4,
ignoreMessages:1,
},
success: function(data){
console.log(data);
...
}
});
}
data should at least then be an array.

I think dataType should not be part of data object rather should be sibling of success (options). I believe you are not getting data as JSON object rather just string because of it

Related

how to extract JSON object data from laravel API?

I want to extract JSON data from laravel using JQUERY but the result is always undefined.
this is the json code I've got:
{"data":{"id":1,"title":"glove hard","code":"0102","category":"glove"}}
and this is the js code:
$('#show').click(function(){
$.ajax({
url: 'example.com/api/product/1',
method: 'GET',
dataType: 'json',
success: function(data){
$('#result').text(data.category)
}
})
})
Since your code return JSON data is
{"data":{"id":1,"title":"glove hard","code":"0102","category":"glove"}}
The ajax success function parameter is called data and the first key in the json result is named data, to access the value of category, your code should be
$('#show').click(function(){
$.ajax({
url: 'example.com/api/product/1',
method: 'GET',
dataType: 'json',
success: function(data){
//Call the first wrapper key first.
$('#result').text(data.data.category)
}
})
})
Use the $.parseJSON which parse the well formatted json string into js object.
Your success callback will be
success: function(data){
var obj = $.parseJSON(data);
$('#result').text(obj.data.category)
}
Make it even simpler:
jQuery('#show')
.click(function() {
jQuery
.getJSON('example.com/api/product/1')
.done(function(data) {
jQuery('#result').text(data.data.category);
}
});

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 to determine what a PHP page posts back to an AJAX call

I've used ajax quite a bit to send data off to a php page and get something back, but I'm not sure how to determine what specifically gets sent back. I understand what most of the fields here do, but I have a few questions as well.
My current code looks like this:
$.ajax({
url: "search.php",
type: "post",
dataType: "json",
data: {partNumber: q , newType:newType},
success: function(data) {
console.log(data);
}
});
One thing I don't fully understand is how the success: line works. When I say success: function(data), it's my understanding that I'm saying "upon success (of something? I'm not sure what), the information that is returned to this ajax function will be called data," and then inside the brackets, I'm choosing to console.log that data.
Please correct me if I'm wrong in that assumption.
Ultimately, my php page will do a ton of work and return an array with data in it. If the last line of my php code is:
$myArray = array("bob","dan","carl","mike");
how do I choose for that to be returned to ajax? The php page is working fine, but right now my console.log(data) line of code is not returning anything.
You are not supposed to return anything from the php page called by your ajax, you're supposed to echo it (i.e. write it to the response).
echo json_encode($myArray);
And if what you're echoing is not JSon, then take out dataType: "json". The success function means that the request was successful, i.e. a response was received back from the server with status 200. There is also an error method you can use for when you don't get a successful response back.
success: function(data) {
console.log(data);
},
error: function(data) {
console.log("Error: "+data);
}
1) Your on "success" is basically saying when there is not an error that occurs.
Here is testing error
$.ajax({
url: 'search.php',
success: function(){
alert('success');
},
error: function(){
alert('failure');
}
});
2) For your "data" what you echo on the php side gets returned into the variable defined in your
function(results) {
for example if you want to return an array you may want to return "echo" json
your array should include a key and a value
$myArray = array("key" => "value");
echo json_encode($myArray);
and on the jquery side parse the json object returned.
function(data) {
var obj = jQuery.parseJSON(data);
alert(obj.key);
3) Pass JSON Objects
var JSONObject= {"partNumber":q, "newType":newType};
var jsonData = JSON.parse( JSONObject );
var request = $.ajax({
url: "search.php",
type: "POST",
data: jsonData,
dataType: "json"
});

Send multiple JSON objects through AJAX/jQuery returns me an "undefined" array (PHP)

The goal
Send [{"ID": 1, "Name": "XBOX"}, {"ID": 2, "Name": "Playstation 3"}] via $.ajax() using jQuery.
The problem
I have this:
[...]
var object = $.parseJSON(data);
$.ajax({
type: "POST",
url: "laboratory.php",
data: object,
success: function(response) {
console.log(response);
}
});
And, in laboratory.php:
<?php print_r($_REQUEST); ?>
And finally, the return via console is:
Array
(
[undefined] =>
)
This is what the data's variable means:
[{"ID": 1, "Name": "XBOX"}, {"ID": 2, "Name": "Playstation 3"}]
And this is what object means (by Chrome's console):
[Object, Object]
Can someone give me an idea?
have you tried using JSON.stringify:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
$.ajax({
type: "POST",
contentType: 'application/json',
url: "laboratory.php",
data: JSON.stringify(object), // using stringify
success: function(response) {
console.log(response);
}
});
Here's the problem. passing your array of objects to $.param() (which is what jQuery does internally with data: that isn't a string) results in "undefined=undefined&undefined=undefined" which is exactly what you are getting back from php. Your array simply is in a format that jQuery can't understand. Since what you actually want to send is json, don't use $.parseJSON because it'll turn your json into an array and what you really want is just a string.
//var object = $.parseJSON(data);
$.ajax({
type: "POST",
url: "laboratory.php",
data: data,
success: function(response) {
console.log(response);
}
});
For multiple data, getJSON is better in my opinion:
$.getJSON('laboratory.php', function(json) {
$.each(json, function(key, val) {
//Getting the value of id
val["ID"];
//Getting the value of name
val["NAME"];
//DO whatever u want.
});
});

Can a Jquery Ajax Call Accept an Object on Succes from 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
}
});
}

Categories