I have a form like this
<div data-role="page" id="callAjaxPage">
<div data-role="header">
<h1>Login</h1>
</div>
<div data-role="content">
<form id="callAjaxForm">
<div data-role="fieldcontain">
<label for="userName">Username</label>
<input type="text" name="userName" id="userName" value="" />
<label for="password">Password</label>
<input type="text" name="password" id="password" value="" />
<button data-theme="b" id="submit" type="submit">Submit</button>
</div>
</form>
</div>
</div>
And in the $(document).ready () the code is
$(document).ready(function() {
$("#submit").click(function(){
alert("Hi");
});
});
Then it works for the first time. But Second time my screen gets distorted.
If i put <form id="callAjaxForm" data-ajax="false"> then it is little bit better.
But still If i press submit it shows me an alert.And i have to wait a long time for the second alert..
Why is this happening?
Behavior you’re experiencing is correct for jQuery mobile.
In jQuery mobile, there’s a concept of keeping user on the same page and rely heavily on ajax calls. That’s aimed to prevent reloading whole page and having to fetch again all the resources. Read this page, especially markup conventions section http://jquerymobile.com/test/docs/forms/docs-forms.html.
Now that we have some background knowledge of how jQuery mobile works, we can take a swing on your problem.
The reason why there’s no second alert message when you don’t put
data-ajax="false"in your form is simply because the form you see after clicking#submitbutton for the first time isn’t the same form. It looks the same, it has the same markup, but that’s because jQuery mobile submits the form to the same address you’re on and displays the result. Click event handler you’ve attached on page load was valid at that time (meaning it still works but for that previous, now hidden button), so there’s no way you will see your alert message. Working example: http://jsfiddle.net/c4uy7/5/show/ notice the page transition that clearly shows how your initial form gets hidden (also notice the browser address bar – it stays the same).So that’s the first case. The behavior after adding
data-ajax="false"to the form results in jQuery mobile to submit the form regular way, so the page actually get reloaded and the click handler for#submitbutton works every time. The long waiting time you mentioned may be caused by your network lag, slow server-side processing or something like that. Here’s example http://jsfiddle.net/c4uy7/4/show/ – clicking on submit shows alert every time (page gets reloaded as you can see by looking at the parameters in address bar).