0

I have a button in my html form.When i enter values in the textfield, a background operation is performed and data is sent to the server.But since this button already has an event (submit), how do i open a new page once that background operation is completed?

This is the button.

<a href="#" id="submit" data-role="button" data-inline="true"> Submit</a>

and in my javascript i have this function

$(document).ready( function() {

$("#submit").bind('click', function(event){
    doSomeBackgroundStuff();

});

This is happening from Page A, i want Page B to open when doSomeBackgroundStuff() finishes.

Ojonugwa Jude Ochalifu
  • 26,627
  • 26
  • 120
  • 132

2 Answers2

0

since this button already has an event (submit)

Use preventDefault or return false:

$(document).ready( function() {

$("#submit").bind('click', function(event){
     event.preventDefault(); //or just use : return false; at last  
     doSomeBackgroundStuff();

});
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
0

You have a few options.

First, working with what you have already, You could use a callback function for your bind event, and add window.open to load the new page, and simply pass in a url, or hardcode it.

Your jquery would look something like:

$(document).ready( function() {

$("#submit").bind('click', function(event){
    //fire AJAX request
    doSomeBackgroundStuff();

},function(){//call back function
window.open('http://www.yourURL.com');
});//end bind

});//end doc ready

Here is further reading on window.open - How to open a new HTML page using jQuery?

A second option is to use AJAX. You would setup an AJAX request for the new page, and use $.ajaxSend and $.ajaxComplete to fire functions before and after the request.

Your jquery would look something like:

//on button click
$('#submit').click(function(){
   doSomeBackgroundStuff();
});

//ajax start handler
$(document).ajaxStart(function(){
    //do stuff before AJAX request
});

//ajax complete
$(document).ajaxComplete(function(){
  //do stuff after AJAX request

});

A related question with a similar solution.

Global AJAX handlers

Hope this helps

Community
  • 1
  • 1
lukeocom
  • 3,243
  • 3
  • 18
  • 30
  • I am trying to open a new page in my app.`Page B` isn't a web address, but a page on my app.However, using your suggestion i did something like `window.open("#page_b_id);`. This opens `Page B` in a new window (not desired outcome) and `doSomeBackgroundStuff()` doesn't execute. – Ojonugwa Jude Ochalifu May 12 '14 at 08:51
  • sounds to me like you need an ajax solution then. you could use the ajax complete method to doSomeBackgroundStuff. My answer to the following question may be of help http://stackoverflow.com/questions/23216493/javascript-jquery-page-change-event-on-mobile-browsers/23378657#23378657 – lukeocom May 13 '14 at 00:42