Getting duplicate prints - javascript

I am facing some unidentified issue. please any one help me to sort out.
problem is when runonload() function runs, we will get print but I am getting duplicate prints (with same data). but this function executes one time (logs in this function write one time) but fnQrCode() & fnBuildBody() calling twice (logs in these function writes twice and getting prints twice). there is no loop for second time. Below is my code snippet.
var xmlcodebar="";
---
---
function runonload(){
code for print preparation
-------
-------
fnQrCode(dealref,sterlingQR, deliveryType); //this function for qr code generation
xmlcodebar = "data:image/png;base64,"+xmlcodebar;
footer11 = '<td width="100%"><img src='+xmlcodebar+' align="center" width="750" height="150"></td>';
footer12 = '</tr></table>';
fnBuildBody(strRows,strPrintData, Number(strPageLength),footer1,footer2, footer3, footer4, footer5, footer6, footer7, footer8,footer9, footer10, footer11, footer12); //this function for printing
-------
--------
}
function fnQrCode(dealref,sterlingQR,deliType){
var data =sterlingQR+";"+dealref+"$;"+deliType;
var strQueryString = "hdnOptPage=QRCODE&DATA="+data;
xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert("Browser doesn't supports Http Request");
return;
}
var url = "<%=CONTROLSERV_TFROUT%>"+"?"+strQueryString;
xmlHttp.onreadystatechange = stateBarcode;
xmlHttp.open("POST",url,false);
xmlHttp.send();
}
function stateBarcode() {
if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
if(xmlHttp.status == 404 || xmlHttp.status == 500){
alert("Problem occured at server. Please try again.");
window.event.returnValue=false;
return;
} else if (xmlHttp.status == 200) {
xmlcodebar = xmlHttp.responseText;
}
}
}
function GetXmlHttpObject() {
var objXMLHttp = null;
//check whether browser supports HttpRequest
if (window.XMLHttpRequest) {
objXMLHttp = new XMLHttpRequest();
} else {
if (window.ActiveXObject) {
objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return objXMLHttp;
}

Related

Ajax condition is not working in the jquery mobile phonegap

In Ajax the condition given to check the readystate and status is not working in the jquery mobile phonegap.I checked it by giving an alert message inside the condition. why? And I attached the code
function checkLogin()
{
// navigator.notification.alert("hiii");
var username;
var password;
var x=new XMLHttpRequest();
x.onreadystatechange=function()
{
// alert("....."+x.responseText);
if (x.readyState == 4 && x.status == 200)
{
// alert(x.readyState+" --- "+x.status);
alert("hai checkLogin");
var item=x.responseText.trim();
alert("Message :"+item);
if(item=="1")
{
window.location="home.html";
}
}
}
//alert("open");
x.open("POST", "http://localhost:8087/CarRental/com/selcar/getLogin.jsp?username="+document.getElementById('username').value+"&password="+document.getElementById('loginpaswrd').value, true);
x.send();

else clause to repeat ajax triggers too many times

I have an ajax function on my website which calls a cgi script. infrequently, this script returns a 500 error. I am trying to change the AJAX call so that when this happens, it will repeat the request. I have tried to do that as follows:
function shelverx() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//process data if successful...
} else if (xmlhttp.status == 500) {
limit++;
if (limit < 5) {
shelverx(usershelf);
}
}
}
xmlhttp.open("POST", filepath, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(postdata);
}
I'm wondering if there is a better way to accomplish this? I find that what happens is that whenever there is a 500 error, the shelverx function is called four times, even if the second call is successful. Is there a way to repeat the call only once per error?
I also tried to accomplish the same thing by changing the entire ajax call to jQuery and using the following error function:
error: function(xhr, textStatus, errorThrown ) {
this.tryCount++;
if (this.tryCount<=this.retryLimit) {
$.ajax(this);
return;
}
But I got an Unexpected Token : error. If anyone could help me to get either of these methods to work I would appreciate it greatly. My goal is to have the ajax call repeat only once per 500 error.
Jonathan -
The code snippet below works as you want. The counter holds its value between calls and stops requests at 5. I also changed the IF statement logic and added a timer to wait 1 second between tries. Give it a try.
Note that the original logic doesn't work correctly. In the debugger it was incrementing the counter multiple times per each request. Much better to check status after readyState = 4.
Original Code:
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//process data if successful...
} else if (xmlhttp.status == 500) {
limit++;
if (limit < 5) {
shelverx(usershelf);
}
}
Tested and working example:
<!doctype html>
<html>
<body>
<script type="text/javascript">
var postdata = '';
var filepath = 'NothingHere.html';
var limit = 0;
function shelverx() {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
console.info('Success: Recieved ' + xmlhttp.responseText.length + ' bytes');
}
else {
limit++;
console.info( 'Error: ' + xmlhttp.status + ':' + xmlhttp.statusText );
if (limit < 5) setTimeout( shelverx, 1000 );
}
}
}
xmlhttp.open("POST", filepath, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(postdata);
}
shelverx();
</script>
</body>
</html>

validate multiple ajax call complete successfully in javascript

