How to open a new page in jQuery Mobile from javascript function - javascript

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.
Submit
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.

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();
});

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

Related

Ajax sends request more than once

I have a huge problem with working with AJAX:
After the AJAX request on my page is send the next request are send multiple times, and buttons think that they are pressed multiple times.
Now I searched around here and the internet, but I can't solve it. So far, following corrections are made in the code:
All code is in an own function called AjaxInit()
AjaxInit() is called upon $(window).load and on $(document).ajaxStop
All Element have their binder to body (e.g. $("body").on("click","#btn-main", function)
Now I have tried unbinding all events using $("body").find("*").off(), but that did not help either.
I know that I do something wrong, I just don't know what.
How can I properly rebind everythink after the Ajax call is done? How can I make shure that object bindings (e.g. $("#news").sortable({})) will work properly after the first ajax call? I would love to use AJAX for all the callbacks on my page, but currently the best solution seems to be just reloading the entire page after every ajax call, which would be rather bad.
Any help is appreciated.
EDIT: Code added
$(window).load(function() {
AjaxInit();
});
$(document).ajaxStop(function() {
AjaxInit();
});
function AjaxInit() {
$("body").on("click", "#btn-admin-main", function(e) {
console.log("Admin clicked");
e.handled = true;
e.preventDefault();
LoadDynamicContent("/Edit/");
});
}
function LoadDynamicContent(path) {
//Nach oben Scrollen
$('html,body').scrollTop(0);
$.ajax({
type: 'GET',
url: path,
success: function(response) {
var html_response = $(response).find('#dynamic_content').html();
$("#dynamic_content").html(html_response);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<a class="sidebutton-full" id="btn-main">Edit</a>
<div id="dynamic_content"></div>
You can unbind the click event from button
$(document).unbind('click').on("click", "#btn-main", function () {
//do stuff here
});
OR
$(document).off("click", "#btn-news").on("click", "#btn-news", function () {
});
If your form submission hitting twice then you need to change your code little bit
$("#form_news_sort").submit(function(e){
e.preventDefault()
// do stuffer here
.
.
.
.
return false;
})
if you are still facing error , please comment below
The problem is that when your ajaxStop handler calls AjaxInit(), it adds another click handler to the body.
In your example code, it looks like you don't need ajaxStop at all. All it will do is add another click handler, which is the problem. Or if your real code does some more complex initialization that needs to run whenever all Ajax requests are complete, you should factor out the click handler assignment from whatever else needs to happen.

Prevent $element.on('click') before ajax is loaded

I am making and ajax call and storing the results in an array. After the first set of data is loaded, I am using next and previous buttons to navigate through the array.
I want to prevent any $(element).on('click') events from happening until I have the first set of data loaded.
Is there any way to do this?
I have already tried to use
$(element).unbind('click');
for when the document loads and then
$(element).bind('click');
when the ajax call is successful, but still clicking on either the next or previous links will still trigger my
$('#next #prev').on('click', function () {
//my code to navigate through the array here.
});
Anyone have any ideas on how I can complete stop this event from firing until the ajax has loaded?
You can disable them by default and in the ajax success callback you can turn them on with something like this:
$(element).prop("disabled", false); // Element will get enabled for clicking
I will update the answer now as it is not working for the concerned person, to disable the button do this:
$(element).attr(“disabled”, true);
In success callback of the ajax call you need to do this:
$(element).removeAttr('disabled');
$.ajax({
....
success:function(){
$('#next #prev').on('click', function(){
// only ajax event complete the #prev can run this function
}).off('click'); // no more clickable now
}
});
or you can just
$('#next #prev').hide();
// done?
$('#next #prev').show();

How can I call an ajax click event from page load?

I have a click event which fires when I click on a button, it opens a modal interface:
$(".profileF2fClinicalServiceDetails").live("click", function(){
var requestUrl = '/php/includes/ajax.php?operation=profile_edit_f2f_clinical_service_details&service=f2f&counsellor_id='+getPractitionerId($(this))+'&counsellor_address_id='+getAddressId($(this))+'&edit_level='+getEditLevel($(this))+'&tab='+getTab($(this));
openDialog(requestUrl, "Edit Face to Face Service Details", 850, "location.replace(getCleanedLocationHref()+'&tab="+getTab($(this))+"');");
return false;
});
But now I want to prompt this to be fired when a page loads, how do I call it directly from the HTML?
Add the code in the click event to an independent function (rather than a closure) called, for example, showPopup. Then change the function bound to the click event to call showPopup, and add a call to showPopup function on page load.
A note, as of 1.7 jQuery's live function is deprecated, you should use on instead (source)
You will have to pass some arguments to the function, since you won't be able to use this during the initial call. You will have to pass those arguments to the main function the first time you call it, I won't presume to guess how you'll determine that.
When the click event is fired, you can extract the arguments from the element in the fashion you're currently using. You'd have something like this:
$(document).ready(function() {
// add the click event
$(".profileF2fClinicalServiceDetails").on("click", function () {
var Me = $(this);
showPopup(
getPractitionerId(Me),
getAddressId(Me),
getEditLevel(Me),
getTab(Me)
);
});
// call the function right away
showPopup(
[initial_counsellor_id],
[initial_address_id],
[initial_level],
[initial_tab]
);
});
function showPopup(counsellor_id, address_id, level, tab) {
var requestUrl = '/php/includes/ajax.php?operation=profile_edit_f2f_clinical_service_details&service=f2f&counsellor_id='+counsellor_id+'&counsellor_address_id='+address_id+'&edit_level='+level+'&tab='+tab;
openDialog(
requestUrl,
"Edit Face to Face Service Details",
850,
"location.replace(getCleanedLocationHref()+'&tab="+tab+"');"
);
return false;
}
Documentation and Related Reading
jQuery.ready - http://api.jquery.com/ready/
jQuery.on - http://api.jquery.com/on/
jQuery.live - http://api.jquery.com/live/ [DEPRECATED]
Javascript functions on MDN - https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Functions

AJAX: Submitting form without page refresh only works once

I am using AJAX to submit a form behind the scenes, without refreshing the page. The problem I am running into is I can only submit the form once. After I submit it once, the on('submit') function no longer works and I am getting no errors. This completely defeats the purpose of using AJAX to submit the form :/
$(document).on('submit', '#myForm', function(e) {
$.post('mail.php', $(this).serialize(), function (data) {
//SUCCESS
$('.successORfail').html(data);
setTimeout(function(){
$(".successORfail").fadeOut("slow", function () {
$(".successORfail").remove();
});
}, 4500);
}).error(function() {
alert("Fatal Error: mail.php not found!");
});
e.preventDefault();
});
I was wondering if someone ran into a similar problem or knows how to solve this? I would like to be able to submit the form more than once, making changes to the form input values after each submit, if needed.
Many thanks in advance
Are you sure the AJAX request is not happening? It looks like you are removing the .successORfail element from the page, and thus the there is nothing to append the content to on subsequent calls.
Check your console and you will probably notice an ajax call happening each time.
Try changing your setTimeout to this:
var msgEl = $(".successORfail");
setTimeout(function() {
msgEl.fadeOut("slow", function () {
msgEl.empty().show();
});
}, 4500);
Your success event handler:
$('.successORfail').html(data);
setTimeout(function () {
$(".successORfail").fadeOut("slow", function () {
$(".successORfail").remove();
});
}, 4500);
is setting content in an element (.successORfail), then removing that element. The next time you submit the form, get a successful response, and that function is executed the element is no longer there to set the content into so you wouldn't see anything change.
Instead of removing the element, just .hide() it so that the next time it can be populated. You'll need to .show() it each time too.
$(document).on('submit', '#myForm', function(e) {
$.post('mail.php', $(this).serialize(), function (data) {
//SUCCESS
$('.successORfail').html(data).show(); //<-- show
setTimeout(function(){
$(".successORfail").fadeOut("slow", function () {
$(this).hide(); //<-- hide
});
}, 4500);
}).error(function() {
alert("Fatal Error: mail.php not found!");
});
e.preventDefault();
});
Also in the fadeOut() function, you can access the element with $(this) instead of re-selecting it based on the class name.
Can you add some HTML-snippet? Its hard to help without knowledge about your html-structure, because if you are replacing the form via $('.successORfail').html(data); the listener isn't re-bound to the form.
You should also return FALSE because the form-data is sent via javascript.
Well, it seems that you append your result to $('.successORfail').html(data); and the remove it. Take out the following and it should work multiple times...
$('.successORfail').remove();
Without that element, the change can't be made.

JS: Posting form directly

If on document.ready, I want my form to auto post itself, is this possible?
So when the document has loaded, then it posts itself and takes to the action="" (in this case is ?upload=true).
I heard about $.post() jquery, but this is just for posting in the background?
$.post() is an AJAX call and will not force the entire page to postback.
you may want to try
$(document).ready(function(){
var form = $("#yourformid");
form.submit();
});
Yes, $.post() in jQuery is for POST requests with AJAX.
If you want a form to submit on the document ready event, just invoke the submit itself!
$(document).ready( function()
{
$('form').submit()
});
You want something like this:
$(function() {
$('#myformid').submit();
});
See the documentation for jQuery's submit().
And see this working demo: http://jsfiddle.net/8hg8s/

Categories

Resources