How can control print pop window with javascript - javascript

it is my code, i want to click print cancel then my script not execute i will click ok then this code will run. please give me positive feedback.
(function() {
var afterPrint = function() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log('Responce',this.responseText);
//document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("POST", "<?php echo site_url('AppsCtr/updatePrintLog');?>", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("COMP_CODE=<?php echo $session_company_name;?>&UIL_DOC_NO=<?php echo $head[0]['OPH_TXN_CODE'].'-'.$head[0]['OPH_TXN_NO'];?>&UIL_SYS_ID=<?php echo $head[0]['OPH_SYS_ID'];?>&ACTION=Print&DETAILS=");
};
// supported by Chrome 9+ and Safari 5.1+
if (window.matchMedia) {
var mediaQueryList = window.matchMedia('print');
mediaQueryList.addListener(function(mql) {
if (mql.matches) {
beforePrint();
} else {
afterPrint();
}
});
}
// supported by IE 5+ and FireFox 6+
window.onafterprint = afterPrint;
}());

Ok, your question is little bit bad formatted, i think you want to something when click on ok, and something diferent when click in cancel, well if is that, i suggest to you, use a function with diferent id for example:
<button id="ok" onclick="dosomething(this.id);"></button>
<button id="cancel" onclick="dosomething(this.id);"></button>
<script>
// this is the most important, for separate the diferent actions //
function dosomething(a) {
if (a === "ok") {
// your code of the popup ok //
}
if (a === "cancel") {
// the code of the popup cancel //
}
}
</script>

Related

XMLHttpRequest() is not working in Opera mini

