I'm trying to execute a block of code when my XMLHttpRequest reaches state 2. The reason why I want it to be in state 2 is that I don't want the user to wait for a response of the server( I would like to redirect the user at this point).
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 == 2) {
window.location.href = urlFromPreviousAjaxcall;
}
}
xmlhttp.open("POST", "url", true);
xmlhttp.send();
However the block of code inside the if(xmlhttp.readyState == 2) will only be called as soon as the server is done processing the call. This part has to be executed as soon as the call is made( without the waiting from the server).
In the documentation I found that state 2 is reached as soon as the call is send. However that is not the case.
Update:
the call I am trying to make involves calling a Api on the server( this takes time to complete). For the client it doesn't matter what happens to the call.The only thing I want is that the call is executed. So basicly I'm trying to gain speed here.
I know that as soon as I redirect the user, the code will stop running. However the call to the server should have been made(and send away).
What am I missing or doing wrong?
Thanks you all for your help.
I found the solution:
[HttpPost]
public void methode(String parameter,String parameter)
{
Task.Factory.StartNew<string>(() => RunTask(accessToken, parameter, parameter));
}
private string RunTask(String parameter, String parameter)
{
try
{
// Code to execute here
return "Done!";
}
catch (Exception e)
{
return "Error: " + e.Message;
}
}
At the server I started a Task. In this task I execute the long procces. It still takes a brief moment before the server returns the call to the user.
When debuggin ( in visual studio) you can see that the task is running without the presents of the user.
Note : all sessions are gone at the moment I redirected the user to an other page.
Related
I've been looking at how to integrate AJAX calls into a Python Django application and I'm somewhat new to both. I have been following the advice here:
https://www.quora.com/Can-I-execute-a-Python-function-from-JavaScript
Which led to this and this respectively for AJAX and Django advice.Both made pretty good sense to me. The desired end result is that a template in this fourth folder down (dashboard) call a function in a file called logic.py under the api folder above it:
In a JavaScript file hooked up to my django template, I have the following code I stole from the AJAX resource I listed above and made some light edits to:
window.onerror = function() {
debugger;
}
// browser - safety
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else if(window.ActiveXObject) { // ie
try {
request = new ActiveXObject('Msxml2.XMLHTTP');
}
catch(e) {
try {
request = new ActiveXObject('Microsoft.XMLHTTP');
}
catch(e) {}
}
}
function step2() {
console.log('something');
}
function testLogin() {
request.open('POST', '../../../api/logic');
// I've also been trying ^^^ logic.py, if it matters
request.send(null);
console.log('testLogin ran');
step2();
}
request.onreadystatechange = function () {
if(request.readystate === 4) {
if(request.status === 200) {
console.log(request.responseText);
}
}
}
It still is hooked up to a URL POST action in the django views, so when I hit the submit button in question I see the following two requests get generated:
That is the correct filepath for that location:
So I'm wondering if I'm missing something either about the AJAX setup, or the way it needs to interact with Django, or some combination of the two. Other resources I've been consulting in looking into this:
Call Python function from Javascript code
https://codehandbook.org/python-flask-jquery-ajax-post/
https://www.makeuseof.com/tag/python-javascript-communicate-json/
https://bytes.com/topic/javascript/answers/737354-how-call-python-function-javascript
And I originally started way earlier in the day so there were a few more, but needless to say I didn't see my issue immediately from looking at any of them. Any help is much appreciated.
So this wound up being a quirk of the Django url setup, I can't believe I didn't figure it out but I hadn't been in that part of the code base for some time.
In our urls.py script, the place I was pinging (which was in the location of the URL described) had a redirect on it and for that reason, the traffic wasn't going to the place I thought.
Apologies if this question is a bit vague, but I have no idea how to make it more specific. I am a beginner when it comes to javascript. I have a web page which sends a number of ajax calls to the server to call php scripts which runs some sql against a mysql database. Everything was working fine then all of a sudden I started to get an internal server error 500 on one of my ajax calls. The ajax call is placed in a function, it works most of the time. Only when I pass the function one specific sql query does it give the error. I've tested the query in my database manually and it works so its not an issue with the query that I am passing. The strange thing is, since the error has started, every now and then it does work, however most of the time it is not working, the error seems to be somewhat random. I realise that with limited information it may be impossible to give an exact answer, but has anyone experienced anything like this before? OR does anyone have any clues as to how I can get to the bottom of this. I've tried everything. I will paste the function that is causing the error (not sure if that will help at all). The error comes on the "xmlhttp.send();" line.
function phpRequest2(prov, phpsc, funct, bolL) {
<!-- document.getElementById("demo").innerHTML = qry; -->
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");
}
document.getElementById("demo").innerHTML = prov;
xmlhttp.open("GET", phpsc + ".php?qry=" + prov, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var arrLocs = JSON.parse(xmlhttp.responseText);
funct(arrLocs, bolL);
}
}
}
You best bet at finding out the reason when you get the Error 500 is to edit your php.ini file and change the following parameters
display_errors = Off
display_startup_errors = Off
to
display_errors = On
display_startup_errors = On
Hopefully that should give you exact details on what your error is and thereby help you solve it.
In some place there is a policy which needs user to click button Continue to enter for example music streaming website.
Let's assume I want to use this website for a time longer than this policy accepts. After some period of time the music stops playing and after refreshing webpage - policy asks you for clicking Continue again, even if you have not left the page.
I'd like to make a script which would check if a connection still persists, but without website refreshing (because it plays music).
I've already created script which would click Continue, but don't know how to (and if it is possible) check connection, if connection is broken then refresh website and click Continue.
Can it be done with GreaseMonkey?
I enter http://deezer.com/
Script click Continue for me
I listen to music
Script is checking connection
if connection is ok go to 3.
Refresh website
Go to 2.
Click script:
if (document.title == 'Click continue')
{
var a = document.getElementById('continue-text');
a.children[1].click();
}
If no policy then the return of page is:
200 OK 318ms
If policy goes on, then it returns:
200 Forbidden 91ms
You can check the connection like this:
function checkConnection() {
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 == XMLHttpRequest.DONE ) {
if(xmlhttp.status == 200){
// this might need some customisation:
var connected = document.getElementById("id_of_the_continue_button") ? true : false;
if (!connected) {
reconnect();
}
}
else {
reconnect();
}
}
}
// here you'll need a relevant url:
xmlhttp.open("GET", "http://deezer.com/", true);
xmlhttp.send();
}
I am using javascript to make call to server. The javascript code is following,
function cs() {
alert("");
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("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "lp.aspx?pb=true", true);
xmlhttp.send();
}
And my server code is following
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["pb"] != null)
{
Response.Redirect("main.aspx");
}
}
The problem is my Response.Redirect is not working with my ajax call. Why is that?
You can not redirect on ajax call, because, it expects some return value from the invoked page. And if that page itself redirects, it has no way to tell calling function to redirect, as it simply expects some return value in success callback.
So to solve this, you can return a param lets say { redirect: true } if condition satisfied. And on success callback , if redirect is true, then redirect using JS - window.location.href="required".
I believe that redirect doesn't work because the Response for the page with the javascript is closed before the AJAX call is even made.
Instead of using Response.Redirect you could send back a string containing the url and in your script use location.href to redirect.
Simple you can not use response on ur ajax call. use
window.location
So I have some code, which checks for whether a one time use discount code exists, and if so, it applies it and then marks it as used in the database. The problem is, it ends up being useable more than once if you spam click it, and then some time maybe 15-20 seconds later it stops being useable.
The relevant javascript component:
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) {
discountAmount += parseFloat(xmlhttp.responseText);
modifyCartOrder();
}
}
xmlhttp.open("GET","forms/jsPromoCode.php?code="+code+"&type="+order_name,true);
xmlhttp.send();
This is processed over in the php file, and when a match is found we echo that amount and then delete the entry
$mysqli->query("DELETE FROM discounts_available WHERE `index`=$index");
The php file is indeed doing what its supposed to. When you click apply code, it is immediately deleted from the database. The problem is, even with the code no longer in the db, you can still apply the code over and over for some amount of time before the js file finally realises there is no entry in the db. Why is this?
You should first check if it exists in DB then only you should proceed with request, it should be very first statement.
If it does not exists you can send response saying code already applied.
You most likely need to lock the table ASAP so no other instances can modify the table concurrently.
http://dev.mysql.com/doc/refman/5.0/en/lock-tables.html
I did not get your problem, exactly I am assuming lost of things, so..
//this is triggered on some click, right?
//TODO:- check if button is disabled? you can have some js variable or check button attribute disbled
//TODO:-if its not disaled->{so first disable the button when it is clicked } else do nothing
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) {
discountAmount += parseFloat(xmlhttp.responseText);
// if succefull keep button disabled
// else renable it, so that it can be clicked again.
modifyCartOrder();
}
}
xmlhttp.open("GET","forms/jsPromoCode.php?code="+code+"&type="+order_name,true);
xmlhttp.send();
thers's no syntax problem here in your code its logical,
ajax call is asynchronous call, it does not happen in sequence
1) You clicked
2) Request Sent
3) Request Processed
4) JS is informed : your modifyCartOrder function executed
what I am trying to say here is that, there is no 3 immediately after 2, 3 will take time to start, js has no control over it, whenever php is done it will reply there's no guarantee. so you can repeat 1 again and again, and 2 will keep repeating... and so 3 will...
I hope I understood your problem, and you understood what I am trying to say :)
Problem is : You are sending asynchronous ajax calls from following code :
xmlhttp.open("GET","forms/jsPromoCode.php?code="+code+"&type="+order_name,true);
Solution : as defined , for opening an ajax call , method is :
xmlhttp.open(method,url,async)
So, You have to modify above line as:
xmlhttp.open("GET","forms/jsPromoCode.php?code="+code+"&type="+order_name,false);