This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have the code below and my div with loader gif doesn't appears. I tried many ways to do that and I could. Why $('.loader').show(); doesn't works?
$('.loader').show();
var url = "myURL.ashx?p1=" + p1;
if (GetRequestReturnStatus(url)) {
window.open(url);
}
$('.loader').hide();
function GetRequestReturnStatus(url) {
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
if (http.status == 404 || http.status == 403 || http.status == 500) {
ShowMessage("nFailure", "some message");
return false;
}
return true;
}
And the HTML:
<div class="loader" style="display: none;">
<asp:Image ID="Loader" CssClass="p12" ImageUrl="~/_img/loader.gif" runat="server" ViewStateMode="Enabled" />
</div>
It's working in another functions in the code. Just in that case doesn't works.
I'm not using ajax because I don't know how to download de response and when I was looking for that topic, I read is better use window.open than ajax to download file.
It is working, however you are immediately hiding it again with $('.loader').hide();
$('.loader').show();
var url = "myURL.ashx?p1=" + p1;
if (GetRequestReturnStatus(url)) {
window.open(url);
}
//$('.loader').hide(); //this line was hiding your .loader element(s)
function GetRequestReturnStatus(url) {
var http = new XMLHttpRequest();
http.onreadystatechange = function() {
//todo logic here once the request has changed state
if(http.readyState == 4) { //done loading
hideLoader();
}
};
http.open('HEAD', url, false);
http.send();
if (http.status == 404 || http.status == 403 || http.status == 500) {
ShowMessage("nFailure", "some message");
return false;
}
return true;
}
function hideLoader() {
$('.loader').hide();
}
You can see it in this JS fiddle: https://jsfiddle.net/jr5uye4o/2/
There is more reading on how to use XMLHttpRequest here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
Since you are already using jQuery, why not use $.ajax for the request?
$.ajax({
method: "GET",
url: "/yourRequestUrl",
data: { p1: yourParam, p2: otherParam }
}).done(function(msg) {
$('.loader').hide(); // Processed once the request is complete.
})
.fail(function() {
alert("Something went wrong with the request");
});
Related
I have been using Ajax with jQuery to save pictures from canvas as follow:
HTML
<script src="https://code.jquery.com/jquery-3.4.0.min.js"></script>
<script src="javascript/take_pic.js"></script>
take_pic.js
$.ajax({
method: "POST",
url: "pictureController.php",
data: { canvasData }
}).done(function(data){
console.log("Success");
}).fail(function(html){
console.log("Fail");
});
pictureController.php
if(isset($_POST['canvasData']))
{
$data = $_POST['canvasData'];
saveData($data);
}
function saveData($data)
{
//...
}
This was working perfectly yesterday but stopped working today.. It seems that pictureController.php is not called anymore! What is strange is that console.log logs success..
I would like to stop using jQuery and use Ajax only, how can I update my JavaScript to do so?
Thank you!
Hey you can do this with :
const req = new XMLHttpRequest();
req.onreadystatechange = function(event) {
// XMLHttpRequest.DONE === 4
if (this.readyState === XMLHttpRequest.DONE) {
if (this.status === 200) {
console.log("Réponse reçue: %s", this.responseText);//ur response is here
} else {
console.log("Status de la réponse: %d (%s)", this.status, this.statusText);
}
}
};
req.open('POST', 'http://www.exemple.com/pictureController.php', true);//url to get and method here
req.send({ canvasData });//data to send here
and for more documentation read this
This question already has answers here:
using javascript to detect whether the url exists before display in iframe
(8 answers)
Closed 5 years ago.
How can I check if there is an .html file in a folder exists? I'm trying to not get the error "It may have been moved or deleted." and instead display notFound.html
<body>
<header>
<form autocomplete="off">
<input id="3Digits" type="number" min="100" placeholder="3-Digit Code">
<span style="display:inline-block; width: 15px;"></span>
Go
<hr>
</form>
</header>
<div id="frameDiv">
<iframe id="srcCC"></iframe>
</div>
<script>
var newLink
function check() {
newLink = document.getElementById("3Digits").value + ".html";
if(newLink == ".html") {
alert("You forgot to put the 3-Digit Code");
}
else {
LinkCheck(newLink);
}
}
function LinkCheck(url) {
if(HTML EXISTS) {
document.getElementById("frameSRC").src = newLink;
}
else {
document.getElementById("frameSRC").src = "notFound.html";
}
}
</script>
</body>
The function LinkCheck is what I'm asking for, all the files are going to be in the same directory.
This is a small school project, so any help would be appreciated!
You can use XMLHttpRequest to check if the file exists
function LinkCheck(url)
{
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status!=404;
}
Replace your function with this:
function LinkCheck(url) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onload = function(e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
document.getElementById("frameSRC").src = newLink;
} else {
document.getElementById("frameSRC").src = "notFound.html";
}
}
};
xhr.send(null);
}
Option 2: use jQuery ajax
function LinkCheck(url) {
$.ajax({
url: url,
success: function(data) {
document.getElementById("frameSRC").src = newLink;
},
error: function(data) {
document.getElementById("frameSRC").src = "notFound.html";
},
})
}
Try replacing your function LinkCheck with this:
function LinkCheck(url) {
const http = new XMLHttpRequest();
http.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) { // if (HTML EXISTS)
document.getElementById("frameSRC").src = newLink;
} else {
document.getElementById("frameSRC").src = "notFound.html";
}
}
http.open('get', url, true);
http.send();
}
If that says some deprecation issue try the new javascript native fetch API:
function LinkCheck(url) {
fetch(url).then(function(response) {
if (response.status === 200) {
document.getElementById("frameSRC").src = newLink;
} else {
// this else isn't needed but you can put it here or in the catch block
document.getElementById("frameSRC").src = "notFound.html";
}
})
.catch(function (err) {
throw err;
});
}
I am new to AJAX and presently learning it from Head First AJAX. The problem I am facing is really weird. I developed a simple program that creates a request through JavaScript and then shows the output.
main.js
window.onload = initPage;
function initPage() {
request = createRequest();
if(request == null) {
alert("request could not be created");
}
else {
var url = "requestMe.php";
request.onreadystatechange = showResult;
request.open("GET", url, true);
request.send(null);
}
}
function showResult() {
if(request.readyState == 4) {
if(request.status == 200) {
if(request.responseText == "okay") {
alert("A successful request was returned");
}
else {
alert("ALERT : " + request.responseText);
}
}
else {
alert("Request status received was not correct");
}
}
}
//--function to create request objects--
function createRequest(){
try{
request = new XMLHttpRequest();
}
catch(tryMS){
try{
request = new ActiveXObject("Msxm12.XMLHTTP");
}
catch(otherMS){
try{
request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(failed){
request = null;
}
}
}
return request;
}
Now, here is the php script.
requestMe.php
<?php
echo 'okay';
?>
This code should give the alert A successful request was returned
But instead it gives the result ALERT : okay
The weird thing is this same code was working yesterday for me when I tried it and now it is giving me this result. I tried to create similar programs and they all are showing me this kind of weird behavior. The responseText received is correct because it appends okay after ALERT :. What wrong am I doing here in the code? Why is it going to the else part when the responseText received is correct?
Any Help? Thanks in advance.
I personally would do it using jQuery's Ajax Function in the following way:
document.addEventListener("DOMContentLoaded", function()
{
$.ajax({
"url": "requestMe.php"
}).done(function(data)
{
if(data == "okay")
{
alert("A successful request was returned");
} else
{
alert("ALERT : " + data);
}
}).fail(function()
{
alert("Connection Failed");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I haven't tested this Script, but it should in theory work out well.
Do one thing add exit; after echo 'okay';
Issue in your code is after ?> there is extra space available you can fix it either by removing ?> or removing extra space after ?>.
I hope it will fix your issue.
I have the following block of code:
console.log(1);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://anothersite.com/deal-with-data.php');
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
console.log(2);
xhr.onreadystatechange = function () {
console.log(3);
if (this.status == 200 && this.readyState == 4) {
console.log(4);
xhr.send("formType="+thisFormType+
"&mediaCode="+3478+
"&car="+carID+
"&title="+$('#title').val()+
"&firstname="+$('#firstname').val()+
"&surname="+$('#lastname').val()+
"&tel="+$('#telephone').val()+
"&email="+$('#emailaddress').val()+
"&postcode="+$('#postcode').val()+
"&add1="+$('#add1').val()+
"&add2="+$('#add2').val()+
"&add3="+$('#add3').val()+
"&town="+""+
"&county="+""+
"&optin-post="+$('#optin-post').attr('checked')+
"&optin-tel="+$('#optin-tel').attr('checked')+
"&optin-email="+$('#optin-email').attr('checked')+
"&optin-sms="+$('#optin-sms').attr('checked')+
"&tarID="+targetID+
"&campID="+campaignID+
"&subID="+subjectID
);
console.log(5);
}
}
console.log(6);
So, everything fires except for the xhr.onreadystatechange - I never get the console.log(4) - I have enabled Access-Control-Allow-Origin in PHP and the htaccess as well as trying a veritable plethora of Javascript post functions.
The problem is, as a requirement, I need to post data from a form on a server that has no support for Server side languages - to another domain to handle the data.
Any ideas? It's driving me insane!
edit: I've also tried it with $.ajax
$.ajax({
url: 'http://anothersite.com/deal-with-data.php',
type: "post",
crossDomain: true,
data: {
"formType":thisFormType,
"mediaCode":3478,
"car":$('#car').val(),
"title":$('#title').val(),
"firstname":$('#firstname').val(),
"surname":$('#surname').val(),
"tel":$('#telephone').val(),
"email":$('#email').val(),
"postcode":$('#postcode').val(),
"add1":$('#add1').val(),
"add2":$('#add2').val(),
"add3":$('#add3').val(),
"town":"",
"county":"",
"optin-post":$('#opt-post').attr('checked'),
"optin-tel":$('#opt-tel').attr('checked'),
"optin-email":$('#opt-email').attr('checked'),
"optin-sms":$('#opt-sms').attr('checked'),
"tarID":targetID,
"campID":campaignID,
"subID":subjectID
},
beforeSend: function() {
$('#submit').val('Sending...').attr('disabled','disabled');
},
success: function(data) {
console.log("success call");
console.log(data);
},
error: function(err) {
console.log("error call");
console.log(err);
}
});
And now I've tried to enable it in httpd.conf as well: https://serverfault.com/a/378776/36601
You should not pass xhr.send inside xhr.onreadystatechange. Do something like the following:
var xhr = new XMLHttpRequest();
xhr.open('POST', 'myurl', true);
xhr.onload = function () {
if (xhr.status === 200 && xhr.readyState === 4) {
// do some cool stuff
console.log('You got a successfull request');
}
};
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xhr.send(); // pass your params here
You may need to set Access-Control-Allow-Methods: POST header also. Read more on https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Im trying to pass parameters to servlet from javascript with :
function selectHandler() {
var selection = table.getChart().getSelection()[0];
var topping = data.getValue(selection.row, 0);
var answer=confirm("Delete "+topping+"?");
if(answer){
document.location.href="/item?_method=delete&id="+topping;
alert(topping+" has been deleted");
location.reload();
}
else return false;
}
The values are getting passed to the servlet and is working fine when I'm using firefox as in I'm getting the url as: http://XXXXXXX/item?_method=delete&id=xxxx
But when I'm using chrome the URL that is send is http://XXXXXXX/item. as the values are not getting passed!! I have tried with window.location.href also with no change. what could be the issue?
What you need is ajax call or say XMLHttpRequest as below:
<script type="text/javascript">
function doAjax () {
var request,
selection = table.getChart().getSelection()[0],
topping = data.getValue(selection.row, 0),
answer=confirm("Delete "+topping+"?");
if (answer && (request = getXmlHttpRequest())) {
// post request, add getTime to prevent cache
request.open('POST', "item?_method=delete&id="+topping+'&time='+new Date().getTime());
request.send(null);
request.onreadystatechange = function() {
if(request.readyState === 4) {
// success
if(request.status === 200) {
// do what you want with the content responded by servlet
var content = request.responseText;
} else if(request.status === 400 || request.status === 500) {
// error handling as needed
document.location.href = 'index.jsp';
}
}
};
}
}
// get XMLHttpRequest object
function getXmlHttpRequest () {
if (window.XMLHttpRequest
&& (window.location.protocol !== 'file:'
|| !window.ActiveXObject))
return new XMLHttpRequest();
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) {
throw new Error('XMLHttpRequest not supported');
}
}
</script>
You can also do it easily by jquery,
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" />
<script type="text/javascript">
function doAjax () {
...
$.ajax({
url: "item?_method=delete&id="+topping+'&time='+new Date().getTime()),
type: "post",
// callback handler that will be called on success
success: function(response, textStatus, jqXHR){
// log a message to the console
console.log("It worked!");
// do what you want with the content responded by servlet
}
});
}
</script>
Ref: jQuery.ajax()