I just Trying to make an asynchronous project with XMLHttpRequest. it works well on other browsers but not working on Opera Mini Mobile Browser. now tell me how can I fix this.
Code:
function runxml(){
var xmlhttpr;
var setup = document.getElementById("setup");
if(window.XMLHttpRequest) {
xmlhttpr = new XMLHttpRequest();
} else {
// for IE8 and Earlier
xmlhttpr = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttpr.onreadystatechange = function(){
if(this.readyState == 4 || this.status == 200) {
setup.innerHTML = this.responseText;
}
}
xmlhttpr.open("GET", "file.txt", true);
xmlhttpr.send();
}

AJAX with better re-usability?

I have my AJAX split in two parts. The "AJHAX" function which has two values, the url of the file to load and then the function where I can specify where I want it to end up ("cFuntion" uses the function "loadToContent"):
First part:
function AJHAX(url, cFunction) {
var xhttp;
// compatible with IE7+, Firefox, Chrome, Opera, Safari
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
Second part:
function loadToContent(xhttp) {
document.getElementById('content').innerHTML =
xhttp.responseText;
}
So from the first part, I can call the functionality in my menu by adding the following to a link / an element:
onclick="AJHAX('page.php', loadToContent)"
However, with this I can only specify which page to load, not which element I want it loaded to. I tried to add it as a criteria for the second part of my code, like this. But to no avail:
function loadToContent(xhttp, targetElement) {
document.getElementById(targetElement).innerHTML =
xhttp.responseText;
}
Onclick:
onclick="AJHAX('menu.php', loadToContent(sidebar))"
Any suggestions?
Solution has been found (thanks to #schogges, please upvote!). Complete working example:
JS:
function AJHAX(url, targetElement, cFunction) {
var xhttp;
// compatible with IE7+, Firefox, Chrome, Opera, Safari
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction(this, targetElement);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function loadToContent(xhttp, targetElement) {
document.getElementById(targetElement).innerHTML =
xhttp.responseText;
}
HTML:
<div onclick="AJHAX('home.php', 'content', loadToContent);closeSidebar()">
Home</div>
So in the HTML, you just specify the page to load, the ID of the element to load the page into and then the "loadToContent" function that actually loads it into to element. As you can see, also have ";closeSidebar()" in there, and even if it does nothing for this example, I'll just leave it here to show anyone new that you can do it this way to add more than one function to an onclick-event. Mine simply just edits some CSS to hide the sidebar.
What about using a third parameter at AJHAX()?
Try this:
function AJHAX(url, target, cFunction) {
var xhttp;
// compatible with IE7+, Firefox, Chrome, Opera, Safari
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction(this, target);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function loadToContent(xhttp, targetElement) {
document.getElementById(targetElement).innerHTML =
xhttp.responseText;
}
and Onclick:
onclick="AJHAX('menu.php', 'sidebar', loadToContent)"
The line onclick="AJHAX('menu.php', loadToContent(sidebar))" doesn't work because it references an inert string.
Instead what you need to do is to reference a function, so it actually carries out the intended task: onclick = function () { AJHAX('https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js', loadToContent);};
Here is a snippet showcasing my answer:
//First part:
function AJHAX(url, cFunction) {
var xhttp;
// compatible with IE7+, Firefox, Chrome, Opera, Safari
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
//Second part:
function loadToContent(xhttp) {
console.log(xhttp.responseText);
alert(xhttp.responseText);
}
//TEST
var button = document.body.appendChild(document.createElement("h1"));
button.textContent = "Click me!";
button.onclick = function () {
AJHAX('https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js', loadToContent);
};

Function call not returning control AJAX - PHP - MYSQLI

I have checked all the similar questions to this but not found anything that helped... so here goes!
I am writing designing a site for my college project. It simply is an image gallery. I have a counter displayed for each image that increments each time the image is clicked. When the page refreshes the new number is displayed. With me so far?
The problem is that after the database update is completed the return does not complete the rest of the code...
echo "<div class='gridImg'><a href=".$imgpath." data-lightbox='countryside' data-title='".$row['ldesc']."' onclick='"."showUser(&#39".$fname."&#39)'>";
The above line is in a php file and the function in question is showUser, which passes a variable $fname...
function showUser(str) {
if (str === "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML =
this.responseText;
}
};
xmlhttp.open("GET","../php/countrysideupdateviews.php?q="+str,true);
xmlhttp.send();
return;
}
}
The above script takes the passed value and hands it over to countrysideupdateviews.php (Sorry if this script is a mess, I am new to AJAX and took it from the W3Schools site.
<?php
$q = $_GET['q'];
$conn=new mysqli('localhost','user','pass','dbname');
$sql="UPDATE countryside SET views = views + 1 WHERE fname = '".$q."'";
$result=$conn->query($sql);
mysqli_close($conn);
?>
The above php file updates the database.
Ok...
So, a user clicks on one of the images on-screen, which opens a lightbox gallery, BUT also updates the view count and then returns control - except that everything works - the update takes place - but the lightbox does not start, instead a static larger image of the one that was clicked is shown. The only way to clear it is to refresh the site, which does reflect the updated counter.
I have added returns to the onclick function call which does return control but the counter is not updated. Where am I going wrong? Bear in mind please I am still learning and I hope this makes sense :)
The argument to onclick must be a function. showUser("foo") is not a function. You're also missing event.preventDefault() which prevents the click action from opening the link.
Change your showUser to
function showUser(str) {
return function(event) {
if (str === "") {
document.getElementById("txtHint").innerHTML = "";
} else {
if (window.XMLHttpRequest) {
var xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","../php/countrysideupdateviews.php?q="+str,true);
xmlhttp.send();
}
event.preventDefault();
};
}
Ok, after playing around with #apaatsio's answer I got it working, this is what the function now looks like...
function showUser(str) {
if (str === "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","../php/countrysideupdateviews.php?q="+str,true);
xmlhttp.send();
event.preventDefault();
}
}
It looks like preventing the click opening the link worked just fine - thanks :)

how to change ckeditor value by javascript

my textarea is:
<textarea class="content" name="content" id="content" rows="10" cols="80"></textarea>
and initializing it as:
<script>
$(document).ready(function(){
///CKeditor
CKEDITOR.replace( 'content', {
height: 320,
} );
});
</script>
now i am getting data in an array and then changing the values of different elements according to it. the array that i am getting is:
[{"id":"5","subject_Id":"1","topic_id":"1","question_type_id":"4","exam_id":"1","difficulty_id":"1","year_id":"1","essay":"","right_marks":"2","negative_marks":"3","question":"question 2","options":"Ans CC~Ans BB~Ans AA~","correct_answer":"Ans BB~"}]
[{"id":"6","subject_Id":"1","topic_id":"1","question_type_id":"4","exam_id":"1","difficulty_id":"1","year_id":"1","essay":"","right_marks":"2","negative_marks":"3","question":"question 1","options":"<img alt=\"\" src=\"\/corePhp\/examinationsystem\/assets\/ckeditor\/kcfinder\/upload\/images\/profile-icon-9(1).png\" style=\"height:512px; width:512px\" \/>~Ans BB~Ans AA~","correct_answer":"Ans BB~"}]
[{"id":"18","subject_Id":"1","topic_id":"1","question_type_id":"1","exam_id":"1","difficulty_id":"1","year_id":"2","essay":"Essay 5","right_marks":"2","negative_marks":"3","question":"Brass gets discoloured in air because of the presence of which of the following gases in air?","options":"Oxygen~Hydrogen sulphide~Carbon dioxide~Nitrogen","correct_answer":"\"Hydrogen sulphide\""}]
then in my javascript
<script type="text/javascript">
function dbDataQuestion(quesId) {
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)
{
var convert=JSON.parse(xmlhttp.responseText);
//console.log(convert[0].subject_Id);
document.getElementById("selectSubject").value=convert[0].subject_Id;
document.getElementById("selectTopic").value=convert[0].topic_id;
document.getElementById("selectQuestionType").value=convert[0].question_type_id;
document.getElementById("selectExam").value=convert[0].exam_id;
document.getElementById("selectYear").value=convert[0].year_id;
document.getElementById("selectDiffLvl").value=convert[0].difficulty_id;
document.getElementById("txtRightMarks").value=convert[0].right_marks;
document.getElementById("txtNegMarks").value=convert[0].negative_marks;
console.log(convert[0].question_type_id);
console.log(convert[0].question);
CKEDITOR.on("instanceReady", function(event)
{
//CKEDITOR.instances.content.insertHtml(convert[0].question);
CKEDITOR.instances.content.focus();
CKEDITOR.instances.content.setData(convert[0].question);
});
if(convert[0].essay){
document.getElementById("txtEssayName").value=convert[0].essay;
document.getElementById("radioEssayYes").checked = true;
}
else{
document.getElementById("txtEssayName").value=convert[0].essay;
document.getElementById("radioEssayNo").checked = true;
}
}
}
xmlhttp.open("POST","process/questions/quesDetails.php?quesId="+quesId, false);
xmlhttp.send();
}
</script>
as you can see i am consoling console.log(convert[0].question); in which i am getting correct data, but when i am writing CKEDITOR.instances.content.setData(convert[0].question); its not updating ck editor's value.
actually the function "dbDataQuestion(quesId)" is being called once at the time of page load at that time its working fine the CKEditor is showing question 2 which you can see is in the first array, after that I have a button on which I am getting the next array and so on. on clicking this button array is getting displayed in the console as well as other element are changing its values but CKEditor is showing the same old value that is question 1 and not question 2 on consoling console.log(convert[0].question); I am getting "question 2" which is correct.
Note: function dbDataQuestion(quesId) is where from where i am getting above mentioned array and on xmlhttp.readyState === 4 && xmlhttp.status === 200 of the function i am changing the values of the elements which includes ck editor. its once called at the time of page load and then its being called on a button click:
<button type="button" class="btn btn-xs btn-success" onclick="fetchQuestionDetails('next')">Next</button>
I am calling all my scripts at the bottom of the page.
thanks in advance.
Update:
I noticed that instanceReady event is not getting triggered by calling the function when the button is pressed. I altered my code to check
console.log(convert[0].question);
CKEDITOR.on("instanceReady", function(event)
{
console.log(convert[0].question);
console.log("sss");
CKEDITOR.instances.content.focus();
CKEDITOR.instances.content.setData(convert[0].question);
});
only console.log(convert[0].question); is getting triggered and none of the other console statements. What am I doing wrong?
first thanks a lot #Muhammad Omer Aslam for responding, so quickly. i have not tried your answer but i ll try it and comment if it solved the problem or not but i found a way to make it work i removed instanceReady event and wrote
setTimeout(function(){
CKEDITOR.instances.content.setData(convert[0].question);
}, 1000);
and its working fine. but again thanks #Muhammad Omer Aslam
try it the following way by moving the initialization inside the ajax response section.
$(document).ready(function () {
dbDataQuestion(quesId);
});
Your function will look like this.
function dbDataQuestion(quesId) {
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) {
var convert = JSON.parse(xmlhttp.responseText);
//console.log(convert[0].subject_Id);
document.getElementById("selectSubject").value = convert[0].subject_Id;
document.getElementById("selectTopic").value = convert[0].topic_id;
document.getElementById("selectQuestionType").value = convert[0].question_type_id;
document.getElementById("selectExam").value = convert[0].exam_id;
document.getElementById("selectYear").value = convert[0].year_id;
document.getElementById("selectDiffLvl").value = convert[0].difficulty_id;
document.getElementById("txtRightMarks").value = convert[0].right_marks;
document.getElementById("txtNegMarks").value = convert[0].negative_marks;
console.log(convert[0].question_type_id);
console.log(convert[0].question);
///CKeditor
CKEDITOR.replace('content', {
height: 320,
});
CKEDITOR.on("instanceReady", function (event) {
//CKEDITOR.instances.content.insertHtml(convert[0].question);
CKEDITOR.instances.content.focus();
CKEDITOR.instances.content.setData(convert[0].question);
});
if (convert[0].essay) {
document.getElementById("txtEssayName").value = convert[0].essay;
document.getElementById("radioEssayYes").checked = true;
} else {
document.getElementById("txtEssayName").value = convert[0].essay;
document.getElementById("radioEssayNo").checked = true;
}
}
}
xmlhttp.open("POST", "process/questions/quesDetails.php?quesId=" + quesId, false);
xmlhttp.send();
}

