My Ajax works just fine until I add a conditional status property.
Here's the snippet
if (XMLHttp.readyState==4 && XMLHttp.status==200){
// do something
}
and here's the complete code
function getXMLHttp()
{
try
{
var xmlhttp = new XMLHttpRequest();
// document.getElementById("Content").innerHTML="<h1>Using XMLHttpRequest Object</h1>";
//alert('Mozilla XMLHttpRequest Obeject Created Successfully');
}
catch(err1)
{
var ieXmlHttpVersions = new Array();
ieXmlHttpVersions[ieXmlHttpVersions.length] = "MSXML2.XMLHttp.7.0";
ieXmlHttpVersions[ieXmlHttpVersions.length] = "MSXML2.XMLHttp.6.0";
ieXmlHttpVersions[ieXmlHttpVersions.length] = "MSXML2.XMLHttp.5.0";
ieXmlHttpVersions[ieXmlHttpVersions.length] = "MSXML2.XMLHttp.4.0";
ieXmlHttpVersions[ieXmlHttpVersions.length] = "MSXML2.XMLHttp.3.0";
ieXmlHttpVersions[ieXmlHttpVersions.length] = "MSXML2.XMLHttp";
ieXmlHttpVersions[ieXmlHttpVersions.length] = "Microsoft.XMLHttp";
var i;
for (i=0; i < ieXmlHttpVersions.length; i++)
{
try
{
var xmlhttp = new ActiveXObject(ieXmlHttpVersions[i]);
// var catatan = "<h1>Using " + ieXmlHttpVersions[i] + "</h1>";
break;
}
catch (err2)
{
var xmlhttp = null;
//alert(ieXmlHttpVersions[i] + " not supported.");
}
}
}
if (typeof xmlhttp == "undefined" || xmlhttp == null){
//document.getElementById("Content").innerHTML="<h1>XMLHttp cannot be created!</h1>";
alert('XMLHttp Request Object Is not Supported Somehow');
}
return xmlhttp;
}
var XMLHttp = getXMLHttp();
function loadData(url, targetID){
if(!url) {var url="data.txt";}
if(!targetID){var targetID='ajaxID';}
XMLHttp.onreadystatechange = function (){getResponse(targetID)};
XMLHttp.open('GET', url, true);
XMLHttp.send(null);
}
function getResponse(targetID){
var data = XMLHttp.responseText;
var ajaxContent=document.getElementById('ajax_content');
if(XMLHttp.readyState == 4){
// This works Just fine, data from data.txt actually fetched
// BUT When i Add this if statement with " && XMLHttp.status==200" It's not returning data from data.txt
if(data.length > 0){
fill(targetID,data);
}
}
}
function fill(ID,data){
hideLoading();
document.getElementById(ID).innerHTML = data;
}
function showLoading(){
document.getElementById('loading').style.visibility='';
document.getElementById('loading_text').innerHTML = '....Loading Please Wait....';
}
function hideLoading(){
document.getElementById('loading').style.visibility = 'hidden';
document.getElementById('loading_text').innerHTML = '';
}
My question is why I can't get the data from data.txt when I add && XMLHttp.status==200 statement ?
Could your web-server be returning one of the other 'success' status codes from the HTTP specification?
Try testing if (XMLHttp.status >= 200 && XMLHttp.status < 300).
Can you tell us whether you know or don't know if execution-flow is getting to the fill(targetID,data) line? It would be very unusual if the XMLHttp.status check were interfering in the actual data retrieval step.
From what you've told us, it seems that XMLHttp.readyState must be reaching 4 without XMLHttp.status == 200. Have I misinterpreted your question?
I think its the problem in creating the XMLHTTP object. try use the basic syntax that has been provided by w3schools.
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert("Your browser does not support XMLHTTP!");
}
its work for me or use jquery or prototype.
Related
I wrote different code (at least twice) where Ajax is supposed to change an innerHTML-value by a database call (GET). While the first requests succedes in a 100 % of the time (changing a value in the database) the next commands that extracts the new Information to update the HTML-file fails in about 20-30 % of the time, receiving the wrong response from the xerver (an old value).
I tried tracking the error but can't find it since it only appears sometimes after a call. The following code is just the relevant part of my problem.
<p>I like <b><span id="numCom"><?php echo liked_comments(); ?></span></b> comments.</p>
// Each comment has a likeComment and CountComments function that triggers the Ajax:
let likeIcon = document.getElementsByClassName("like-icon");
for(let i = 0; i < likeIcon.length; i++){
likeIcon[i].addEventListener("click", likeComment);
likeIcon[i].addEventListener("click", countComments);
}
function likeComment(){
let child = this.children[0];
let mainID = this.parentElement.parentElement.id;
url = "ajax/like_comment.php";
let xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function(){
if(this.status == 200){
let result = this.responseText;
if(result == "t"){
child.classList.remove("red-text");
} else if (result == "f") {
child.classList.add("red-text");
}
}
}
xhr.send("com_id=" + mainID);
}
function countComments(){
let numCom = document.getElementById("numCom");
let xhr = new XMLHttpRequest();
let url = "ajax/count_liked_comments.php";
xhr.open("GET", url, true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.onload = function(){
if(this.status == 200){
numCom.innerHTML = this.responseText;
}
}
xhr.onerror = function(){
console.log("Error");
};
xhr.send();
}
// In the php-files these functions are executed:
function like_comment($id){
global $db;
$check_query = "SELECT liked FROM comments WHERE comment_id = $id LIMIT 1";
$check_result = mysqli_query($db, $check_query);
while($stm = mysqli_fetch_array($check_result)){
$l = $stm['liked'];
}
if($l == 0){
// UPDATE TO 1
$query = "UPDATE comments SET liked = 1 WHERE comment_id = $id LIMIT 1";
$result = mysqli_query($db, $query);
return $result;
} else if($l == 1) {
// UPDATE TO 0
$query = "UPDATE comments SET liked = 0 WHERE comment_id = $id LIMIT 1";
$result = mysqli_query($db, $query);
return $result;
}
}
function is_liked($id){
global $db;
$check_query = "SELECT liked FROM comments WHERE comment_id = $id LIMIT 1";
$check_result = mysqli_query($db, $check_query);
while($stm = mysqli_fetch_array($check_result)){
$l = $stm['liked'];
}
return $l;
}
function liked_comments(){
global $db;
$query = "SELECT comment_id FROM comments WHERE liked = 1";
$result = mysqli_query($db, $query);
return mysqli_num_rows($result);
}
The code ist just a demonstration and not really neccessary to understand the problem. In another project. I change the value of a table row via Ajax and afterwards want to update the result. This only happens in about 70 to 80% of the time. All the other times and old value is returned
When I try to parse a reponseText using JSON.parse I get this error:
Uncaught SyntaxError: Unexpected token < in JSON at position 0 at
JSON.parse () at XMLHttpRequest.xhr.onreadystatechange
(index.js:75)
Any time i run the code below.
javascript/ajax code
function calculateMeasurements() {
clearResult();
clearErrors();
var form = document.getElementById("measurement-form");
var action = form.getAttribute("action");
// gather form data
var form_data = new FormData(form);
for ([key, value] of form_data.entries()) {
console.log(key + ': ' + value);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', action, true);
// do not set content-type with FormData
//xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var result = xhr.responseText;
var json = JSON.parse(result);
if (json.hasOwnProperty('errors') && json.errors.length > 0) {
displayErrors(form, json.errors);
} else {
postResult(json.volume);
}
}
};
xhr.send(form_data);
}
var button = document.getElementById("ajax-submit");
button.addEventListener("click", calculateMeasurements);
})();
process.php
<?php
function is_ajax_request(){
return $_SERVER["HTTP_X_REQUESTED_WITH"] && $_SERVER["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest";
}
$length = isset($_POST['length']) ? (int) $_POST['length'] : '';
$width = isset($_POST['width']) ? (int) $_POST['width'] : '';
$height = isset($_POST['height']) ? (int) $_POST['height'] : '';
$errors = [];
if(empty($length)){$errors[] = "length";}
if(empty($width)){$errors[] = "width";}
if(empty($height)){$errors[] = "height";}
if(!empty($errors)){
$result_array = array('errors' => $errors);
echo json.encode($result_array);
exit;
}
$volume = $length * $width * $height;
if(is_ajax_request()) {
echo json.encode(array('volume' => $volume));
} else {
exit;
}
?>
I noticed this error anytime I use the JSON.parse on result variable gotten from the ajax response.
i dont think their is anything wrong with your javascript code. please try using the php function properly. it should like this
echo json_encode(array('volume' => $volume));
echo json_encode($result_array);
AND NOT :
echo json.encode(array('volume' => $volume)); // json.encode as you have used in your code is wrong.
echo json.encode($result_array) // json.encode as you have used in your code is wrong.
it should work properly once this change is made
I got the action "pega" in controller Posts:
public function pega($id = null)
{
$posts = $this->Post->findById($id);
foreach($posts as $pok)
{
$foda = $pok['love'];
}
$this->set('foda', $foda);
$this->set('_serialize', array('foda'));
}
In my layout I try to do a requestto catch the data from function "pega" and put inside tag html:
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://localhost:81/booklandia/posts/pega/<?php echo $post['Post']['id'];? >.json";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var out = JSON.parse(xmlhttp.responseText);
function loap (){
var arr = out[0];
document.getElementById("id01").innerHTML = arr;
}
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
this is my ajax code
function sendAjax(send_data,id)
{
var ajaxobj;
alert("After this alert problem occurs!");
if (window.XMLHttpRequest) ajaxobj = new XMLHttpRequest();
else ajaxobj = new ActiveXObject("Microsoft.XMLHTTP");
ajaxobj.onreadystatechange=function()
{
if(ajaxobj.readyState==4)
{
if(ajaxobj.responseText.match("confirmPage") != null) document.getElementById(id).innerHTML = ajaxobj.responseText;
else
{
if(id == "FreshContent")
document.getElementById(id).innerHTML = "<a id=\"refreshpage\" onClick=\"siteSelection('select')\">Failed.Click here to Reload!</a>";
else
document.getElementById(id).innerHTML = "<a id=\"refreshpage\" onClick=\"sendAjax(0,'latest_gossip_marquee');\">Failed.Click here to Reload!</a>";
}
}
else document.getElementById(id).innerHTML="Loading....";
}
if(id == "FreshContent") ajaxobj.open("GET","sitexyz.php?"+send_data,true);
else ajaxobj.open("GET","html/xyz.html",true);
ajaxobj.send();
}
Here the FreshContent is a div tag id.it works in opera & firefox but it crashes in my IE7.
to see if the page returned by the server is valid the code checks if the returned page has confirmPage string in it.
Try this function out - it's a little more robust than what you're using.
function getHTTPObject() {
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
xhr = false;
}
}
}
return xhr;
}
I am using window.onbeforeunload in my javascript.
This works perfectly in IE but is not triggered in Firefox.
I checked on different links in stackoverflow.... In it I read that window.onbeforeunload is not supported by firefox. Is this true?
If yes, can you please tell me a different way to call app.deleteAccount(key) on close of browser. Here is my javascript. Please look at the deleteFile() and dontDeleteFile() methods.
<script type="text/javascript">
//Event handler for body onload
function confirmDeleteFile(){
var secured =document.r_form.Secure[1].checked;
alert("confirmDeleteFile : "+secured);
if(secured){
var agree=confirm("Are you sure you wish to continue?");
if (agree){
//document.form1.submit();
return true;
}
else
return false ;
}
// submitForm();
return true;
}
function deleteFile() {
alert('inside deleteFile() but outside window.onbeforeunload');
window.onbeforeunload = function(){
var key = DOMAIN+'::' + elem('userName').value;
alert('inside deleteFile()');
app.deleteAccount(key)
alert('Unloading!');
}
}
function dontDeleteFile() {
alert('inside dontDeleteFile() but outside window.onbeforeunload');
window.onbeforeunload = function(){
alert("Not deleting");
}
}
function validateFormOnSubmit(theForm) {
var reason = "";
var userName = theForm.username.value;
var pin = theForm.pin1.value;
var PAM = theForm.pam.value;
var organization = theForm.organization.value;
//reason += validateUsername(theForm.username);
reason += validateEmpty(theForm.pam);
reason += validatePinMatch(theForm.pin1,theForm.pin2);
reason += validatePin(theForm.pin1,theForm.pin2);
if (reason != "") {
if(!confirmDeleteFile()){
return false;
}
alert("Some fields need correction:\n" + reason);
return false;
}
else{
if(!confirmDeleteFile()){
return false;
}
<% String url = request.getServerName().toString();
int port = request.getServerPort();
String contextPath = request.getContextPath();
%>
var servlet = "arcotebank.az"; //AroctEBanking Servlet
var url = BASE_URL + '/' + servlet;
var query = 'lang=en&reqid=1&version=1.1';
query += '&device=' + urlEncode(navigator.userAgent);
query += '&uid=' + urlEncode(userName);
query += '&code=' + urlEncode(PAM);
query += '&pin=' + urlEncode(pin);
query += '&usePin=' + usePin+'&method=arcotOTPEnroll&organization='+organization;
//alert("url=>"+url + '?' + query);
var xml = app.openUrl(url + '?' + query) + '';
//alert("xml=>"+xml);
if(appError()){
alert("applet error");
}
var domain = getDomain(url);
app.provisionAccount(domain, xml);
if(appError()){
alert("applet error");
}
var acc = app.getAccount(DOMAIN + '::' + userName);
if(acc!=null){
<%String formSubmitAction1 =
URLEncoderDecoder.encodeURL(
formAction,
"Action.2FA.Arcot.Navigation.LogoutActionCalled=Y",cm);%>
theForm.action ='<%=formSubmitAction1%>';
var secured =document.r_form.Secure[1].checked;
alert("line 131 "+secured);
if(secured){
deleteFile();
}else{
dontDeleteFile();
}
theForm.submit();
}else{
document.getElementById("error").innerHTML = "Failed to Create ArcotOTP";
}
}
}
function resetForm(){
var form = document.forms[0];
form.username.value = '';
form.pam.value = '';
form.pin1.value = '';
form.pin2.value = '';
}
function validateUsername(fld) {
var error = "";
var illegalChars = /\W/; // allow letters, numbers, and underscores
if (fld.value == "") {
fld.style.background = 'Yellow';
error = "You didn't enter a username.\n";
} else if ((fld.value.length < 5) || (fld.value.length > 15)) {
fld.style.background = 'Yellow';
error = "The username should contain more than 4 characters.\n";
} else if (illegalChars.test(fld.value)) {
fld.style.background = 'Yellow';
error = "The username contains illegal characters.\n";
} else {
fld.style.background = 'White';
}
return error;
}
function validateEmpty(fld) {
var error = "";
if (fld.value.length == 0) {
fld.style.background = 'Yellow';
error = "You didn't enter Personal Assurance Message \n"
} else {
fld.style.background = 'White';
}
return error;
}
function validatePin(pin1,pin2){
var error="";
if(pin1.value!=pin2.value){
pin1.style.background = 'Yellow';
pin2.style.background = 'Yellow';
error += "Pin numbers dont match\n";
//alert("Pin numbers dont match");
}
return error;
}
function validatePinMatch(pin1,pin2){
var error="";
if(pin1.value==""){
//elem('otp').style.background = 'Yellow';
pin1.style.background = 'Yellow';
error += "Pin number cannot be empty\n";
//alert("Pin number cannot be empty");
}
if(pin2.value==""){
//elem('otp').style.background = 'Yellow';
pin2.style.background = 'Yellow';
error += "Confirm Pin number cannot be empty\n";
//alert("Pin number cannot be empty");
}
return error;
}
</script>
Note that in Firefox 4 and later the returned string is not displayed to the user. See Bug 588292.
https://developer.mozilla.org/en/DOM/window.onbeforeunload
Maybe this is what's causing your problem in part. Also the example on the page might be better suited for cross-browser compatibility?
window.onbeforeunload = function (e) {
var e = e || window.event;
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = 'Any string';
}
// For Safari
return 'Any string';
};
window.onbeforeunload is supported by Firefox and all major browsers. It should be implemented as a function that returns a string, which will be used as the message in the confirmation dialog.