PHP included JavaScript is not working properly in Jquery Mobile - javascript

In my jquery mobile web app I include a Login-Form on every page the user is navigating to. I do that so that the user could login at every time he wants to, not just on the start page.
Since I do the Form submitting procedure with my very own Ajax logic, I disabled the Jquery Mobile Ajax logic with data-ajax="false" on the Form. The Ajax logic is implemented with JavsScript. On the start page everything works fine, but if I navigate to another page (through a link on the start page), my JavaScript is not firing anymore, but the form is submitted via the Jquery mobile own Ajax logic (and therefore it don't works).
The code (which I include at every page) looks like this:
<div data-role="fieldcontain">
<form id="loginForm" data-ajax="false" onsubmit="login();return false;">
<div data-role="fieldcontain">
<h2>Login</h2>
<label for="textinput1">
Email
</label>
<input name="emaillogin" id="textinput1" placeholder="Email" value=""
type="text">
<label for="textinput2">
Password
</label>
<input name="passwordlogin" id="textinput2" placeholder="Password" value=""
type="password">
</div>
<input type="submit" data-icon="ok" data-iconpos="left" value="OK">
<input type="hidden" name="inputCase" value="login">
</form>
</div>
The JavaScript (which is just at the end of the Code stated above) looks like that:
<script>
function login()
{
var request = $.ajax({
url: "../case.php",
type: "POST",
data: $('#loginForm').serialize(),
dataType: "json"
});
request.done(function(msg) {
if(parseInt(msg.status)==1)
{
//top_notification("Willkommen zurück!","success");
window.location="index.php";
}
else if(parseInt(msg.status)==0)
{
alert(msg.text);
}
else {
alert("Gibts nicht");
}
});
request.fail(function(jqXHR, textStatus) {
alert("Fehler");
});
}
</script>
Maybe I got the Jquery Mobile "we replace just the page-div with the other page-div from the new URL" thing wrong, but I understand it in that way that my whole JS logic will also be pulled from the new ressource.
EDIT Thanks. I have updated my JS code, which looks now like that:
<script>
$(document).on('pageinit', '[data-role="page"]', function(){
$(document).on('click','#submit-btn',function() {
login();
});
});
function login()
{
var request = $.ajax({
url: "../case.php",
type: "POST",
data: $('#loginForm').serialize(),
dataType: "json"
});
request.done(function(msg) {
if(parseInt(msg.status)==1)
{
//top_notification("Willkommen zurück!","success");
window.location="index.php";
}
else if(parseInt(msg.status)==0)
{
alert(msg.text);
}
else {
alert("Gibts nicht");
}
});
request.fail(function(jqXHR, textStatus) {
alert("Fehler");
});
}
</script>
BUT. Now when I navigate to 3 pages, and then submit the login Form, I will get 3 alerts (even when I navigate to just 1 site) of the request.fail function... after that the login goes correctly!

Ajax is still your problem. You have disabled ajax form submition but ajax is still used to load additional pages. This is just my assumption because you didn't mentioned that ajax is turned off all together.
If ajax is still used to load pages all your other pages are loaded into the DOM. Because of this you will have multiple forms with a same ID. When your first page is loaded there's only 1 form in a DOM and that form is used. But when another pages is loaded then additional form (with a same id) is added to the DOM. And whey you click a submit button jQuery will find first form with that ID from the DOM. And because there are 2 of them it will submit first for, same form loaded with an initial page.
That is why you NEVER use inline javascript with jQuery Mobile.
Instead of
onclick="..."
Your submit button should have an id and make it type="button".
<input type="button" data-icon="ok" data-iconpos="left" value="OK" id="submit-btn">
Put a click event on every button and use a $.mobile.activePage selector to find a form on an currently active page.
$(document).on('click','#submit-btn',function() {
$.mobile.activePage.find('#loginForm').submit();
});
Also everything should be wrapped inside a correct jQuery Mobile page event:
$(document).on('pageinit', '[data-role="page"]', function(){
$(document).on('click','#submit-btn',function() {
$.mobile.activePage.find('#loginForm').submit();
});
});

Related

tag <form> deletes part of code after ajax request?

I have a kind of form like this:
<form>
<input class="form-control" id="searchField" type="text">
<button type="submit" id="searchUserButton">SEARCH BUTTON</button>
</form>
When I press on SEARCH BUTTON (I'm using jquery to figure out when button is pressed), I call an ajax request and I print some information from json file in a html file BUT something strange happens:
I can't see the result! Otherwise if I remove the form tag (so I have just input and button element) everything is ok, I can see all the data...so what happens?! How should I do in the right way an ajax request with jquery (so when button is pressed)?
Jquery:
$("#searchUserButton").bind("click", function () {
searchData();
});
Ajax:
function searchData() {
$.ajax({
type: 'GET',
url: 'data/file.json',
dataType: 'json',
success: showData,
error: function () {
// FAIL
alert("ERROR!");
}
});
}
Change your click event to this:
$("#searchUserButton").bind("click", function (e) {
e.preventDefault();
searchData();
});
Your problem seems to be what I had assumed in the comments above.
A type="submit" button inside of a <form> will cause the form to process and the page to reload, whereas without <form> tags, this will not happen. By doing e.preventDefault();, you're instructing the button to not submit the form, and instead do your searchData() function.
Just change
<button type="submit" ...
to
<button type="button" ...
otherwise the form submits anyways and your page reloads regardless of your click handlers.

Log in from another php file with jquery load function

I would like to do a web site using Aptana IDE and xampp, and it has a few pages. Index page is where all users which does not log in the system and home is where all users which does log in the system must visit. I am very new to develop web site. Because of that I am changing a lot of and vital things during the development. An here my problem is began.
I have created log and sign pages separately using HTML5, CSS, Javascript, JQuery and Php. To achieve more quality service, decided to use also Ajax. These pages works correctly, log page can control validation with jquery
$('#login-form').validate({
//validation rules, messages and submitHandler(ajax code) goes here});
and with using ajax, it can communicate with php file and mysql database so can check whether the user is exist or not.
$.ajax({
type: 'POST',
url: 'log.php',
data: strAjax, //username and password
success: function(data) { //data is echoing from php file either as true or false
if(data) {
window.location.href = "home.php";
}
else {
//some error messages
}
}
});
Sign systems works like it and correctly. But I do not like the design of these pages because of emptiness. So in index file when user click log in button, the log file is showing inside a div with jquery load function.
$(".jumbotron").load("login.html").hide().fadeIn(1500).delay(5000);
Same thing for sign system as well. For good looking, I am satisfied but...
The whole system messed up. (I want to cry) I have to think before start to coding web site, very bad I know but this is my first complete web site. How can achieve a system working properly in this way? I have searched some pages on the internet and they said that the ajax can not work across the pages or something like that. I am also new to stack overflow too, so some important thing will be forgotten. I can edit if you want more information.
Thank You and Regards...
EDIT 1:
<div class="jumbotron">
<div class="container">
<h1>//sometext</h1>
<p>//some text</p>
</div>
</div>
Firstly this is showing on the screen. And when the user press login button, jquery load function running which is above. And loads login.html which works properly by itself.
<form id="login-form" class="text-left">
<div class="form-group">
<label for="lg_username" class="sr-only">Username</label>
<input type="text" class="form-control" id="lg_username" name="username" placeholder="username"
data-container="body" data-toggle="popover" data-placement="left" data-content=""
value="">
</div>
<div class="form-group">
<label for="lg_password" class="sr-only">Password</label>
<input type="password" class="form-control" id="lg_password" name="password" placeholder="password"
data-container="body" data-toggle="popover" data-placement="left" data-content="">
</div>
<div class="form-group login-group-checkbox">
<input type="checkbox" id="lg_remember" name="lg_remember">
<label for="lg_remember">remember</label>
</div>
<button type="submit" class="login-button">Submit</button>
</form>
The jquery validation works right. My rules are valid. If the inputs are ok upon my rules, it send me to home.php. I think ajax code can not work.
submitHandler: function() {
var username = $('#lg_username').val();
var password = $('#lg_password').val();
var checkbox = $('#lg_remember').is(":checked");
var strAjax = "username=" + username + "&password=" + password + "&checkbox=" + checkbox;
$.ajax({
type: 'POST',
url: 'logDeneme.php',
data: strAjax,
cache: false,
success: function(data) {
if(data) {
window.location.href = "home.php";
}
else {
//error message. but when this code run, always send to home page.
}
}
});
return false;
}
This parts all works. It does not works inside index.php. My question is why and how to handle this!
Problem 1
Your form is submitting via a GET request because the JS is not getting called (see #2 below) and the HTML is likely declared like this:
<form action='log.php'>
[...]
</form>
You must specify method='post' to submit POST data.
Problem 2
Unless you're using a jQuery plugin there is no .validate event for forms. You want to use .submit.
Finally, make sure all your javascript is in $(document).ready(function() { ... }); or it won't execute at the right time. Look in the Firefox/Chrome developer console, it's a lifesaver for debugging.

Using AJAX in login procedure

I just changed my login file login.php to a website I am building, as to apply AJAX inside it just to keep username and password visible in case of fault. In case of success I am using javascript
window.location = 'index.php';
as to redirect the user to the right place.
In my previous login file I did not use AJAX and the form submission was just calling the same login file. The last method was not keeping username and password and also I was using PHP
include "index.php";
as to redirect the user to the right place.
However, there is something I do not like with the first method. The transition from the login form to index.php is not smooth as it is with the second method and the screen seems first to reload login.php instantly and then go to index.php. Do you have any explanation or any solution as to eliminate this little flicker?
I am using the Jquery form plugin. It follows login.php
$(document).ready(function() {
$('#user_login_form').ajaxForm({
dataType: 'json',
success: processJson
});
});
function processJson(data) {
if (data=="database problem")
{
...
return;
}
if (data=="no member")
{
...
return;
}
window.location = 'index.php';
}
<form action="login_user_authorization.php" method="post" name="user_login_form" id="user_login_form" onsubmit="return validate_login_user()">
<input name="user_email" type="text" id="user_email"/>
<input name="user_password" id="user_password" type="password" />
<input type="submit" name="submit_button" id="submit_button" value="ENTER" />
</form>

Submit Form that is Dynamicly inserted into the page using jQuery and AJAX?

I have a Form that is generated with JavaScript and then inserted into a popup Modal window.
My form HTML is not generated or inserted into the page until well after the DOM has generated the whole page (it is triggered from a Socket post event which then makes my popup open and inserts the HTML for this form)
There can also be multiple Forms inserted into the page so not just 1.
Here is an example of the form code that is generated and inserted into the page...
<form action="/" id="logCallForm" class="logCallForm">
<div class="col-xs-10">
<input class="form-control input-sm" type="text" name="subject" placeholder="Subject">
<br><input type="hidden" name="qmsId" value="1c885762-27d5-58ef-9f95-527ae750c9be">
<input type="hidden" name="dateTime" value="2013-11-07 01:05:19">
</div>
<input type="submit" value="Save Call">
</form>
Now below is some JavaScript that is already running on the same page, my goal is to be able to POST these Forms using AJAX. Right now it does not seem to detect the code though as when I hit the submit button, it loads a new page instead of trying to submit through AJAX.
Please help me? I am pretty sure it has something to do with my Forms being added after the page has been loaded already?
$(function () {
$('.logCallForm').on('submit', function (e) {
var url = '/custom/modules/nam_call_logger/call_server.php';
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(), // serializes the form's elements.
// qmsId dateTime subject
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault();
});
});
Try subscribing in a lively manner:
$(document).on('submit', '.logCallForm', function (e) {
Basically this will subscribe to the submit event of elements that match the selector, even if those elements do not yet exist at the time you are making the subscription (a.k.a the DOM load of the page). It will listen for future elements that might be added to the DOM and which match the selector.

basic html text form

I want a text form for entering a string which is later read by javascript.
<form style='margin:10px;'>
Input Value: <input type="text" value="3" id="input" name="input"/>
</form>
I'm noticing that when I press enter while it's selected causes the page to be reloaded. This is not what I want. How do I make it not reload the page when the form is "submitted"?
Do you need the <form> tags? They don't seem to be doing anything. If you remove them you will no longer get that submission behaviour when you hit enter.
Pressing enter is submitting the form. You can use Javascript to prevent the form from being submitted - one way of doing that is by using a submit button:
<input type="submit" onsubmit="formhandle(); return false;">
Create a formhandle() function in Javascript to do the processing you want to do. Returning false should prevent the form from being posted back to the server - however, that doesn't always work. There's more detailed information on preventing default actions in browsers here:
http://www.quirksmode.org/js/events_early.html
You have to catch the form send with JScript and send it to the server with ajax
<form style='margin:10px;' id='formID'>
Input Value: <input type="text" value="3" id="input" name="input"/>
</form>
the JQuery (you can use Prototype or pure JS if you want) code goes a litte something like this
$('#target').submit(function() {
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType,
});
return false;
});
The return false prevents the page from reloading. The documentation can be found here

Categories

Resources