setInterval runs continuously in Firefox on Android

I have a short snippet of Javascript which I want to poll a server every couple of seconds and update the DOM.
function updateCard() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
card = JSON.parse(this.responseText);
document.getElementById("season").innerHTML = card.season;
}
};
xhttp.open("GET", "/curr_card/", true);
xhttp.send();
}
window.onload = updateCard;
window.setInterval(updateCard,2000);
On most browsers that's what happens. There are a few one-off calls to updateCard, but on the whole the server shows ~1/2 connection per second per client.
However, when I access the page in Firefox on Android (49.0) the browser starts continuously polling /curr_card/, tens of times a second.
I've seen people suggest replacing the setInterval line with window.setInterval(function() {updateCard();},2000);, this doesn't help.
I'm pretty new to Javascript and AJAX, so have no idea why this is happening. Is it a bug in FF? I can post more code if requested.
Thanks in advance.
After testing and discussing in OP's comments, we concluded this must be an issue specific to Firefox on the OP's HTC M7, as it could not be reproduced on the same version Firefox on a Galaxy S7.
That may happen not only with Firefox on some device.
It may happen when response has not finished because of servers late answer but it sends another request and so on...
What if to do like this:
function updateCard(before, after) {
if(before) {
before();
}
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
card = JSON.parse(this.responseText);
document.getElementById("season").innerHTML = card.season;
}
if(after) {
after();
}
};
xhttp.open("GET", "/curr_card/", true);
xhttp.send();
}
window.onload = updateCard;
var updateCardRunning = false;
setInterval(function() {
if(updateCardRunning === true) {
console.log('postponing to next schedule');
return;
}
updateCard(
function() {updateCardRunning = true;},
function() {updateCardRunning = false;}
);
}, 2000);
or:
function updateCard() {
var xhttp = new XMLHttpRequest();
window.xhttp = xhttp;
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
card = JSON.parse(this.responseText);
document.getElementById("season").innerHTML = card.season;
}
};
xhttp.open("GET", "/curr_card/", true);
xhttp.send();
}
window.onload = updateCard;
setInterval(function() {
if(window.xhttp) {
window.xhttp.abort();
}
updateCard();
}, 2000);

Categories