Ajax - How to use a returned array in a success function
You should return the data as JSON from the server.
PHP
$arr = array();
$arr[0] = "Mark Reed";
$arr[1] = "34";
$arr[2] = "Australia";
echo json_encode($arr);
exit();
JS
$.ajax({
type: "POST",
url: "/returndetails.php",
data: 'id=' + userid,
dataType: "json", // Set the data type so jQuery can parse it for you
success: function (data) {
document.getElementById("name").innerHTML = data[0];
document.getElementById("age").innerHTML = data[1];
document.getElementById("location").innerHTML = data[2];
}
});
How to access an array returned from controller to ajax success
You are using .each()
instead of $.each()
, so you treat data
as DOM selectors. Instead of that you should use:
$.each(data.data, function (key, value) {
('#journalLogs').append($('<tr id="'+ value.journal_id +'">'
+ '<td class="dateJournal">'+ value.date +'</td>'
+ '<td class="accountJournal">'+ value.account +'</td>'
+ '<td class="debitJournal">'+ parseFloat(value.debit).toFixed(2) +'</td>'
+ '<td class="creditJournald">'+ parseFloat(value.credit).toFixed(2) +'</td>'
+ '</tr>'));
});
Check documentation for both of them:
.each()
$.each()
Updated according to the array structure. You need to iterate over first dimension and then after the second, so:
$.each(data.data, function (type, typeData) { // type is "credit" or "debit"
$.each(typeData, function (key, value) {
('#journalLogs').append($('<tr id="'+ value.journal_id +'">'
+ '<td class="dateJournal">'+ value.date +'</td>'
+ '<td class="accountJournal">'+ value.account +'</td>'
+ '<td class="debitJournal">'+ parseFloat(value.debit).toFixed(2) +'</td>'
+ '<td class="creditJournald">'+ parseFloat(value.credit).toFixed(2) +'</td>'
+ '</tr>'));
});
});
How to return array in php to $.ajax success function
You need to do 2 thing
remove html and add array collection. This is how your DBCOMANSWERS.php must be look like
<?php
include("connection.php"); //includes mysqli_connent with database
include("ErrorHandler.php"); //includes error handling function
set_error_handler("ErrorHandler"); //set the new error handler
$q = intval($_GET['q']);
$sql="SELECT * FROM tbl_answers WHERE QID ='".$q."'"; //define sql statement
$query = mysqli_query($con,$sql); // get the data from the db
$result = [];
while ($row = $query->fetch_array(MYSQLI_ASSOC)) { // fetches a result row as an associative array
$result [] = $row['answer'];
}
mysqli_close($con); // close connection with database
header('Content-Type: application/json');
echo json_encode($result); // return value of $result
?>
Then in your html as @madalinivascu suggests
success: function(result){ //Performs an async AJAX request
result.forEach(function(i,v){
$("#output").append(v.answer);
})
}}
How to return an array from jQuery ajax success function properly?
In your code, you are looking for groups
using procedural coding after the ajax call was made. The main problem is that you are looking for groups
before the ajax call is complete.
Another problem is that you are returning groups to the success()
function, but the TheObject.getArray()
function returns nothing.
So you need to bring in the callback into the ajax function like this:
TheObject = {
getArray: function(callback) {
var groups = new Array;
$.ajax({
type: "POST",
url: "link.php",
success: function (data){
var counter = 0;
$('g',data).each(function(){
var group_name = $(this).find("name").text();
var group_id = $(this).find("id").text();
var group = {
id: group_id,
name: group_name
}
groups[counter] = group;
counter++;
});
callback.call(this,groups);
}
});
}
}
TheObject.getArray(function(a) {
// this code runs when the ajax call is complete
alert(a);
});
Save ajax return data to an array and call that array outside of ajax
Create an empty array at the very top of your function, and push the new URL's into as they come in. Then use the array later.
ie:
let surahArr = []
//..inside ajax success
surahArr.push(urlServer + '/' + resUrl + '.mp3');
//then later in your app, you can loop over them
for(let surah of surahArr){
//do stuff with surah
}
return an array from jQuery ajax success function
I'm assuming you're just loading the rss feed once then creating a carousel with the result. If so, this is easy to fix.
Look for this line:
var mycarousel_itemList = [];
That is creating a local variable inside the ajax success callback. What you'll want to do is make it global and move it to the top (make it the very first line inside the < script> tag).
Move the $.ajax call to inside the document ready callback.
Find the following jcarousel code:
jQuery('#mycarousel').jcarousel({
size: mycarousel_itemList.length,
itemLoadCallback: {onBeforeAnimation: mycarousel_itemLoadCallback}
});Move it to inside the $.ajax callback as the last thing in the callback.
Your final code should look like this: http://jsfiddle.net/h35VQ/
How to return an array from jQuery ajax success function and use it in a loop?
I would do something like this:
setInterval(updateTimestamps,30000);
var ids = new Array();
function updateTimestamps(){
$(".timestamp").each(function(i){
var obj = new Object();
obj.id = $(this).attr("postID");
obj.timestamp = $(this).attr("postdate");
ids.push(obj);
}
$.post("http://site.com/ajax/humanTime.php", {"time": ids}, function(data) {
for (i = 0; i < data.length; i++) {
$("#" + data[i].id).html(data[i].content);
}
}, "json");
}
EDIT:
And in humanTime.php:
<?php
$ids = json_decode($_POST['time']);
foreach($ids as $id) {
// Calculate human time ...
}
?>
then return something like this:
[{id:1, content:1 minute ago}, {id:3, content: 5 hours ago}]
PS: This solution is what you requested, but I think Bram aproach is better.
Jquery Ajax success function based on array response
Give a conditional look at your response.
$.ajax({
url: "<?php echo base_url().'admin/creditcard/authorize';?>",
type:'POST',
data: postData,
dataType: 'json',
success: function(output_string){
if(x = $.parseJSON(output_string)){
if(x.property == 'true'){ //or if(x.property != null){
$(".authorization_result").append(x);
}else{
$(".authorization_result").append("fail");
}
}else{
$(".authorization_result").append("fail");
}
}
});
Ajax returns array of objects to jquery and php
Well each loop of your foreach
will erase the data defined in the preview loop, so when your foreach
is done iterating you end up with the last set of data.
You don't need to iterate through the array, because your query already returns an array
$sql = "SELECT ......";
$results = Db::getInstance()->ExecuteS($sql);
echo json_encode($results);
Now if you want to access you data from the success function you just need call them the same name as your rows. for instance if you rows are product_id, date, and name you will call them that way:
function getData(id){
$.ajax({
url: 'ajax_info.php',
type: 'POST',
dataType:'json',
data: {id: id},
success: function(response) {
response = JSON.parse(response);
console.log("Product id is: " + response[0].product_id);
console.log("Product name is: " + response[0].name);
console.log("Product date: " + response[0].date);
}
});
}
You also need to understand the following: say for some reason you want to have different variable name for your json without changing your database then you will have to do the following:
$sql = "SELECT ......";
$results = Db::getInstance()->ExecuteS($sql);
$newResults = array();
foreach ($results as $row)
{
$newResults[] = array('newId' => $row['product_id'], 'newName' => $row['name'], 'newDate' => $row['date']);
}
echo json_encode($newResults);
Which will result of changing the variables in JSON:
function getData(id){
$.ajax({
url: 'ajax_info.php',
type: 'POST',
dataType:'json',
data: {id: id},
success: function(response) {
response = JSON.parse(response);
console.log("Product id is: " + response[0].newId);
console.log("Product name is: " + response[0].newName);
console.log("Product date: " + response[0].newDate);
}
});
}
Related Topics
Hosting Your Own JavaScript Scripts Files (Other Than Jquery) on Fast Free Cdns Like Google
Reactjs Dynamic Drop Down Populated With Map Function
Detect Click into Iframe Using JavaScript
How to Close Current Tab in a Browser Window
Change Image on Scroll Position
Converting Excel Date Serial Number to Date Using JavaScript
Why Am I Not Able to Add Input Text into My Table
How to Pass Checkbox State to Onclick Function in React
How to Call the Same Method for Different Elements With Different Ids
Reactjs How to Call a Component Function from Another Function on the Same File
Datatables/Tabletools: Format Data as Text When Exporting to Excel
Passing Value from Java to JavaScript
Postman Test - Validating String Values in an Object in an Array
Javascript Json Parsing Error: Unexpected Token ' in Json At Position 1
Check If a Key Exists Inside a Json Object
How to Detect Overflow of React Component Without Reactdom