Ajax success code not loading in synchronous manner - javascript

We are expecting the below things:
Would like to show the page with updated values.
Then show the session attribute.
What is happening for the below code, session message displayed first and then the page is getting reload.
$.ajax({
type: "POST",
url: "startSelectedServer",
data: { selectedJvmHostIp : selectedJvmHostIp, selectedJvmPort : selectedJvmPort },
success: function(result){
1. location.reload();
2. $("#save-message-div").show();
},
error : function(e) {
}
});
<div id="save-message-div" style="background-color: #DFF2BF; padding: 8px;display:none">
<h2 id="save-message" style="color: #4F8A10"></h2>
</div>
But we are expecting to show message after reloading the page.
In above 2 is executing first then 1 is executing.

ok it appears to me that you are trying to perform a server-side functionality and then refresh the page and have a message appear that the functionality has occurred.
This is fine as far as it goes but will not work the way you have it. To do it closest to the way you invision you will want to put in conditional logic on page load to determine if it is appropriate to show the div.
Even if your page did not show the div prior to reloading, the way it is written, when the page reloads it will not still be executing the same piece of script - it is a blank slate with only what you pass to it.
I am not sure why you want to reload the page at all actually; you can, and should [to make use of ajax], just use the information client-side that is returned from the server asynchronously.

Related

Using Ajax to call the same page makes the body content show twice