In my application i'am making two ajax call for getting some data from database based on another variable value.
code part:
var xmlHttp;
var redirect;
function populate_site(obj, passedselect) {
xmlHttp = GetXmlHttpObject();
var site_type;
if (obj.value) {
site_type = obj.value
}else {
site_type = document.app.site_type.value;
}
var url="/cgi-bin/Web/Begin.cgi";
url=url+"?redirect=Get_Site_List";
url=url+"&site_type=" + site_type;
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function stateChanged() {
if (xmlHttp.readyState == 4){
document.getElementById('site_id').innerHTML = xmlHttp.responseText;
}
}
function Populate_Process_List(obj, process_id_param) {
var action_id;
if (obj.value) {
action_id = obj.value
}else {
action_id = document.app.action_id.value;
}
xmlHttp = GetXmlHttpObject();
if (obj.value == '') {
document.getElementById('process_id').innerHTML = ' ';
return false;
}
var url="/cgi-bin/Web/Begin.cgi";
url=url+"?redirect=Fetch_User_Process_List";
url=url+"&action_id=" + action_id;
url=url+"&process_id=" + process_id_param;
url=url+"&gp_flag=" + 'YES';
xmlHttp.onreadystatechange= Process_Data_StateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function Process_Data_StateChanged() {
if(xmlHttp.responseText != 'NA') {
if (xmlHttp.readyState == 4){
document.getElementById('process_id').innerHTML = xmlHttp.responseText;
}
}
}
function GetXmlHttpObject(){
var xmlHttp1=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp1=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp1=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp1=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp1;
}
And validating site_id and process_id variable using JavaScript.
Problem facing is whenever user press the submit button before ajax call loading is not completed (since me passing async parameter of the open() method has as true). Even while validating the site_id and process_id variable using JavaScript is not getting captured.
Validation code:
var siteaddindex = document.app.site_id[document.app.site_id.selectedIndex].value;
if(siteaddindex == "null"){
alert("Please select site location.");
document.app.site_id.focus();
return false;
}
var process_id = document.app.process_id.value;
if (process_id == '') {
alert("Please select process");
return false;
}
Please let me know how to perform validation of above fields, since those fields are mandatory.

Run getElementById bound to success of AJAX call

I'm building a small quiz. The score is stored in a variable quizScore - each question on the quiz is output using AJAX. The single AJAX call grabs the ID of the button pressed (so, on question 2, the button ID is 2a which takes you to the next AJAX refresh of question2a.php)
On the last AJAX call, which calls up a file called questionendQuiz.php, I want to have the output of the variable quizScore. I need to bind this output to an event, so success of loading that through AJAX makes sense.
/* Output score */
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("quizWrapper").innerHTML=xmlhttp.responseText;
if (buttonID == "question_endQuiz") {
document.getElementById("scoreOut").innerHTML = quizScore;
}
}
So this should output quizScore into div id="scoreOut" when the successful AJAX content loads.
I've double checked the score is actually working by using console logs. It is building the score correctly (see here it outputs the score in the console http://francesca-designed.me/quiz/quiz.php
I can't work out what is wrong with the success if statement to cause it to not output the score?
AJAX request, I've omitted some things that aren't useful to this question like the correct answer scoring and the start of the quiz:
/* Quiz Score */
var quizScore = 0; /* Takes you to each next question, based on ButtonID */
function nextQuestion(buttonID) {
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("quizWrapper").innerHTML = xmlhttp.responseText;
}
}
var splitID = buttonID.split('_');
var questionID = splitID.pop();
xmlhttp.open("GET", "question" + questionID + ".php", true);
xmlhttp.send(); /* Output score */
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("quizWrapper").innerHTML = xmlhttp.responseText;
if (buttonID == "question_endQuiz") {
document.getElementById("scoreOut").innerHTML = quizScore;
}
}
}
The button that marks the end of the quiz is:
<button id="question_endQuiz" onClick="nextQuestion(this.id)">See your score</button>
The score recording part should go into onreadystatechange as well. It is the callback for the request, and gets executed after the response is received, rather than before as in the code you provided.
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("quizWrapper").innerHTML = xmlhttp.responseText;
if (buttonID == "question_endQuiz") {
document.getElementById("scoreOut").innerHTML = quizScore;
}
}
}

Timeout method after hitting the url

We have the following method to invoke the URL using ajax.
Currently after hitting the url we are using the response.
So we want to put a timeout for reposne.So when we invoke the url if the response didn't came after 2sec then call one more method and if resp comes within two seconds call other mehtod.
We have tried using the timeout,but unable to made it working with the code.
function ajaxCall(url1) {
var ajaxresp = null;
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", url1, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
ajaxresp = xmlhttp.responseText;
//function call
getAdResponse(ajaxresp);
}
}
}
}
Please advice me how to proceed.
Try smth like this
xmlhttp.open("GET",url1,true);
xmlhttp.onreadystatechange= function (){
if (xmlhttp.readyState==4){
if (xmlhttp.status == 200){
ajaxresp = xmlhttp.responseText;
}
}
xmlhttp.send();
setTimeout(function() {
if(ajaxresp) {
dosmth(ajaxresp);
} else {
dosmthelse();
}
}, 2000);

Categories

Resources