While loop wont print twice - javascript

Currently I'm trying to print two copies of the same receipt without using the browser-print dialogue. Now unfortunately there is no way to pass the number of copies to the print dialog so the only solution I came up with is doing it in a LOOP, but when looping the print command it does not work! while looping the whole POST method works just fine.
Here's the code before I enter the loop
print function
function p_print(receipt) {
$('#receipt_section').html(receipt.html_content);
__currency_convert_recursively($('#receipt_section'));
__print_receipt('receipt_section');
}
Code without Loop
$.ajax({
method: 'POST',
url: url,
data: data,
dataType: 'json',
success: function(result) {
if (result.success == 1) {
if (result.mail_enabled) {
window.open(result.mail_enabled);
}
$('#modal_payment').modal('hide');
toastr.success(result.msg);
//Check if enabled or not
if (result.receipt.is_enabled) {
p_print(result.receipt);
}
} else {
toastr.error(result.msg);
}
},
});
Functioning loop that prints twice but also POSTS the data twice
var Count = 0;
var Copies = 2;
while ( Count < Copies ) {
$.ajax({
method: 'POST',
url: url,
data: data,
dataType: 'json',
success: function(result) {
if (result.success == 1) {
if (result.mail_enabled) {
window.open(result.mail_enabled);
}
$('#modal_pay').modal('hide');
toastr.success(result.msg);
if (result.receipt.is_enabled) {
p_print(result.receipt);
}
} else {
toastr.error(result.msg);
}
},
});
Count ++;
};
Now If I apply the loop only on p_print(result.receipt) it wont print twice, only by applying it to the whole POST request it would then print twice but also stores the data twice which is not a proper solution at all.
Any help would be very appreciated.

Related

Populate Ajax response with clickable elements that fires another Ajax with correct parameters

