When i click my login button, it just reloads the page for some reason. it should alert the string i echo from my php page.
This is my login.js code:
$(document).ready(function(){
$('#login').click(function(){
$('#msgLoginStatus').show();
$('#msgLoginStatus').html("processing...");
$.post('login.php',{username:"bob",password:"pass"}, function(data){
alert(data);
});
});
});
my login.php:
<?php
echo "message";
?>
and my form:
<form id="loginForm" action="" method="post">
<fieldset id="body">
<fieldset>
<label for="username">Username</label>
<input type="text" name="username" id="username" />
</fieldset>
<fieldset>
<label for="password">Password</label>
<input type="password" name="password" id="password" />
</fieldset>
<button id="login">login</button>
<label for="checkbox"><input type="checkbox" id="checkbox" />Remember me</label>
<br />
<p id="msgLoginStatus" style="display:none"></p>
</fieldset>
<span>Forgot your password?</span>
</form>
There are no errors in browser console. I tried this also using $.ajax, it returned an error, i tried putting the error variable in an alert, but when it alerted, it was an empty string. Anyone have an idea whats wrong?
Your login button has an ambiguous action - add type="submit" like this:
<button id="login" type="submit">Login</button>
Now if you really want to execute an explicit POST with JavaScript, call e.preventDefault so the browser's automatic "submit" action will be suppressed.
e.preventDefault();
$.post(...);
But it will probably be better to let the form submit itself. To do this specify the correct action="login.php" attribute in the form:
<form id="loginForm" action="/login.php" method="post">
Keep your existing "click" handler on the login button, just remove the "$.post" part and let the browser handle the posting. You'll still get the nice "processing..." text.
Even better, handle the "submit" event on the form instead of the "click" event on the button:
$('#loginForm').submit(function(e) {
$('#msgLoginStatus').show();
$('#msgLoginStatus').html("processing...");
});
This way you'll get the nice updates whether the user submits the form using the button or by pressing "enter" on the keyboard.
Try:
$('#login').click(function(e){
e.preventDefault();
$('#msgLoginStatus').show();
$('#msgLoginStatus').html("processing...");
$.post('login.php',{username:"bob",password:"pass"}, function(data){
alert(data);
});
});
That prevents a "normal" submit from happening (which, I take, is why you are not getting any errors).
See http://api.jquery.com/event.preventDefault/
Add e.preventDefault(); to the clck handler (and grab the event object in the handler as e).
Or you can Just set the button type = 'Button' and not Submit. THis will also run your code
<button id="login" type="button">Login</button>
In this way you don't have to halt the browser's event
Related
I have written a HTML form and script to validate the form. The issue is that whenever I go to submit the form I get redirected to a page that tells me "Your file was not found".
Is there a specific way I have to call the script? or any way I can force it to run without redirecting me?
<form id="bioform" action="/action_page.php">
<label>Biography</label><br>
<textarea placeholder="Enter bio here" name="bio" rows="10" cols="50"></textarea><br><br>
<label>Update Biography Picture</label><br><br>
<input type="file" name="bioimage"><br><br>
<button type="submit" onclick="function()">Update</button><br>
</form>
<script>
$(document).ready(function () {
$('#bioform').validate({
rules: {
bio {
required: true,
minlength: 5,
},
}
messages: {
bio {
required: 'Please enter a biography.',
minlength: 'Please enter a valid biography.',
},
}
});
});
</script>
Add enctype="multipart/form-data" to form tag
<form id="bioform" action="/action_page.php" enctype="multipart/form-data">
<label>Biography</label><br>
<textarea placeholder="Enter bio here" name="bio" rows="10" cols="50">
</textarea><br><br>
<label>Update Biography Picture</label><br><br>
<input type="file" name="bioimage"><br><br>
<button type="submit" onclick="function()">Update</button><br>
</form>
Is the forward slash when specifying where it sends to necessary? For instance:
<form id="bioform" action="/action_page.php">
Should be replaced with:
<form id="bioform" action="action_page.php">
Since you're using jQuery, try using this:
e.preventDefault()
The e.preventDefault() method stops the default action of an
element from happening. For example: Prevent a submit button from
submitting a form. Prevent a link from following the URL.
Also, you need to add method attribute inside the <form> tag with value POST and also the enctype="multipart/form-data" since you're dealing with file upload.
Go to this fiddle and check if it works for you: https://jsfiddle.net/z0db4vq0/1/
I have this in my PHP code, and it currently does the login request in the same login.php page but now i want to do it with Ajax. Basically I have this in the login.php
echo '<form method="post" ><div id="login" class="login">
<label for="login">User Name</label>
<input type="text" name="logInUsername" />
<label for="Password">Password</label>
<input type="password" name="logInPassword" />
<input type="submit" value="Submit" name="submitlogin" class="button" />
</div>';
I would like to still use this but have a login_request.php or something where i can send the username and password validated and then change the <div id=login> to say you are logged in!</div> I can do it the conventional way, with the form post .. but now I would like to try it with Ajax.
Any help will be much appreciated.
Regards
What have you tried so far? This is how I would start:
This should get you started:
HTML:
<form id="loginForm">
<div id="login" class="login">
<label for="login">User Name</label>
<input type="text" name="logInUsername" />
<label for="Password">Password</label>
<input type="password" name="logInPassword" />
<input type="button" value="Submit" id="submitlogin" class="button" />
</div>
</form>
jQuery:
$("#submitlogin").click(function() {
inputs = //grab then inputs of your form #loginform
$.ajax ({
url: "urltoyourloginphp.php",
data: inputs,
success: function() {
$("#login").html("You are now logged in!");
}
});
})
I wrote this a while ago, it's not quite a full ajax login (i.e. at the end it does still redirect you), but it may serve as a basis for a full ajax login. As a plus you actually don't need https (that was the whole point of this little project).
https://github.com/eberle1080/secure_http_login/blob/master/login.php
The high level steps go something like this:
Ask the server for a seed value (a salt) using an ajax request
Hash the password + seed using a sha1 sum
Ask the server to verify the username and salted + hashed password
If it's valid, the server sets a session cookie indicating that the user is logged in
The server responds to the ajax request with a success / fail message
jQuery has built in .post() and .serialize() methods for wrapping up a form.
$.post("login.php", $("#loginForm").serialize(), function(data) {
//pass information back in with data. if it's JSON, use $.parseJSON() to parse it.
alert('either logged in or errored');
);
You will also need to edit your form so it has an id, like: <form id="loginForm">...
I don't know PHP but will give you an example of how I would have done it with vbscript (classic asp) so you may try to adapt it to PHP as needed.
I, in my applications, don't use the form tag since I first used ajax. So, here we go:
login html page:
include jquery
<script type='text/javascript' src='your-jquery-url'></script>
<script type='text/javascript'>
function tryLogin() {
var inputs='userName='+$('logInUsername').val()+
'&userPassw='+$('logInPassword').val();
//notice that I changed your name= to id= in the form
//notice the '&' in the '&userPassw=
$.post('your-login-validation-page',inputs,function(data) {
eval('var json='+data);
if (json['success'] == 'true') {
$('#loginForm').html('<p>Congratulations! You\'ve been logged in successfully</p>')
} else {
alert(json['errorMessage']);
$('#logInUsername').focus();
}
});
}
</script>
<div id='loginForm' >
<label for="login">User Name</label>
<input type="text" id="logInUsername" />
<label for="Password">Password</label>
<input type="password" id="logInPassword" />
<button onClick='tryLogin(); ' >LOGIN</button>
</div>
login-validation-page
[in vbscript]
user = request.Form("userName")
passw = request.Form("userPassw")
"if is there this user" (coded as if there was a database look up...)
"if the password = passw" (coded as comparing the values)
response.write "{'sucess':'true'}"
else
response.write "{'success':'false','errorMessage':'wrong password'}"
end if
else
response.write "{'success':'false','errorMessage':'user not found'}"
end if
---> end of login-validation-page
I have seen what seems like a hundred ways to do what I want but I can't seem to get a single one to work. I have a test page here : http://upcycledonline.com/test/Site/defaultUpCyc.php
What I want to happen is when the user clicks submit a pop window appears saying "Thanks! Your email has been added". When they click 'ok' the pop will close and the page refreshes. Right now I have the pop up going but after clicking the ok button it goes to my PHP page.
FYI: I am new to PHP and Javascript
Here is the form code and Javascript
<div id="signUp">
<script>
function confirmSubmit() {
if (confirm("Are you sure you want to submit the form?")) {
document.getElementById("FORM_ID").submit();
}
return false;
}
</script>
<?php
//if the validation falls back to php, then print the validation error
if (isset($error_message)) echo $error_message;
?>
<form method="post" action="process-form.php" id="emailForm" name="emailForm" target="_self">
<h4>Sign up to be notified when we go live!</h4>
<!--value="<?php if (isset($_POST['email'])) echo $_POST['email'];?>"-->
<label for="email">E-mail</label>
<input type="text" name="email" id="email" />
<!-- onSubmit="alert('Thank you. Your email has been added.')"-->
<input type="submit" name="submit" id="submit" value="Submit" onclick="return confirm('Are you sure?');">
<p>emails will not be shared with third parties</p>
</form>
<script>
<?php echo $validation_js_code;?>
</script>
</div>
You could do a couple things:
move your form processing logic to defaultUpCyc.php, submit the form to that URI and then have defaultUpCyc.php both process the form and reload the page.
Use AJAX, and post the data to process-form.php, this wouldn't require any refresh at all.
Do a redirect in process-form.php to defaultUpCyc.php.
I'm using the jQuery Form plugin to submit AJAX requests. It's a simple contact from using this PHP script: http://pastie.org/725652 - the only validation happens inside the PHP.
Here's my Javascript code to trigger the whole thing:
$('#contactform').ajaxForm({
target: '#error',
beforeSubmit: function() {
$('#error').append('<p class="loading">Sending your message...</p>');
},
success: function() {
$('#error p.loading').fadeOut();
$('#error').fadeIn('slow');
}
});
Unfortunately, it doesn't seem to work. The PHP works perfectly, sends the email and returns the success message, but the AJAX magic isn't working for some reason. Obviously what I want to achieve, is to display the message returned by the PHP script via AJAX in the <div id="error />
I used the same script many times and never had any problems with it, now I can't figure out why it doesn't work. Here's the markup for the contact form.
<form id="contactform" class="group" method="post" action="submitemail.php">
<fieldset>
<div><label for="first-name">First Name</label>
<input type="text" name="first-name" value="Jeremy" /></div>
<div class="alt"><label for="last-name">Last Name</label>
<input type="text" name="last-name" value="Anderson" /></div>
<div><label for="email">E-mail <span>(never published)</span></label>
<input type="text" name="email" value="jeremyanderson#mywebsite.com" /></div>
<div class="alt"><label for="url">Website</label>
<input type="text" name="url" value="http://www.mywebsite.com" /></div>
<label for="question">Message</label>
<textarea name="question" id="" cols="30" rows="10">Thinking of something to say...</textarea>
<input type="submit" name="submit" id="submit" value="Send E-mail" />
<div id="error"></div>
</fieldset>
</form>
Here's the code of the jQuery plugin if it can be any help. http://pastie.org/726175
If anyone could look at the whole thing and provide some tips why would it not work, I would be very grateful, thanks in advance!
you must include the parameters in which are the response from PHP:
EDIT:
try with these changes, in this example I'm separating the message "loading" with the response message.
HTML:
<form id="contactform" class="group" method="post" action="submitemail.php">
<fieldset>
<!-- fields -->
<input type="submit" name="submit" id="submit" value="Send E-mail" />
<div id="error"><span id="eloading"></span><span id="eresponse"></span></div>
</fieldset>
</form>
Javascript:
$('#contactform').ajaxForm({
target: '#eresponse',
beforeSubmit: function() {
$('#eresponse').hide('slow');
$("#eloading").append("<p class=\"loading\">Sending your message...</p>");
},
success: function(responseText, statusText) {
alert("test status: " + statusText + "\n\nresponseText: \n" + responseText);
$("#eloading").empty();
$('#eresponse').show('slow');
}
});
It didn't do the trick :( It still
goes to the submitemail.php file with
the success message instead of showing
the message in #error. – Justine 39
mins ago
If this happens that means the function attached to the submit event didnt end with
return false;
i beleive with ajaxForm this is done automagically so that means there is an error in your code somewhere. If you dont have firebug installed, install it and keep an eye on the console make sure:
jquery is loading ok
there are no
errrors setting up the ajax
interaction or in any other js on
the page that may stop it
I need jquery to check if my posted filename (up_image) is empty or not.
if it's empty i need a div tag to be shown and come with some kind of alert message.
if not, just do the
$("#submit").submit();
<form action="/profile/" method="post" enctype="multipart/form-data" id="submit">
<p>
<label for="up_image">image:</label>
<input type="file" name="up_image" id="up_image" />
</p>
Upload
</form>
$(function() {
$("#post_submit").click(function() {
var fil = $("#up_image");
if($.trim(fil.val()).length == 0) {
alert("Choose a file!");
fil.focus();
return false;
}
$("#submit").submit();
});
});
1: use a standard submit button to submit your form rather than a javascript-dependent link, for accessibility reasons, and to prevent brokenness if someone tries to right-click-open-in-new-window or other similar action on the link. If you want it to look like a link, you can still use a button, just apply some CSS to make it no longer look like a button.
2: use the form.onsubmit event to do validation rather than relying on a submit button click (forms can also be submitted by pressing enter, which may not always generate a button click)
<form id="uploadform" method="post" action="/profile/" enctype="multipart/form-data">
<p>
<label for="up_image">image:</label>
<input id="up_image" type="file" name="up_image" />
</p>
<p>
<input type="submit" value="Upload" />
</p>
</form>
<script type="text/javascript">
$('#uploadform').submit(function(e) {
if ($('#up_image').val()=='') {
alert('Please choose a file to upload.');
e.preventDefault();
}
});
</script>