javascript/Ajax only working when debugging - javascript

I wanted to remove the user session and related data when the user closes the browser. i referred to this (http://weblogs.asp.net/kaushal/archive/2011/02/25/user-is-trying-to-leave-trap-and-set-confirm-alert-on-browser-tab-close-event.aspx) post and i have some coding as below. I wanted to delete the user data from the application state and SQL server database when the user closes the browser. And i am doing this with the help of a handler.
The below code is working fine while debugging, it is calling the handler and executing all the codes which i have written in to it. But when i really use this app this is not working. I don't know where the problem is. And it is eating my time.
(I am using this inside the content of a Master page)
window.onbeforeunload = confirmExit;
function confirmExit() {
var UserID = '<%= Session["UserID"] %>';
$.ajax({
type: "POST",
url: "../../Handlers/HandlerUser.ashx?Action=RemoveUserDataOnBrowserClose&UserID=" + UserID.toString(),
contentType: "application/json; charset=utf-8",
async: false,
success: function (data) {
}
});
}
if any one can suggest another way to achieve the same, it will be a great help.

My guess is it is not working because it is asynchronous call.
the function exits before the call happens.
I suggest you interrupt the closing action, clean the data from your database and than after in your callback you call the closing event programmatically.
I found this post which might help you.

At last i got the answer. My problem was my handlers were not calling and it was because i didn't add Forms Authentication to my app. I added this code after authentication and it worked fine.
FormsAuthentication.RedirectFromLoginPage(UserID, false);
I didn't knew that this was necessary.Thanks every one for helping me..

Related

Why is my async jQuery ajax call blocking?

I have read many similar questions to mine from long ago but have yet to find the answer to my problem, so apologies if it sounds so familiar.
I have a Laravel/PHP web app which loads in an excel file of transactions. These are processed as either success or failure. In development it takes about two seconds per transaction. A typical file has about 40 transactions. I am now wanting to use the Bootstrap progress bar to provide feedback to the user about how far along the processing is going.
I have a page with a button to fire the import, previously file selection and things have happened, so I can just call the backend URL (audit.import) with the correct parameters and the upload will happen and work. So what I have done, is create a URL to return the status of the upload from the server (loadprogress). The plan being that the loadprogress will be called via ajax and the magic of js setTimeout, in order to poll the backend. Once we see all records have been successful or not, then the poll can end.
The problem is, the loadprogress poll fires regularly, right up until I press the button to start the main file load. Then it fails to fire again until the main file load has completed, thus removing the planned use for the progress meter.
My javascript looks like this,
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var fullname = '<?php echo $fullname; ?>';
$("#ajaxButton").click(function(event) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '/audit.import/1/' + fullname,
type: 'POST',
async: true,
}).always(function(xhr, status) {
console.log("Import complete with status of " + status);
});
console.log("sent async call to perform audit");
});
(function loadProgress() {
$.ajax({
type: 'GET',
url: '/loadprogress',
}).done(function(result) {
console.log(result);
}).then(function() {
setTimeout(loadProgress, 100);
})
})();
});
</script>
I am on a mac in safari, but have tried chrome on mac with the same results.
Any assistance would be welcomed.
Thanks.
It was indeed a server side problem. I was running on a single threaded test server which means there was no second thread for my second process. Hence the block. By default the test Laravel server that comes with the install is only single threaded. A fact I had missed in my setup of the test server.

execute a PHP script from Ajax without expecting an answer (and no daemons)

I hope you can help me with this issue:
My sistem runs over Zend Framework, I have installed jQuery in it's latest version. I have an input that receives a file and it makes an Ajax call when changes, and I want that call made in the background, without expecting any response (because that script will send an email when finished). My ajax call is like this:
var formData = new FormData();
formData.append('file', $(this).get(0).files[0]);
$.ajax({
url: 'uploadaddresses.php',
type: 'POST',
data: formData,
dataType: 'json',
async:true,
processData: false,
contentType: false,
beforeSend: function(){
bootbox.alert("You've made your petition correctly. When finished, an email will be sent to you.")
},
error: function(err) {}
});
return false;
Although, the call waits for a response (even FireBug shows me that uploadaddresses.php is still executing...). What i'm doing wrong? How should I do it best? I want to avoid using daemons and system calls, because system restrictions...
Thank you very much in advance :)
If you're wanting uploadaddresses.php to return an HTTP response immediately but continue processing, take a look at pcntl_fork in PHP.
Here's the main doc page: http://php.net/manual/en/function.pcntl-fork.php
Here's a good example that you might want to follow: http://php.net/manual/en/function.pcntl-fork.php#94338
Create a success method for the ajax call and have something like this:
console.log("Done");
This way you know if is complete and successful but only if you are looking at the dev tools. Unless you specify output it should not continue to run after the call has been made. Maybe you have an error in your PHP code?
EDIT: If you can't get this resolved you may want to post your PHP page as well.

running jquery.ajax causes to slow down in navigating to other page

