Run two ajax calls at the same time? - php

If I have one ajax call with a long foreach loop where I update a text file, and at the same time I want to read that file and display changed content from the first call by another second call, how can I achieve that?
When the first runs, the second waits until the first one has finished.
I want to run the first and second at the same time. In the second call, every second I want to check the state inside the file created by the first call - something like a progress bar.
function startTimer(){
timer = window.setInterval(refreshProgress, 1000);
}
function refreshProgress(){
$.ajax({
type: "POST",
url: '/index.php?/system/run_progress_checker',
dataType:"json",
success: function(data)
{
console.log(data);
if (data.percent == 100) {
window.clearInterval(timer);
timer = window.setInterval(completed, 1000);
}
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
}
function completed() {
//$("#message").html("Completed");
window.clearInterval(timer);
}
$(".systemform").submit(function(e) { //run system
$.when(startTimer(),run_system()).then(function(){});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
function run_system(){
$("#leftcontainer").html("");
$("#leftcontainer").show();
$("#chartContainer").hide();
$(".loading").show();
var sysid = $(".sysid:checked").val();
var oddstype = $(".odds_pref").val();
var bettypeodds = $(".bet_type_odds").val();
var bookie = $(".bookie_pref").val();
if (typeof oddstype === "undefined") {
var oddstype = $(".odds_pref_run").val();
var bettypeodds = $(".bet_type_odds_run").val();
var bookie = $(".bookie_pref_run").val();
}
$.ajax({
type: "POST",
url: '/index.php?/system/system_options/left/'+'1X2/'+oddstype+'/'+bettypeodds+'/'+bookie,
data: {
system : sysid,
showpublicbet : showpublicbet }, // serializes the form's elements.
dataType:"json",
success: function(data)
{
console.log(data);
$("#systemlist").load('/index.php?/system/refresh_system/'+sysid,function(e){
systemradiotocheck();
});
$("#resultcontainer").load('/index.php?/system/showresults/'+sysid+'/false');
$("#resultcontainer").show();
$("#leftcontainer").html(data.historic_table);
$("#rightcontainer").html(data.upcoming_table);
var count = 0;
var arr = [];
$("#rightrows > table > tbody > tr").each(function(){
var row = $(this).data('row');
if(typeof row !== 'undefined'){
var rowarr = JSON.parse(JSON.stringify(row));
arr[count] = rowarr;
$(this).find('td').each(function(){
var cell = $(this).data('cell');
if(typeof cell !== 'undefined'){
var cellarr = JSON.parse(JSON.stringify(cell));
arr[count][6] = cellarr[0];
}
});
count ++;
}
});
if(oddstype == "EU" && bookie == "Bet365"){
$('.bet365').show();
$('.pinnacle').hide();
$('.ukodds').hide();
}
if(oddstype == "EU" && bookie == "Pinnacle"){
$('.pinnacle').show();
$('.bet365').hide();
$('.ukodds').hide();
}
if(oddstype == "UK"){
$('.bet365').hide();
$('.pinnacle').hide();
$('.ukodds').show();
}
if(bookie == "Pinnacle"){
$(".pref-uk").hide();
}
else{
$(".pref-uk").show();
}
$(".loading").hide();
runned = true;
var options = {
animationEnabled: true,
toolTip:{
content: "#{x} {b} {a} {c} {y}"
},
axisX:{
title: "Number of Games"
},
axisY:{
title: "Cumulative Profit"
},
data: [
{
name: [],
type: "splineArea", //change it to line, area, column, pie, etc
color: "rgba(54,158,173,.7)",
dataPoints: []
}
]
};
//console.log(data);
var profitstr = 0;
var parsed = $.parseJSON(JSON.stringify(data.export_array.sort(custom_sort)));
var counter = 0;
for (var i in parsed)
{
profitstr = profitstr + parsed[i]['Profit'];
//console.log(profitstr);
var profit = parseFloat(profitstr.toString().replace(',','.'));
//console.log(profit);
var event = parsed[i]['Event'].toString();
var hgoals = parsed[i]['Home Goals'].toString();
var agoals = parsed[i]['Away Goals'].toString();
var result = hgoals + ":" + agoals;
var date = parsed[i]['Date'].toString();
var bettype = parsed[i]['Bet Type'];
var beton = parsed[i]['Bet On'];
var handicap = parsed[i]['Handicap'];
//alert(profitstr);
//alert(profit);
//options.data[0].name.push({event});
counter++;
options.data[0].dataPoints.push({x: counter,y: profit,a:event,b:date,c:result});
}
$("#chartContainer").show();
$("#chartContainer").CanvasJSChart(options);
$(".hidden_data").val(JSON.stringify(data.export_array));
$(".exportsys").removeAttr("disabled");
$(".exportsys").removeAttr("title");
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
}
Backend part is not so important because it works.

Sounds like a great case for jQuery's $.when $.then. In the first part, the $.when, you'll have the first ajax call, and when that is finished... you can port the data from the first part to the $.then part. For example:
$.when(
//perform first ajax call and pass this data to the 'then'.
$.ajax(
{
type: "POST",
url: "<<insert url>>",
contentType: "application/json; charest=utf-8",
success: function (data) {
//process data
},
error: function (XMLXHttpRequest, textStatus, errorThrown) {
}
})
).then(function (data, textStatus, jqXHR) {
var obj = $.parseJSON(data); // take data from above and use it to perform second ajax call.
var params = '{ "CustomerID": "' + obj[0].CustomerID + '" }';
$.ajax(
{
type: "POST",
url: "<<insert url>>",
data: params,
contentType: "application/json; charest=utf-8",
success: function (data) {
//process data
},
error: function (XMLXHttpRequest, textStatus, errorThrown) {
}
})
});
}
});

Related

Save Ajax JQuery selector in an array

I'm very new with Ajax and I need help to store the data from an Ajax request into an array. I looked at answers here at the forum, but I'm not able to solve my problem.The Ajax response is going into $('#responseField').val(format(output.response)) and I'm want store "output.response" into an array that can be used outside of the Ajax. I tried to declare a variable outside of the Ajax and call it later, but without success. I'm using $json_arr that should get the data. How do I do to get the data from the Ajax and store it in a variable to be used outside of the Ajax? This variable will an array that I can access the indexes.
function sendRequest(postData, hasFile) {
function format(resp) {
try {
var json = JSON.parse(resp);
return JSON.stringify(json, null, '\t');
} catch(e) {
return resp;
}
}
var value; // grade item
$.ajax({
type: 'post',
url: "doRequest.php",
data: postData,
success: function(data) { //data= retArr
var output = {};
if(data == '') {
output.response = 'Success!';
} else {
try {
output = jQuery.parseJSON(data);
} catch(e) {
output = "Unexpected non-JSON response from the server: " + data;
}
}
$('#statusField').val(output.statusCode);
$('#responseField').val(format(output.response));
$("#responseField").removeClass('hidden');
data = $.parseJSON(output.response)
$json_arr=$('#responseField').val(format(output.response));
},
error: function(jqXHR, textStatus, errorThrown) {
$('#errorField1').removeClass('hidden');
$("#errorField2").innerHTML = jqXHR.responseText;
}
});
}
window.alert($json_arr);
let promise = new Promise(function(resolve, reject) {
$.ajax({
type: 'post',
url: "doRequest.php",
data: postData,
success: function(data) { //data= retArr
var output = {};
if(data == '') {
output.response = 'Success!';
} else {
try {
output = jQuery.parseJSON(data);
} catch(e) {
output = "Unexpected non-JSON response from the server: " + data;
}
}
$('#statusField').val(output.statusCode);
$('#responseField').val(format(output.response));
$("#responseField").removeClass('hidden');
data = $.parseJSON(output.response)
resolve(format(output.response));
},
error: function(jqXHR, textStatus, errorThrown) {
$('#errorField1').removeClass('hidden');
$("#errorField2").innerHTML = jqXHR.responseText;
}
});
});
promise.then(
function(result) { /* you can alert a successful result here */ },
function(error) { /* handle an error */ }
);
The issue is you are calling asynchronously.
You call the alert synchronously, but it should be called asynchronously.
A little snippet to help you see the difference:
// $json_arr initialized with a string, to make it easier to see the difference
var $json_arr = 'Hello World!';
function sendRequest() {
$.ajax({
// dummy REST API endpoint
url: "https://reqres.in/api/users",
type: "POST",
data: {
name: "Alert from AJAX success",
movies: ["I Love You Man", "Role Models"]
},
success: function(response){
console.log(response);
$json_arr = response.name;
// this window.alert will appear second
window.alert($json_arr);
}
});
}
sendRequest();
// this window.alert will appear first
window.alert($json_arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

loop Ajax Response in select Option tag

i have to select multiple tests and date and when clicked on submit based on the test,laboratory names are loaded in select option
Ajax script
$('[name=submits]').click(function(e)
{
e.preventDefault();
var array = [];
$('select :selected').each(function(i,value)
{
array[i] = $(this).val();
});
var testdate = $("#appointmentdate10").val();
//here make your ajax call to a php file
$.ajax({
type: "POST",
url: "http://localhost/refer/index.php/details",
data: { laboratory_tests: array, testdate: testdate },
success: function(data){
// alert(data);
console.log(data);
var selOpts = "";
for (i=0;i<data.length;i++)
{
var id = data[i]['laboratory_id'];
var val = data[i]['laboratory_name'];
selOpts += "<option value='"+id+"'>"+val+"</option>";
}
$('#yourSelect').append(selOpts);
}
});
});
Ajax success response is:
[
{"laboratory_id":"19","laboratory_name":"ghc","laboratory_address":"cgc","laboratory_place":"jhggj","laboratory_tests":"MRI R\/L SHOULDER WITH CONTRAST"},
{"laboratory_id":"20","laboratory_name":"BBNB","laboratory_address":"sdfds","laboratory_place":"sdfsd","laboratory_tests":"MRI R\/L SHOULDER WITH CONTRAST"},
{"laboratory_id":"22","laboratory_name":"Anand","laboratory_address":"bsk","laboratory_place":"bengaluru","laboratory_tests":"MRI R\/L SHOULDER WITH CONTRAST"}
]
html
<select class="form-control" id="yourSelect">
</select>
but i am not able to display in select tag
$.ajax({
url: config.routes.profitsReport,
type: "POST",
dataType: 'json',
success: function (result) {
$.each(result, function (i, value) {
$('#category_profit').append('<option id=' + JSON.stringify(value.id) + '>' + JSON.stringify(value.name) + '</option>');
});
},
error: function (request, status, error) {
alert(request.statusText + "[" + request.status + "]");
alert(request.responseText);
$('button#form_salesReport_button').html(config.messages.searchReport);
}
});
Try to loop through the result like this:
success: function(data){
// alert(data);
console.log(data);
var selOpts = "";
$.each(data, function(k, v)
{
var id = data[k].laboratory_id;
var val = data[k].laboratory_name;
selOpts += "<option value='"+id+"'>"+val+"</option>";
});
$('#yourSelect').append(selOpts);
}
You can loop
[
{"laboratory_id":"19","laboratory_name":"ghc","laboratory_address":"cgc","laboratory_place":"jhggj","laboratory_tests":"MRI R\/L SHOULDER WITH CONTRAST"},
{"laboratory_id":"20","laboratory_name":"BBNB","laboratory_address":"sdfds","laboratory_place":"sdfsd","laboratory_tests":"MRI R\/L SHOULDER WITH CONTRAST"},
{"laboratory_id":"22","laboratory_name":"Anand","laboratory_address":"bsk","laboratory_place":"bengaluru","laboratory_tests":"MRI R\/L SHOULDER WITH CONTRAST"}
]
via
var options = "";
for (let item in array) {
options += `<option value=${item.id}>${item.laboratory_name}</option>`;
}
document.getElementById("yourSelect").innerHTML = options;
If it's a String, you can convert it to an array via JSON.parse.
If you are expecting json data from ajax request then you need to require to add dataType as json.
$('[name=submits]').click(function(e)
{
e.preventDefault();
var array = [];
$('select :selected').each(function(i,value)
{
array[i] = $(this).val();
});
var testdate = $("#appointmentdate10").val();
//here make your ajax call to a php file
$.ajax({
type: "POST",
dataType: "json",
url: "http://localhost/refer/index.php/details",
data: { laboratory_tests: array, testdate: testdate },
success: function(data){
// alert(data);
console.log(data);
var selOpts = "";
for (i=0;i<data.length;i++)
{
var id = data[i]['laboratory_id'];
var val = data[i]['laboratory_name'];
selOpts += "<option value='"+id+"'>"+val+"</option>";
}
$('#yourSelect').append(selOpts);
}
});
});

Ajax data isn't being received by php

Hello overflowers!
I can't seem to manage to send my ajax data over to my php page correctly, it has worked perfectly fine before but now it is not working.
I'm getting the correct data via console.log but on my php page i'm getting Undefined index error.
Jquery
var task_takers_pre = [];
var task_takers = [];
var i = 1;
$(".new-task-takers ul.select_takers li").on('click', function(){
$(this).each(function(){
$(this).toggleClass("active");
if($(this).find('.fa').length > 0){
$(this).find('.fa').remove();
i -= 1;
var removeItem = $(this).data("id");
task_takers_pre.remove(removeItem);
console.log(task_takers_pre);
}else{
$('<i class="fa fa-check" aria-hidden="true"></i>').insertBefore($(this).find("div"));
i += 1;
task_takers_pre[i] = $(this).data("id");
console.log(task_takers_pre);
}
$.each(task_takers_pre, function (index, value) {
if ($.inArray(value, task_takers) == -1) {
task_takers.push(index, value);
}
});
});
});
$("#new-task").on('submit', function(){
console.log(task_takers_pre);
$.ajax({
type: 'POST',
url: '',
cache: false,
data: {task_takers_pre : task_takers_pre },
success: function(data) {
//console.log(data)
}
});
});
PHP
if(isset($_POST['task_submit'])){
$task_takers = $_POST['task_takers_pre'][0];
var_dump($task_takers);
}
EDIT
jQuery
var task_takers_pre = [];
var task_takers = [];
var i = 1;
$(".new-task-takers ul.select_takers li").on('click', function(){
$(this).each(function(){
$(this).toggleClass("active");
if($(this).find('.fa').length > 0){
$(this).find('.fa').remove();
i -= 1;
var removeItem = $(this).data("id");
task_takers_pre.remove(removeItem);
console.log(task_takers_pre);
}else{
$('<i class="fa fa-check" aria-hidden="true"></i>').insertBefore($(this).find("div"));
i += 1;
task_takers_pre[i] = $(this).data("id");
console.log(task_takers_pre);
}
$.each(task_takers_pre, function (index, value) {
if ($.inArray(value, task_takers) == -1) {
task_takers.push(index, value);
}
});
});
});
$(".assign").on('click', function(){
console.log(task_takers_pre);
$.ajax({
type: 'POST',
url: './core/includes/new_task.php',
cache: false,
data: {task_takers_pre : task_takers_pre},
success: function(data) {
//console.log(data)
}
});
$.ajax({
type: 'POST',
url: '',
cache: false,
data: {'task_takers_pre' : task_takers_pre},
success: function(data) {
//console.log(data)
}
});
});
PHP
if(isset($_POST['task_takers_pre'][0])){
$task_takers = $_POST['task_takers_pre'][0]; // Just for testing
var_dump($task_takers); // Just for testing
}
if(isset($_POST['task_takers_pre'])){
$task_takers2 = $_POST['task_takers_pre']; // Just for testing
var_dump($task_takers2); // Just for testing
}
What you are attempting to do is use the same PHP code to handle the Button Press from the Form AND the AJAX Call. Don't!
(note: This answer is Only based upon the code that has been provided and what is trying to achieved with this code.)
So your current PHP is, which I am guessing is what you call when you click the submit button... In that case $_POST['task_takers_pre'] will not exist as you are generating that from the JS and sending it in the AJAX Call.
Write a separate AJAX Call.
You need to create a separate file to handle your AJAX calls and have it perform what duties it needs to perform.
// This is just for testing my AJAX Call
public function ajax_post(){
if(isset($_POST['task_takers_pre'])){
$task_takers = $_POST['task_takers_pre'][0]; // Just for testing
var_dump($task_takers); // Just for testing
die();
}
else {
// Illegal access/entry do something...
echo 'Error - I had better check what I am posting.';
die();
}
}
If you juse want to send some data in the AJAX Call when you click the submit button,you could return false to prevent form submission in the submit event.
$("#new-task").on("submit", function(){
$.ajax({
type: "POST",
url: "",
cache: false,
data: {task_submit:1, task_takers_pre: task_takers_pre},
success: function(data){
console.log(data);
}
});
return false;
});

jQuery use ajax and json to switch page with button

Hi so I have a JS file with a function for my button, this button get value from different checkbox in a table. But now i want to get these value on another page (for invoice treatement).
Here is my Script :
$("#boutonfacturer").click(function () {
var checked = $('input[name="id_commande[]"]:checked');
var tab = [];
var jsonobj = {};
checked.each(function () {
var value = $(this).val();
jsonobj.value = value;
tab.push(jsonobj);
});
var data= { recup : tab };
console.log(data);
$.ajax({
type: 'POST',
url: 'genererfacture-facture_groupee.html',
data: data,
success: function (msg) {
if (msg.error === 'OK') {
console.log('SUCCESS');
}
else {
console.log('ERROR' + msg.error);
}
}
}).done(function(msg) {
console.log( "Data Saved: " + msg );
});
});
i use an MVC architecture so there is my controller :
public function facture_groupee() {
$_POST['recup'];
var_dump($_POST['recup']);
console.log(recup);
$this->getBody()->setTitre("Facture de votre commande");
$this->getBody()->setContenu(Container::loader());
$this->getBody()->setContenu(GenererFacture::facture_groupee());
and for now my view is useless to show.
I have probably make mistake in my code.
Thank you.
Nevermind after thinking, I have used my ajax.php page which get my another page thanks to a window.location :
my JS :
$("#boutonfacturer").click(function () {
var checked = $('input[name="id_commande[]"]:checked');
var tab = [];
checked.each(function () {
var value = $(this).val();
tab.push(value);
});
var data = {recup: tab};
console.log(data);
$.ajax({
type: 'POST',
url: 'ajax.php?action=facture_groupee',
data: data,
success: function (idfac) {
console.log("Data Saved: " + idfac);
var id_fac = idfac;
window.location = "ajax.php?action=facture_groupee=" + id_fac;
}
});
});
my php :
public function facture_groupee() {
foreach ($_POST['recup'] as $p){
echo $p; }

Two ajax post simultaneously on one link click jquery

I am using one link which has class name next and id end.
On clcik on it both class name and id i am using jquery post.
The issue i am getting is sometimes the ajax request fires multiple times on one click.on one click i am getting data from one url and simultaneously saving these data into db by another url.So sometimes there are some issues coming while inserting into db.sometimes null values enters and sometimes multiple rows entering into db.So how can i write these two functions so that both will work perfectly?
$('.next').live('click', function (e) {
e.preventDefault();
var result = [];
var answer = [];
var le = '';
$('.answertext').each(function (index, element) {
result.push($(this).val());
});
$('.answer').each(function (index, element) {
answer.push($(this).val());
});
le = $('#level').val();
mle = $('#mainlevel').val();
$.ajax({
url: 'matchanswers.php',
type: 'POST',
data: {
result: result,
answer: answer,
level: le,
mle: mle
},
async: true,
beforeSend: function () {
// show indicator
},
complete: function () {
// hide indicator
},
success: function (data) {
$('.quizform').html(data);
}
});
});
$('#end').live('click', function (e) {
e.preventDefault();
var sublev = $('#level').val();
var score = $('#count').val();
if (sublev < 11) {
$.ajax({
url: 'submitanswers.php',
type: 'POST',
data: {
sublev: sublev,
score: score
},
async: true,
beforeSend: function () {
// show indicator
},
complete: function () {
// hide indicator
},
success: function (data2) {}
});
} else {
$.ajax({
url: 'getanswers.php',
type: 'POST',
data: {
sublev: sublev,
score: score
},
async: true,
beforeSend: function () {
// show indicator
},
complete: function () {
// hide indicator
},
success: function (data3) {
if (data3) {
$('.quizform').html("");
$('form :input').attr('disabled', 'disabled');
$('#logout').removeAttr("disabled");
var obj = $.parseJSON(data3);
$('#sum').html("Your Total Score for level - " + obj[0] + " is " + obj[1] + " in " + obj[2] + "secs");
}
}
});
}
});
You are firing click on same click even if id and class are different the link is same.
$('.next').live('click', function(e)
fires one ajax call and
$('#end').live('click', function(e)
fires another, what you can do is fire one ajax on success of other
$('.next').live('click', function(e) { ...
success: function(data) { $.ajax({
url: 'submitanswers.php', }
but this is not good practice
Simply check for the event trigger like :
$('.next').live('click', function (e) {
if(e.handled !== true){ // This will prevent event triggering more then once
e.handled = true;
//Your code
}
});
$('#end').live('click', function (e) {
if(e.handled !== true){ // This will prevent event triggering more then once
e.handled = true;
//Your code
}
});
By doing so, you will stop multiple event trigger which is quite a common problem and should solve your problem.
Edit :
Your full code will be :
$('.next').live('click', function (e) {
if (e.handled !== true) { // This will prevent event triggering more then once
e.handled = true;
//Your code
e.preventDefault();
var result = [];
var answer = [];
var le = '';
$('.answertext').each(function (index, element) {
result.push($(this).val());
});
$('.answer').each(function (index, element) {
answer.push($(this).val());
});
le = $('#level').val();
mle = $('#mainlevel').val();
$.ajax({
url: 'matchanswers.php',
type: 'POST',
data: {
result: result,
answer: answer,
level: le,
mle: mle
},
async: true,
beforeSend: function () {
// show indicator
},
complete: function () {
// hide indicator
},
success: function (data) {
$('.quizform').html(data);
}
});
}
});
$('#end').live('click', function (e) {
if (e.handled !== true) { // This will prevent event triggering more then once
e.handled = true;
//Your code
e.preventDefault();
var sublev = $('#level').val();
var score = $('#count').val();
if (sublev < 11) {
$.ajax({
url: 'submitanswers.php',
type: 'POST',
data: {
sublev: sublev,
score: score
},
async: true,
beforeSend: function () {
// show indicator
},
complete: function () {
// hide indicator
},
success: function (data2) {}
});
} else {
$.ajax({
url: 'getanswers.php',
type: 'POST',
data: {
sublev: sublev,
score: score
},
async: true,
beforeSend: function () {
// show indicator
},
complete: function () {
// hide indicator
},
success: function (data3) {
if (data3) {
$('.quizform').html("");
$('form :input').attr('disabled', 'disabled');
$('#logout').removeAttr("disabled");
var obj = $.parseJSON(data3);
$('#sum').html("Your Total Score for level - " + obj[0] + " is " + obj[1] + " in " + obj[2] + "secs");
}
}
});
}
}
});

Categories