I'm making an Ajax call to the same PHP page from a link on the page.
For the final code I'll be passing some parameters but for the sake of keeping it simple, I'm not doing that in the code below. Reason I'm using Ajax is to place a "Please Wait" message as it seemed the most effective way to do it (usually you do a call from one page to another, which works perfectly fine).
I do get to see the "Please wait" message accordingly after clicking on the link but it keeps the content of THE <BODY> section below the new content being displayed by the Ajax call. So int he example, below, I basically end up with 2 links that say "Click here". How do I make it load just the new content (which in this case is identical)?
This must be simple but I'm not sure what I'm missing here.
PWAIT.PHP
<body>
<?php sleep(3); //To allow for the message to show as I have nothing processing here ?>
Click here
<script>
function loadingAjax(div_id)
{
$("#"+div_id).html('<center><img src="http://img/ajax-loader.gif"><b>Please Wait ...
</b></font></center>');
$.ajax({
type: "POST",
url: "pwait.php",
success: function(msg){
$("#"+div_id).html(msg);
}
});
}
</script>
<div id="myDiv"></div>
</body>
After our discussions, we've discovered that your code is working exactly as it should. It is doing exactly what you ask it to do.
Load the page from the server
Click button
Loads the same page via AJAX
Duplicates the page contents into a div on the page
Display duplicate contents
That's what you've asked, that's what you've received.

When I disable submit button (after form submit) the page does not load

I have an HTML form which submits to another page via POST. Nothing special about it, except that after the form validates I try to hide and/or disable the submit button so that it cannot be double-submit, while also telling the user the next page might take a while to load.
The relevant code is:
jQuery(document).ready(function () {
jQuery("form#form").submit(function() {
var result = validate();
jQuery(this).find('input[type=submit]').prop('disabled', true);
jQuery("#submit-button-wrapper").html(jQuery("#submit-button-wrapper").html()+
"<br/><br/><span style='margin: 25px; padding: 5px; background: yellow; "+
"width: 100%; font-weight: bold;'>Loading... this may take a few minutes! "+
"<i class='fa fa-spinner fa-spin' style='color: blue;'></i></span>");
return result;
});
});
function validate() {
return true; // Does stuff, then returns a simple true or false
}
By request, here is the (very simple) button wrapper HTML:
<div class="col-sm-12" id="submit-button-wrapper">
<input type="submit" value="One More Step" />
</div>
When the I remove the which changes the button wrapper's HTML, the form submits just as you'd expect. When I have that line in, however, it still calls the next page and executes that code, without the displayed page ever changing.
I have tested in both Chrome and Firefox, so I know it's not a browser issue, but this is really weird behavior. What am I doing wrong?
My goal: (1) validate the user's input, (2) give the user a clue that the page is going to take a while to load and (3) display the output from the action="complete.php" page once the PHP on it has run.
Maybe you can achieve this with $ajax and show results on the same page.
Send POST data to /some.php
After sending data, give feedback to user changing button behavior
When the task is complete, receive data and verify success or error and act accordingly. If OK, change button text to "complete!" or something else, and append response data to some div. If NOT OK, give feedback as well.
In code:
$("form#form").submit(function(e) {
e.preventDefault();
$.ajax({
method: "POST",
url: "some.php",
data: $(this).serialize(),
dataType : 'json',
timeout: 2000,
cache: false,
afterSend: function() {
/*change button behavior here*/
},
success: function(result) {
if (result === "ok"){
/*maybe append data to div and update button text to complete*/
} else {
/*if result not ok, send feedback*/
}
}
});
});
BTW: ajax documentation http://api.jquery.com/jquery.ajax/
When you return true (if validated) then the form is submitted. However, you're changing the DOM / submit button wrapper and essentially removing the submit button, right? Likely that is what is causing your problem. Leave the submit button wrapper alone. If you want to display a message display it as an overlay or hide the submit button wrapper and show the message wrapper in its place, don't remove the submit button altogether.
I know that you're just showing a slight jQuery and HTML portion of the script, but that isn't quite enough to figure out your problem. Since not all of it seems to be there because you mention action="complete.php" but I don't see that within your jQuery or HTML sample of code. So I have a few questions of my own.
Is the form small or large. If it's a small form then why aren't you displaying the output on the submit page? You could do that with what you currently have but a single PHP or ASP page could save you on amount of pages to make and what not. As a side note, depending on size of the form, you can do the validation on same page or continue to use action="" for it if large.
Do you have need for a database file or are you saving to one? If you do/are, you could write to the DB file, have the submit open the next page and view what was saved in the database on that new page. Again, you can probably use a single PHP or ASP page.
This last part sounds more valid for your purpose. You could use location.href="http://www.domain.com/home.html";
or use window.location("http://www.domain.com/home.html"); to redirect to the new page.
On another matter about some of the comments others made.
You don't exactly need the + unless you're dividing each of those out into their own separate lines when you could just use one line to do that. That's probably what confused Rajesh about the '. In fact I'm not sure why you yourself mentioned the + when referring to Rajesh comment about "concat string" and "append" ,because those two have nothing to do with the +. In fact to take a guess, he might have been referring to your jQuery("#submit-button-wrapper").html(jQuery("#submit-button-wrapper").html() which kinda looks like a concat string.
Speaking about append, not really needed unless for example you're doing something like giving the user the option to add rows to a form question.

AJAX response caching / onclick-event inside of a function

I´m using AJAX to execute some server-side actions and refresh a table inside the page without reloading the page itself. All works fine at first view. But I wrote a function in PHP to send an email and execute it via AJAX. When I´m starting this action for a second time old responses gets triggered.
What exactly happens:
I´m clicking a Button to execute the "Sendmail-Action"
a Modal asks me if I want to execute the action and I´m clicking yes
a PHP-Script gets executed and sends the email
the Modal gets closed after the PHP-Script finishes (~2s)
the table (with emails and so on) gets refreshed and the status updated
What happens next:
I´m clicking a Button to execute the "Sendmail-Action" for the same
or another entry in my table
a Modal asks me if I want to execute the action and I´m clicking yes
the Event triggers twice / 4xAjax-Request instead of 2 (I can see it in my Chrome-Console)
the Modal closes and 2 Mails sended
What I´ve tried to get rid of this behaviour:
checked my JS with JSHint
checked my PHP-Code (no errors in apache error.log)
redesigned the PHP-Script (Sendmail), now the AJAX executes a function
tried different browsers
deactivated AJAX-Caching
completely deactivated Caching with Apache (correct Headers)
deactivated Session-Caching in my php.ini (I don´t use sessions)
unset all variables in PHP
cleared the cache for all of my browsers
checked all headers
searched several hours for solutions
More information about my setup:
jQuery 2.1.4
php 5.4
Apache 2.2
I can´t find a solution to my problem and maybe this is caused because I´m adding the content dynamically to the table. I had the same problem in the past and I´m thinking the Modal (which is also dynamic) triggers the click on the "Yes-Button" twice.
You can put your ajax click handler outside of that function:
$(document).on('click', '.email-resend, .email-send, .show-doc, .show-acc, .more-acc, .no, .yes, .termin', function(){
$.fn.doAction(classname, comEntry);
});
As you mentioned that you have placed this in the function. Instead you should put this outside of it:
$(document).on('click', '.bt-ok', function(){
$.ajax({
....
});
});
Edit by #pandora: Or just use a second function (in my case) like this:
$(document).on('click', '.bt-ok', function(){
$.fn.sendRequest($('#modal').attr('data-1'), $('#modal').attr('data-2'));
});
Then I can call the function like this and execute the AJAX:
$.fn.sendRequest = function(data1, data2) {
$.ajax({
url: 'target.php',
cache: false,
data: { gimme1 : data1, gimme2 : data2 },
success: function(response) {
// Show Error
if(response.length > 0){
alert(response);
}
// Reload Content
$.fn.Reload('','');
// Close Modal
$('#modal').css({'display' : 'none'});
}
});
};

call spring action from jquery without ajax for multiple buttons like view edit etc

I am working on Spring MVC. I have a page having list of items in table. I need jquery to pick up the radio selected and then user can click on view or edit or delete. According to the button clicked, ajax block invokes proper action with the form object serialized and the id goes to the action for processing.
Everything went fine till here.
Then, when the action returns back to ajax success: block
$.ajax({
type : "post",
data : str,
url : newUrl ,
async : false,
success : function(data) { <----- here
I need to redirect to page action has in its view object. Instead, as we know, its ajax, so I need to show the result in some div on that page itself. But I need to go to the page directed by spring action. Please help me do this.
In short, I don't want to show the details on a pop up but another page.
Thanks.
get url of page directed by page action and use following statement to redirect page
window.location = pathReturned;
above statement will simply redirect users' browser window. So if you may require to persist state of the page.

Check for page refresh or close with jQuery/javascript

I am looking to check if a page has been refreshed or closed with jQuery or javascript.
What I have currently is I have some database values that I want to delete if the user either navigates away or refreshes the page.
I am using AJAX calls to delete the values.
Right now, I have the following code:
The handler:
window.beforeunload = cleanUp;
The cleanUp() method:
function cleanUp() {
// Check to see if it's an actual page change.
if(myActualLeave) {
$.ajax({
type: "POST",
url: "/api/cleanup",
data: { id: myLocalId },
success: function (data) {
console.log(myLocalId + " got removed from the database.");
}
});
}
// Reset the flag, so it can be checked again.
myActualLeave = true;
}
Where myActualLeave is a flag that I set to false when AJAX calls are made, so they don't trigger the beforeunload handler.
The problem I am running into is that when I click a link on my page, so for instance a link to Google, the window.beforeunload doesn't trigger. I may have a misunderstanding of this, but I have tried using jQuery's $(window).unload(...); and the onbeforeunload trigger as well.
What should I use to call javascript when:
the user refreshes the page,
when the user navigates away from the page, or
when the user closes the page?
Edit: It came up in a comment that I could use a click() jQuery handler to detect navigating away. I should have made it more specific that I don't mean when the user clicks a link only then I want it to proc. I want it to trigger when they change pages in any way. So if the address bar gets typed in, for instance.
You should try "onbeforeunload" :
window.onbeforeunload
But i think you can't put "active" (ajax call) code in this callback function. All you can do is defining a confirm modal window that will be displayed to the user before leaving like :
Are you sure you want to leave because...
So you should do as #Leeish said : put a code in the .on('click') of the link so it can launch the ajax call before sending to another page.
But for the "refresh" or "close" scenario, you can consider marking your database row as "draft" (or whatever) and if not saved when on the next page, delete the draft line.

Categories

Resources