I have jquery.ajax that always requesting data to the server.My problem is that when I
click some navigation menu I can't navigate it is very too slow.I tried to comment the method inside the success,it works fine I can navigate very fast because there is no request running...Any Idea how to make this work to have request running at the same time and I can navigate to other page.?.
More input greatly appreciated.
Thank you in advance.
$(function(){
getUpdates();
});
function getUpdates(){
type: "GET",
dataType:'json',
url: "updates.php",
error: function () {
setTimeout(getUpdates, 5000);
},
success: function(data){
//do something with the data
...
...
...
getUpdates(); //call again the function
}
});
}
It's not a good idea to start a new request as soon as the previous request finishes. There is no (good) solution for your problem - the best idea is to restructure your code. Since you're constantly pooling the server for new information, you might want to look into Comet or Socket.IO to implement some sort of push mechanism from the server.
That said, for a simple speedup, the best thing you can do is add a timeout in the success function, the same way you did with the error function.

Javascript variable to PHP variable?

Jquery function:
$(document).ready(function() {
$(".checkbox").click(function(){
var selVal = $(this).val();
$.ajax({
type: "POST",
url: 'remove_task.php', //This is the current doc
data: ({sel: selVal}),
success: function(data){
//alert(selVal);
console.log(data);
}
});
});
});
My PHP function in remove_task.php:
function remove_selected_task()
{
$task_to_remove = $_POST['sel'];
echo $task_to_remove;
}
if (isset($_POST['remsubmit']))
{
remove_selected_task();
}
Not able to pass this successfully. Can anyone help me out? Thanks in advance.
try to pass the $_POST variable into the function for ex:
remove_selected_task($_POST['sel']);
function remove_selected_task($task_to_remove)
{
echo $task_to_remove;
}
Start by trying to diagnose the issue using the browser dev tools. Press F12 to get the dev tools panel, and go to the Network tab.
Now click your checkbox and watch for what happens...
Does the network panel show the request being made to remove_task.php?
If not, then there's a problem in your javascript where it registers the click event. Maybe the selector is wrong or something like that.
If the network panel does show the request being made, click on it there to get more info about it, and then look at the request data and the response data.
Does the request send the data you're expecting it to, and in the correct format?
If not, then you'll need to debug your Javascript to see why. I can't really help with that unless I actually see the data, but you should be able to get an idea of what the problem is by what's being sent incorrectly. Maybe the checkbox value is wrong?
If it does look right, then move on to the response.
Does the response contain the data you expect?
If it has a 404 response code, then your URL is incorrect. Maybe the path is wrong?
If the response includes an error message, then you should be able to debug the PHP from that. It'll have the relevant line numbers in it, so that should be enough to get you going.
If the response is blank, then your PHP code isn't sending anything back: Maybe a syntax error (with error suppression), or maybe the program ends before it gets to echo the data. Either way, further debugging in the PHP will be required.
That's about as much help as I can give, given the info you supplied in the question. I hope that's enough to get you started.
This will solve your problem, and next time add the full code in your question.
you check if "remsubmit" exists in your php file, but you don't send it ! This should work by modifying the line data: ({sel: selVal}) as below :
$(document).ready(function() {
$(".checkbox").click(function(){
var selVal = $(this).val();
$.ajax({
type: "POST",
url: 'remove_task.php', //This is the current doc
data: {sel: selVal, remsubmit:"1"},
success: function(data){
//alert(selVal);
console.log(data);
}
});
});
});

Jquery .Get() pulls NULL in Internet Explorer

I have a problem with an AJAX call in JQuery. It works on Chrome, FF, and Safari, but not IE. In fact in IE nothing happens at all, no errors, no data loaded.
Here is the code:
$(document).ready(function() {
$.ajaxSetup({ cache: false });
$.get("ShoppingCart2.aspx", { }, function(data) {
//query the jq object for the values
alert(data);
alert($(data).find('#Items').text());
var intI = parseInt(($(data).find('#Items').html()));
With the alert data I find all the data from the page I am making a call from, but unfortunately my data.find methods pull up null for IE. I'm not sure if it's the code or the browser, but I am really stuck. Thank you for the help.
Edit: I did add in the cache: false command, but still I have no luck. I really cannot understand why this won't work in IE.
Try this (once in your page/external js, before your AJAX calls):
$.ajaxSetup({ cache: false });
IE likes to cache the hell out of things, and if you were testing and had no content there at one point, chances are IE is holding onto it. Using $.ajaxSetup() and and telling it by default to not cache AJAX results should resolve this. If you're curious, it's sticking a timestamp on the URL as a cache breaker under the covers, use fiddler to see this happening.
Is it perhaps caching the AJAX? What happens if you put this before your code:
$.ajaxSetup({ cache:false });
A quick solution without coding it could be to press CTR+F5 to clear the cache upon refresh.
Well I was unable to make the .find part of the .get work in internet explorer, but I did find a way to get the ajax information I needed:
var information = $.ajax({ type: "GET", dataType: "html", url: "ShoppingCart2.aspx", data: querystring, async: false }).responseText + " ";
This passes a query string to the website then gets information from the website back into one big string. I then
manipulated that string to get what I needed. Unfortunately it is a lot slower than the .get command, but it is a fix.
Thanks for the help everyone!

Categories