So i have a function running an Ajax call that receives data and populate that as a table.
The response contains some rows with data and i now want to add a small fontawsome icon that when clicked fires another function with a parameter.
So i have this:
var latestprecasedata = '';
function getPreCaseData() {
$.ajax({
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
url: "case.aspx/GetPreCase",
dataType: "json",
success: function (response) {
if (response != null && response.d != null) {
var data = response.d;
data = $.parseJSON(data);
$("#PreCaseTblBody").html("");
for (var i in data) {
$("#PreCaseTblBody").append("<tr><td>" + data[i].pSubject + "</td><td><span class='preplus' id='" + data[i].pID + "'><i class='fa fa-plus'></i></span></td><td>-</td></tr>");
}
if (latestprecasedata !== response.d) {
$("#precasestatus").removeClass("titleupd1").addClass("titleupd2");
latestprecasedata = response.d;
}
else {
$("#precasestatus").removeClass("titleupd2").addClass("titleupd1");
}
}
$("#PreCaseTblBody tr:odd").css('background-color', '#f9f9f9'); //
$("#PreCaseTblBody tr:even").css('background-color', '#f1ffee');
setTimeout(getPreCaseData, 10000);
}
});
}
This works and every 10 seconds data is repopulated. (Maybe not the fastest solution, but it works..)
As you all can se i have a span with class=preplus and id of a unique value coming from my Ajax response. When inspecting the page i can see that every row from my Ajax response have a unique id.
For example two row looks like this:
<tr><td>Cables</td><td><span class="preplus" id="4815269"><i class="fa fa-plus"></i></span></td></tr>
<tr><td>Skrews</td><td><span class="preplus" id="4815269"><i class="fa fa-plus"></i></span></td></tr>
So now i have the data populated with span containing a unique id that i want to pass to another function.
I've tried span, div, buttons but the only one time I actually got a event fire was when i placed my second function inside the
for (var i in data) {
... and i know, that's not right at all because all rows contained the last id obviously...
So my other function resides outside my first function and look like this (I've tried many different methods to get the id of my span but for now, I'm here)
$(".preplus").click(function () {
var qID = $(this).attr('id');
$.ajax({
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
url: "case.aspx/UpdateQ",
dataType: "json",
data: "{'qid':'" + qID + "','pm':'plus'}",
success: function (data) {
}
});
return false;
});
Please guide me.

Abort all remaining AJAX requests

I am running an AJAX request when the user types in an input field and then displaying the result on the page. When the user presses the backspace to delete all of what they've inputted, I use .empty to remove the result from the page.
However, if you press the backspaces really quickly, the result is removed from the page, but then because the last AJAX query hasn't last executed, the result from that query appears!!!
I have looked at Abort Ajax requests using jQuery but that didn't help, and have tried adding return: false; after $("#results").empty(); to no avail.
If there are any remaining AJAX calls when if(this.value.length < 1) { is true, I would like to abort them all inside that function.
$("input#enter").keyup(function() {
if(this.value.length < 1) {
$("#display").empty();
}else{
$.ajax({
type: "POST",
url: "getdata.php",
data: "title=" + this.value,
success: function(data) {
$("#display").empty();
$("#display").html(data);
}
});
}
});
You can use $.active to check if $.ajax() call is active before calling next $.ajax()
$("input#enter").keyup(function() {
if(this.value.length < 1) {
$("#display").empty();
}else{
if (!$.active) {
$.ajax({
type: "POST",
url: "getdata.php",
data: "title=" + this.value,
success: function(data) {
$("#display").empty();
$("#display").html(data);
}
});
}
}
});
You can also include attaching .ajaxComplete() to document to call next $.ajax() call when current call completes
function request(value) {
return $.ajax({
type: "POST",
url: "getdata.php",
data: "title=" + value,
success: function(data) {
$("#display").empty();
$("#display").html(data);
}
});
}
$("input#enter").keyup(function() {
if(this.value.length < 1) {
$("#display").empty();
}else{
if (!$.active) {
request(this.value)
} else {
$(document).one("ajaxComplete", function() {
request(this.value)
})
}
}
});
One approach to abort requests is to use XMLHttpRequest(), push requests to an array, then call .abort() on each element of the array
function request(data) {
let fd = new FormData();
fd.append("html", data);
fd.append("delay", Math.floor(Math.random() * 10));
let xhr = new XMLHttpRequest();
xhr.open("POST", "/echo/html/", true);
xhr.onload = function() {
console.log(xhr.responseText);
}
xhr.onabort = function() {
console.log("request " + requests.indexOf(xhr) + " aborted")
}
xhr.send(fd);
return xhr
}
function abortAllRequests() {
requests.forEach(function(xhr, index) {
xhr.abort()
})
}
var requests = [];
requests.push(request(123), request(456));
abortAllRequests();
jsfiddle https://jsfiddle.net/onguym5y/
You talk about aborting ajax requests. It would be sufficient to wait until the request returns and then simply do nothing. Yes, if you were doing a lot of large requests it might improve performance if you cancelled them. But that means using jqXhr objects, and personally I prefer to stick to jQuery where possible.
You could have a variable telling you how up-to-date the #display is. It would store the time of sending of the last ajax request that was used to update it. If you get a response from an earlier request, ignore it.
var lastUpdateTime = 0;
$("input#enter").keyup(function() {
var now = new Date().getTime();
if(this.value.length < 1) {
$("#display").empty();
lastUpdateTime = now;
}else{
$.ajax({
type: "POST",
url: "getdata.php",
data: "title=" + this.value,
success: function(data) {
if (now < lastUpdateTime) {
return;
}
$("#display").empty();
$("#display").html(data);
lastUpdateTime = now;
}
});
}
});

Unexpected characters in image url in ajax response Javascript

In My Codeigniter web application I'm using an ajax function to get some data from the database inorder to show it in the view.The data from database contains an image url and other fields.
My problem is that when I get the data in ajax success function, the image url looks like this:
<button id='product-1301' type='button' value=1301 class='blue' ><i><img src='assets\/uploads\/thumbs\/default.png'></button>
Since the url contains these characters \ my view is not rendering properly. I tried using stripslash function to remove this. But didn't work. I didn't know where am going wrong.
my ajax function
$.ajax({
type: "get",
url: "index.php?module=pos&view=ajaxproducts1",
data: {category_id: cat_id, per_page: p_page},
dataType: "html",
success: function(data) {
var x= data;
alert(x);
if(data!=1)
{
$('#proajax').empty();
var newPrs = $('<div></div>');
newPrs.html(data);
newPrs.appendTo("#proajax");
//$('#gmail_loading').hide();
}
else
{
bootbox.alert('Product is Not Available in this Category!');
$('#gmail_loading').hide();
}
}
});
Controller
function ajaxproducts1()
{
$mn;$data1;
$img="assets/uploads/thumbs/default.png"; //this is my image path, when this comes in ajax success,\ character adds
$img=str_replace('\"', '', $img);
if($this->input->get('category_id')) { $category_id = $this->input->get('category_id'); }
if($this->input->get('per_page')) { $per_page = $this->input->get('per_page'); }
if($item = $this->pos_model->getProductsByCategory($category_id,$per_page))
{
foreach ($item as $i)
{
$button="<button id='product-".$i->id."' type='button' value=".$i->id." class='blue' ><i><img src='".$img."'><span><span>".$i->name;
$mn=$mn.$button;
}
$data1=$mn;
}
else
{
$data1=1;
}
echo json_encode($data1);
}
Can anyone help me with this ?
Try this:
// use an array to gather up all the values
// call encodeURIComponent() on the variables before adding them
// join them all together and pass them as "data"
var tempVars=['module=pos&view=ajaxproducts1'];
tempVars.push('category_id='+encodeURIComponent( cat_id ));
tempVars.push('userInfo='+encodeURIComponent( p_page ));
var sendVars=tempVars.join('&');
$.ajax({
type: "get",
url: "index.php",
data: sendVars,
dataType: "text",
success: function(data) {
var x = data;
alert(x);
if (data != 1) {
$('#proajax').empty();
var newPrs = $('<div></div>');
newPrs.html(data);
newPrs.appendTo("#proajax");
//$('#gmail_loading').hide();
} else {
bootbox.alert('Product is Not Available in this Category!');
$('#gmail_loading').hide();
}
}
});
My issue was solved by using jQuery.parseJSON function.

Javascript/jquery iterate async problems

I would like to iterate through a certain amount of pages, and populate them with content using ajax calls. The problem is, when I put the ajax calls inside the iteration function it has problems with the synchronous nature of javascript. The iteration has already continued before the ajax call is completed. So I made a workaround where I made the ajax call in a setTimeout, which works fine. But I don't really like this method, and was wondering if there is an alternative (better) solution. (I know that jQuery provides a async: true option, however that did not work)
function populatePages(i) {
pageId = PageIds[i];
containerId = pageIdContainer[i];
$j.ajax({
type: 'GET',
dataType: 'html',
url: url,
data: { pageid: pageId, containerid: containerId },
success: function(data) {
//populate the DIV
}
});
}
i = 0;
x = 50;
$j.each(pagesIds, function(){
setTimeout("populatePages("+i+")", x);
x = x + 50;
i++;
});
Try this (not tested)
function populatePages(i) {
console.log('populatePages', i)
pageId = PageIds[i];
return $.ajax({
type: 'GET',
dataType: 'html',
url: '/echo/html',
data: { pageid: pageId},
success: function(data) {
}
});
}
function messy(index){
console.log('messy', index)
if(index >= PageIds.length){
return;
}
populatePages(index).always(function(){
console.log('complete', index)
setTimeout(function(){
messy(index + 1)
});//to prevent possible stackoverflow
})
}
PoC: Fiddle

Pausing for loop after every execution

i have a page, wherein i am using a ajax for inserting records... now in javascript i am using a for each loop to loop the html table and insert the rows in database. but happens is as foreach loop executes fast, it sometime, does not insert some records.. so i want to make the loop sleep for sometime once it has executed first and thereafter...
is there any way to pause the for loop.. i used setTImeout.. but it just delay it first time and not consecutive times...
here's my code.
function AddTopStories() {
$("#tBodySecond tr").each(function (index) {
$.ajax({
type: "POST",
url: "AjaxMethods.aspx/AddTopStoriesPosition",
data: "{'articleID':'" + $("td:nth-child(1)", this).text() + "','siteID':1}",
dataType: "json",
contentType: "application/json",
success: function (data) {
window.setTimeout(showSuccessToast(data.d), 3000);
},
error: function (data) {
window.setTimeout(showSuccessToast("Error:" + data.reponseText), 3000);
}
});
});
}
Please help me to resolve this issue... its utmost important.
*************************************UPDATED CODE AS PER THE CHANGES BY jfriend00*********
function AddTopStories() {
var stories = $("#tBodySecond tr");
var storyIndex = 0;
function addNext() {
if (storyIndex > stories.length) return; // done, no more to get
var item = stories.get(storyIndex++);
alert($("td:nth-child(1)", item).text());
addNext();
}
}
This just does not do anything... does not alert...
I'd recommend you break it into a function that does one story and then you initiate the next story from the success handler of the first like this:
function AddTopStories() {
var stories = $("#tBodySecond tr");
var storyIndex = 0;
function addNext() {
if (storyIndex >= stories.length) return; // done, no more to get
var item = stories.get(storyIndex++);
$.ajax({
type: "POST",
url: "AjaxMethods.aspx/AddTopStoriesPosition",
data: "{'articleID':'" + $("td:nth-child(1)", item).text() + "','siteID':1}",
dataType: "json",
contentType: "application/json",
success: function (data) {
addNext(); // upon success, do the next story
showSuccessToast(data.d);
},
error: function (data) {
showSuccessToast("Error:" + data.reponseText);
}
});
}
addNext();
}
Ugly, but you can fake a javascript 'sleep' using one of the methods on this website:
http://www.devcheater.com/

Categories

Resources