I want to create async AJAX query to check server status when web page finish loading. Unfortunately when it comes to data display from processed PHP, I receive only single value.
JS:
<script>
window.onload = function() {
test();
};
function test()
{
var h = [];
$(".hash td").each(function(){
var hash = $(this).closest('#h').text();
if (hash) {
$.ajax({
url: 'stat.php',
method: 'POST',
async: true,
data: {hs: JSON.stringify(hash)},
success: function(data) {
$('.result').replaceWith(data);
}
});
}
});
}
</script>
PHP:
<?php
require_once ('inc/config.php');
require_once ('inc/libs/functions.php');
if (isset($_POST['hs'])) {
$hash = json_decode($_POST['hs']);
serverstatus($hash);
}
function serverstatus($hash) {
$address = DB::queryFirstRow("SELECT address,hash FROM servers WHERE hash=%s", $hash);
$address_exploded = explode(":", $address['address']);
$ip = $address_exploded[0];
$port = $address_exploded[1];
$status = isServerOnline($ip,$port);
if ($status) {
$s = "Online $ip";
} else {
$s = "Offline";
}
echo $s;
}
?>
I embed result from PHP to a table row. I see that AJAX iterating over the array, but all rows receive same value (last checked element in array).
$('.result') matches all elements with the class result. replaceWith will then replace each of them with the content you provide.
If you want to only affect the .result element within some structure (perhaps the same row?), you need to use find or similar:
function test()
{
var h = [];
$(".hash td").each(function(){
var td = $(this); // <====
var hash = td.closest('#h').text();
var result = td.closest("tr").find(".result"); // <====
if (hash) {
$.ajax({
url: 'stat.php',
method: 'POST',
async: true,
data: {hs: JSON.stringify(hash)},
success: function(data) {
result.replaceWith(data); // <====
}
});
}
});
}
Obviously the
var result = td.closest("tr").find(".result"); // <====
...will need to be tweaked to be what you really want it to be, but that's the idea.
This line in your question suggests an anti-pattern:
var hash = $(this).closest('#h').text();
id values must be unique in the document, so you should never need to find the one "closest" to any given element. If you have more than one id="h" element in the DOM, change it to use a class or data-* attribute instead.
Thank you all for help. My final, obviously very dirty but working code:
function testServerPage()
{
var h = [];
$(".hash li").each(function(){
var hash = $(this).closest('#h').text();
if (hash) {
$.ajax({
url: 'stat.php',
method: 'POST',
//async: true,
data: {hs: JSON.stringify(hash)},
success: function(data) {
$('#' + hash).replaceWith(data);
}
});
}
});
return false;
}
I just added dynamic variable to element:
success: function(data) {
$('#' + hash).replaceWith(data);
}
I want to pass data via AJAX. The variable consists of both numbers and non-alphanumeric variables ("001.0/210.00"). My $_POST['task'] doesn't return a value. I've attempted to change the data to JSON, but that doesn't seem to work.
$(document).ready(function(e){
var trigger = $('.task a'),
var container = $('#content1');
trigger.on('click', function(e){
var shotElement = event.currentTarget.children[0].innerText;
$.ajax({
type : 'POST',
url : 'indexPipeline.php',
data : { task: shotElement },
success : function(response) {
$("#displayPipeline").load("indexPipeline.php");
}
});
return false;
});
});
I currently have setup a AJAX to PHP set of functions that processes a number of items on a page. Basically the code inserts a series of tasks into the database, then inserts supplies into the database based on those newly created task ID's. However it works 90% of the time. Sometimes it seems as though the Task ID's are not created first which doesn't allow the supplies to use those ID's for inserting into the database. Is there a way to make sure that the task is inserted, then all supplies are inserted for that ID, then move onto the next one. At the end when all is complete I would like to redirect to a new page, again I put this in the last success call on the supplies portion, but it would redirect on the first loop. This process usually generates around 5 tasks, with 12 supplies per each task. I was reading about a $.when loop but could not get it to work. NOTE: after testing the ajax calls are submitting correctly, it was that one field on some of them was null, and the DB was having an issue. So the counter method below works.
$(document).on("click", "#submitTasks", function(e) {
e.preventDefault();
var tasks = $('#tasks').find('.box');
var project_id = $('#project_id').val();
tasks.each(function() {
var trs = $(this).find('.reqTables').find('.table').find('tbody').find('tr');
var task_definition_id = $(this).find('.task_definition_id').val();
var labor_type_id = $(this).find('.laborAmount').children('option:selected').val();
var task_status_id = 1;
var qty_labor = $(this).find('.laborQty').val();
var amount_labor = $(this).find('.laborTotal').val();
var amount_materials = $(this).find('.matTotal').val();
var amount_gst = $(this).find('.gstTotal').val();
amount_materials = +amount_materials + +amount_gst;
amount_materials = amount_materials.toFixed(2);
var active = 1;
//console.log(div)
var task = {
project_id : project_id,
task_definition_id : task_definition_id,
labor_type_id : labor_type_id,
task_status_id : task_status_id,
qty_labor : qty_labor,
amount_labor : amount_labor,
amount_materials : amount_materials,
active : active
};
saveTasks(task, trs, project_id);
});
});
function saveTasks(task, trs, project_id) {
$.ajax({
type : "POST",
url : "<?php echo base_url(); ?>" + "mgmt/project/saveTasks",
data : task,
dataType : "json",
cache : "false",
success : function(data) {
trs.each(function() {
var total = $(this).find('input[name="calculatedCost"]').val();
if (total != 'n/a') {
var task_id = data;
var supply_id = $(this).find('.suppliesPicker').children('option:selected').val();
var task_requirement_id = $(this).find('td:first-child').data('id');
var qty = $(this).find('input[name="calculatedQty"]').val();
var cost_per = $(this).find('.costPicker').val();
var delivery_cost = $(this).find('input[name="transport"]').val();
var notes = '';
var qty_actual = '';
var active = 1;
var taskSupply = {
task_id : task_id,
supply_id : supply_id,
task_requirement_id : task_requirement_id,
qty : qty,
cost_per : cost_per,
delivery_cost : delivery_cost,
total : total,
notes : notes,
qty_actual : qty_actual,
active : active
};
saveTaskSupplies(taskSupply);
console.log(taskSupply);
}
});
}
});
}
function saveTaskSupplies(taskSupply) {
$.ajax({
type : "POST",
url : "<?php echo base_url(); ?>" + "mgmt/project/saveTaskSupplies",
data : taskSupply,
dataType : "json",
cache : "false",
success : function(data) {
***** I WANT TO REDIRECT TO A NEW PAGE WHEN THE LAST ONE OF THESE COMPLETES ******
}
});
}
This code will wait for nested loop ajax function calls to finish their promises, then proceed..
var allPromises;
$(document).on("click", "#submitTasks", function(e) {
//...
var tasks = $('#tasks').find('.box');
allPromises = [];
tasks.each(function() {
//.. somehow getTask
var req = saveTasks(task, trs, project_id);
allPromises.push(req);
});
$.when.apply(null, allPromises).done(function(){
// Do your things here,
// All save functions have done.
});
});
function saveTasks(task, trs, project_id) {
return $.ajax({
// ,,, your codes
success : function(data) {
// ...
trs.each(function() {
// ... Somehow get taskSupply
var req = saveTaskSupplies(taskSupply);
allPromises.push(req);
}
}
});
}
function saveTaskSupplies(taskSupply) {
return $.ajax({
// ... bla bla bla
success : function(data) {
// Whatever..
}
});
}
Here is a direct solution using the code you provided. The basic concept is to increment a counter as supplies are processed. Once the counter reaches the total number of supplies, a procedure is run. See comments throughout.
var totalTaskSupplies = 0;
var processedTaskSupplies = 0;
$(document).on("click", "#submitTasks", function(e) {
e.preventDefault();
var tasks = $('#tasks').find('.box');
var project_id = $('#project_id').val();
tasks.each(function() {
var trs = $(this).find('.reqTables').find('.table').find('tbody').find('tr');
var task_definition_id = $(this).find('.task_definition_id').val();
var labor_type_id = $(this).find('.laborAmount').children('option:selected').val();
var task_status_id = 1;
var qty_labor = $(this).find('.laborQty').val();
var amount_labor = $(this).find('.laborTotal').val();
var amount_materials = $(this).find('.matTotal').val();
var amount_gst = $(this).find('.gstTotal').val();
// Add number of supplies for current task to total task supplies
totalTaskSupplies += trs.length;
amount_materials = +amount_materials + +amount_gst;
amount_materials = amount_materials.toFixed(2);
var active = 1;
//console.log(div)
var task = {
project_id : project_id,
task_definition_id : task_definition_id,
labor_type_id : labor_type_id,
task_status_id : task_status_id,
qty_labor : qty_labor,
amount_labor : amount_labor,
amount_materials : amount_materials,
active : active
};
saveTasks(task, trs, project_id);
});
});
function saveTasks(task, trs, project_id) {
$.ajax({
type : "POST",
url : "<?php echo base_url(); ?>" + "mgmt/project/saveTasks",
data : task,
dataType : "json",
cache : "false",
success : function(data) {
trs.each(function() {
var total = $(this).find('input[name="calculatedCost"]').val();
if (total != 'n/a') {
var task_id = data;
var supply_id = $(this).find('.suppliesPicker').children('option:selected').val();
var task_requirement_id = $(this).find('td:first-child').data('id');
var qty = $(this).find('input[name="calculatedQty"]').val();
var cost_per = $(this).find('.costPicker').val();
var delivery_cost = $(this).find('input[name="transport"]').val();
var notes = '';
var qty_actual = '';
var active = 1;
var taskSupply = {
task_id : task_id,
supply_id : supply_id,
task_requirement_id : task_requirement_id,
qty : qty,
cost_per : cost_per,
delivery_cost : delivery_cost,
total : total,
notes : notes,
qty_actual : qty_actual,
active : active
};
saveTaskSupplies(taskSupply);
console.log(taskSupply);
}
});
}
});
}
function saveTaskSupplies(taskSupply) {
$.ajax({
type : "POST",
url : "<?php echo base_url(); ?>" + "mgmt/project/saveTaskSupplies",
data : taskSupply,
dataType : "json",
cache : "false",
success : function(data) {
++processedTaskSupplies;
// All supplies have been processed
if (processedTaskSupplies == totalTaskSupplies) {
// Do something
}
}
});
}
Regarding the first question, by studying your code I couldn't see the reason of it. You only execute the saveTaskSupplies() when saveTasks() has executed successfully, so the task_id should already be created.
However, I would think of another possible problem from your backend, in your Ajax success function in saveTasks(), You assume the PHP script always execute successfully and return the task_id. Would it be possible that your PHP script has some problem and the task_id is not created in some instance?
For the second question, there are a few approaches, as #Seth suggest you can use jQuery.when, or you can create a global counter to keep track of whether the saveTaskSupplies() is the last one. Note that you should calculate the total length of trs before firing the Ajax request, otherwise, you may have a chance of having a not well-calculated total and redirecting before all tasks are done. If it is the last one it will redirect after successful Ajax call.
// create a global counter
var counter = 0,
trl = 0;
$(document).on("click", "#submitTasks", function(e) {
...
var trList = [];
tasks.each(function() {
// calculate the length of total task before actually firing the Ajax Request
var trs = $(this).find('.reqTables').find('.table').find('tbody').find('tr');
// keep a copy of the trs so the next each loop does not have to find it again
trList.push(trs);
trl += trs.length;
});
tasks.each(function() {
// get the trs of current iteration we have found in last loop
var trs = trList.shift();
...
saveTasks(task, trs, project_id);
});
});
function saveTasks(task, trs, project_id) {
$.ajax({
...
success : function(data) {
trs.each(function() {
...
saveTaskSupplies(taskSupply);
}
}
});
}
function saveTaskSupplies(taskSupply) {
$.ajax({
...
success : function(data) {
// check if the counter exceed the length of trs
if (++counter == trl) {
location.href = 'place you want to go';
}
}
});
}
On the other hand, for your task I would also suggest shifting the responsibility of data insertion to PHP backend, so all you need to do is to pass the task information and the task supplies at once to a single PHP script. This approach allows the use of Transaction to make sure all data insertion is success or otherwise all should fail.
hey guys i read some of the other posts and tried alot but its still not working for me.
when i alert the array i get all the results on the first site but after sending the data to php i just get an empty result. any ideas?
$(document).ready(function() {
$('#Btn').click(function() {
var cats = [];
$('#cats input:checked').each(function() {
cats.push(this.value);
});
var st = JSON.stringify(cats);
$.post('foo.php',{data:st},function(data){cats : cats});
window.location = "foo.php";
});
});
Php
$data = json_decode($_POST['data']);
THANK YOUU
my array looks something like this when i alert it house/flat,garden/nature,sports/hobbies
this are a couple of results the user might choose (from checkboxes).
but when i post it to php i get nothing. when i use request marker (chrome extension) it shows me something likethat Raw data cats=%5B%22house+themes%22%2C%22flat+items%22%5D
i also tried this way-- still no results
$(document).ready(function() {
$('#Btn').click(function() {
var cats = [];
$('#cats input:checked').each(function() {
cats.push(this.value);
alert(cats);
$.ajax({
type: 'POST',
url: "foo.php",
data: {cats: JSON.stringify(cats)},
success: function(data){
alert(data);
}
});
});
window.location = "foo.php";
});
});
php:
$json = $_POST['cats'];
$json_string = stripslashes($json);
$data = json_decode($json_string, true);
echo "<pre>";
print_r($data);
its drives me crazy
Take this script: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
And call:
var myJsonString = JSON.stringify(yourArray);
so now your code is
$(document).ready(function() {
$('#Btn').click(function() {
var cats = [];
$('#cats input:checked').each(function() {
cats.push(this.value);
});
var st = JSON.stringify(cats);
$.post('foo.php',{data:st},function(data){cats : cats});
// window.location = "foo.php"; // comment this by this page redirect to this foo.php
});
});
//and if uou want toredirect then use below code
-------------------------------------------------
$.post('foo.php',{data:st},function(data){
window.location = "foo.php";
});
---------------------------------------------------
Php
$data = json_decode($_POST['data']);
var ItemGroupMappingData = []
Or
var ItemGroupMappingData =
{
"id" : 1,
"name" : "harsh jhaveri",
"email" : "test#test.com"
}
$.ajax({
url: 'url link',
type: 'POST',
dataType: "json",
data: ItemGroupMappingData,
success: function (e) {
// When server send response then it will be comes in as object in e. you can find data //with e.field name or table name
},
error: function (response) {
//alert(' error come here ' + response);
ExceptionHandler(response);
}
});
Try this :-
$data = json_decode($_POST['data'], TRUE);
I think you should move the "window.location = " to the post callback, which means it should wait till the post finshed and then redirect the page.
$.post('foo.php', {
data : st
}, function(data) {
window.location = "foo.php";
});
I am adding a LoadMore function to append more posts based on the length of current displayed posts and total posts in DOM. The issue I am having is when I console log the listofposts and I inspect the element in Google Chrome, I see the length is showing zero (0). I am not sure exactly where I have gone wrong or if the aproach I have taken is right or should I separate the two functions by first loading the first 4 posts, then create a new function separate to handle the appending?
$(document).on('pagebeforeshow', '#blogposts', function() {
//$.mobile.showPageLoadingMsg();
$.ajax({
url: "http://howtodeployit.com/category/daily-devotion/?json=recentstories&callback=",
dataType: "json",
jsonpCallback: 'successCallback',
async: true,
beforeSend: function() { $.mobile.showPageLoadingMsg(true); },
complete: function() { $.mobile.hidePageLoadingMsg(); },
success:function(data){
var $listofposts = $('data');
console.log($listofposts);
var $loadMore = $listofposts.parent().find('.load-more');
// console.log($loadMore);
currentPage = 0;
postsPerPage = 4;
var showMorePosts = function () {
$offset = currentPage * postsPerPage, //initial value is 0
posts = data.posts.slice($offset, $offset + postsPerPage);
console.log(posts);
$.each(posts, function(i, val) {
//console.log(val);
$("#postlist").html();
var result = $('<li/>').append([$("<h3>", {html: val.title}),$("<p>", {html: val.excerpt})]).wrapInner('');
$('#postlist').append(result);
console.log(result);
});
if(posts.length !== postsPerPage){
alert ('True');
$loadMore.hide();
}
currentPage++;
$("#postlist").listview();
$("#postlist").listview('refresh');
}
showMorePosts();
$loadMore.on('click', showMorePosts);
}});
var $listofposts = $('data');
is asking jQuery for a list of all <data> tags in the document.
You might want to use $(data) instead.