Hi I'm looking to check my database when a user signs up to my website to make sure that the username they chose doesn't already exist and if it does let them know. My code below isn't working though the returns in the ajax don't seem to be returned to my form no matter what i do and the form always submits. Why is this happening? Thank you for any help
HTML
<form name="signup" action="Test1.php" onsubmit="return checkUser();" method="get">
Username: <input type="text" name="user" />
<input type="submit" value="Submit" />
</form>
Javascript
<script type="text/javascript" src="jquery-1.7.1.min.js"/></script>
<script type="text/javascript">
function checkUser(){
var userV = document.signup.user.value;
$.ajax({
url: "Test.php",
type: "POST",
data: {user:userV},
success: function (response) {
if(response=="0"){
//Username already exists notify user
return false;
}else{
return true;
}
}
});
}
</script>
Test.php
<?PHP
$user = $_POST['user'];
if($user=="test"){
die("0");
}else{
die("1")
}
?>
Test1.php
<?PHP
echo "Form submitted";
?>
You put the return value inside the success callback of your ajax call, whose execution is delayed till server answers.
onsubmit="return checkUser();" expects a true or false value in checkUser() function:
function checkUser(){
if( stuff )
return true;
else
return false;
}
Anyway this is an overall bad approach because it relies on intrusive javascript. A better solution would be moving all client side logic out of markup:
HTML
<form name="signup" action="Test1.php" method="get">
<label for="_user">Username:</label><input type="text" name="user" id="_user"/>
<input type="submit" value="Submit" />
</form>
JS
<script>
// wrapping the code in a $(function(){ ... }); call delays its execution till document is loaded
$(function(){
$('form[name="signup"]').on('submit', function(event){
// this prevents browser from actually following form url
event.preventDefault();
// a reference to the form to get used inside ajax callback
var form = this;
$.ajax({
url: $(form).attr('action'),
type: "POST",
data: {user:$(form.user).val()},
success: function (response) {
if(response=="0"){
alert('User exists!');
}else{
alert('User does not exist!');
}
}
});
});
});
</script>
Where the alerts would be a proper message to the user, or a more sophisticate validation - this is just for example's sake.
You return false in the callback, thats too "late", as it will be called when the request is done. Think about adding an explicit e.preventDefault() or return false to your function. Currently, it will return undefined, as you have defined the return statement in the "inner" function.
Of course you will then need to manually navigate to the target page.
Or set the async parameter of the $.ajax() call explictly to false.
Related
After following the example and answers by the following threads
jQuery AJAX submit form
submitting a form via AJAX
I have built a similar test form to get to learn the ajax request on submit. Your guess was right, it doesn't work for me (no alert popping up).
My testajax.php with the form:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="../test.js"></script>
<form name="feedback" id="idForm" action="(myurl)/testajax.php" method="post">
<input id="name" type="text">
<input type="submit" name="feedbacksent" value="Send" />
</p>
</form>
My test.js:
// this is the id of the form
$("#idForm").submit(function(e) {
var url = "(myurl)/testajaxinput.php"; // the script where you handle the form input.
e.preventDefault(); // avoid to execute the actual submit of the form.
alert("bla"); // does not work either
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});
My testajaxinput.php that should handle the input:
if (isset($_POST['feedbacksent'])){
echo "<h1>".WORKS."</h1>";
}
Try this :
if (isset($_POST['feedbacksent'])){
echo "<h1>".WORKS."</h1>";
return true;
}
Then try your alert and also check have you got any error in console.
I've read at least 20 of these similar questions and can't figure out what's wrong with my code.
I've got a login form as shown below:
<div class="login-form">
<form class="login-form-container" action="./" method="post" autocomplete="off">
<input id="login-user" type="text" placeholder=" Username"/>
<input id="login-pass" type="password" placeholder=" Password"/>
<div class="login-button-container">
<input id="login-button" type="submit" value="Log in"/>
</div>
</form>
</div>
My login.js script is as below:
$(document).ready(function(){
$("#login-button").click(function(e){
var username = $("#login-user").val();
var password = $("#login-pass").val();
$.ajax({url: "../includes/index.php", //.js file is in a diff directory
data: {'login':true,'name':username,'pwd':password},
type: "POST",
success: function(html) {
if (html=='true') {
//window.location="dashboard.php";
alert('success');
}
else {
alert('failure');
}
}
});
return false;
});
});
This is supposed to get sent back to 'index.php', which has included a separate php file that handles the login information. The reason for this is so I can update the page with the user's successful login without refreshing.
My other php file is simply checking for the post data:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
var_dump($_POST);
if (isset($_POST['login']) && $_POST['login']) {
} else if (isset($_POST['reg']) && $_POST['reg']) { //this is for registration, which will be used once this login is working
} else {
echo 'Neither login/reg were set';
}
The var dump shows:
array(0) { }
So the data is not being received. However, it clearly reaches the php page. I don't know what's wrong, any suggestions?
Edit: I figured I would add, that adding an alert at the top of login.js with the username/password does print the entered values. So the login.js is being reached, and the data is accessible there. But it doesn't go beyond that.
Edit2: Here is my updated HTML and login.js code:
index.php:
<form class="login-form-container" action="./" method="post" autocomplete="off">
<input id="login-user" type="text" placeholder=" Username"/>
<input id="login-pass" type="password" placeholder=" Password"/>
<div class="login-button-container">
<input id="login-button" type="button" value="Log in"/>
</div>
</form>
login.js
$(document).ready(function(){
alert(1);
$("#login-button").click(function(e){
alert(0);
//e.preventDefault();
var username = $("#login-user").val();
var password = $("#login-pass").val();
$.ajax({url: "../includes/index.php",
data: {'login':true,'name':username,'pwd':password},
type: "POST",
success: function(html) {
if (html=='true') {
//window.location="dashboard.php";
alert('success');
}
else {
alert('failure');
}
}
});
return false;
});
});
The solution was to change my
$("#login-button").click(function(e){
to
$(document).on("submit",".login-form-container",function(e) {
which will handle the form submit, and this includes pressing the button as well as hitting enter (ideal situation).
Now the data is being sent successfully and I can handle the actual login/registration SQL, so thank you to #Ashokkumar M. Prajapati for helping to come to the conclusion that the .js script was not actually firing upon submit (not that the rest of you didn't help!)
please replace type: "POST" with method: "POST"
you mentioned it wrong in jquery ajax function.
Default is "GET" in case you don't specify it. So, if you had checked both $_POST & $_GET then you would have found your data in $_GET.
try var_dump($_REQUEST) if it don't show up anything then your client is not sending data to server.
also, check net panel of you browser developer console. so, you will know what data are passed to server.
Can't figure out what's wrong but all that happens is the URL changes to "http://localhost/?search=test" if I enter "test" for instance.
index.php
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
</script>
<script>
$("#Form").submit(function(e) {
$.ajax({
type: "POST",
url: "search.php",
data: $("#Form").serialize(),
success: function(data)
{
alert(data);
}
});
e.preventDefault();
});
</script>
</head>
<body>
<form id=Form>
Search: <input type="text" name="search" id="search" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
search.php
<?php
echo 'The search is '. $_POST['search'];
?>
You're missing the action and method on your form, which are necessary for the form to generate a submit event.
<form id="Form" method="post" action="search.php" />
Now that we have the action and method defined, why not just take it from the form instead of re-writing it in Javascript? That would be better for re-usability. Also note that you have to assign event handlers when the DOM is ready. At the time you're assigning the event, the DOM element doesn't exist, so it will do nothing:
<script type="text/javascript">
$(document).ready(function() { // Here, after DOM is ready
$('#Form').submit(function(e) {
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(data) {
// At this point, we already have the response from the server (we got it asynchronously)
// Lets update a div, for example <div id="response_message"></div>
$('#response_message').text( data );
// Div already has data, show it.
$('#response_message').show();
// Another option (same as before but with a function): Pass the response data to another function already defined: processData() in this case
// Use one or another, they're the same
processData( data );
},
error: function(err) {
alert('An error just happened...');
}
});
});
});
// This functions only receives data when the asynchronous call is finished
function processData( data )
{
$('#response_message').text( data );
// Div already has data, show it.
$('#response_message').show();
}
</script>
Note that in asynchronous calls you DO NOT expect a return. It simply doesn't exist by design (because the script would be blocked until the data is ready, and that's called synchronous). What you do in asynchronous calls is to define a function/method that will be called at any time when the data is ready (that's the success handler function). You don't know at what time it will be called, you only know that it will be called when data has been fetched and the argument will be the actual response from the server.
1st you forget " Form id and good to add method=""
<form method="post" action="#" id="Form">
2nd try to use e.preventDefault(); in the beginning not the end
3rd try to rearrange the code
<body>
<form method="post" action="#" id="Form">
Search: <input type="text" name="search" id="search" /><br />
<input type="submit" value="Submit" />
</form>
<script>
$("#Form").on('submit',function(e) {
e.preventDefault(); // use it here
$.ajax({
type: "POST",
url: "search.php",
data: $("#Form").serialize(),
success: function(data)
{
alert(data);
}
});
});
</script>
I want to submit a form with php variables to input into javascript, the problem is that the variables are only set after posting, which is too late for them to be echoed into the javascript. Of course, if I then submit again, the variables have been implemented into the javascript and it works as it should. However, I would prefer just to submit once.
Is there any way to validate the form before submission ? Here is an example of my dilemma:
<?php
if(isset($_POST['submit'])){$name=$_POST['name'];}
?>
<html>
<div id="message"></div>
<form action="home.html" method="POST">
<input type="text" name="name">
<input type="submit" name="submit" value="conditions-met"
onclick=<?php if($name=="bob"){echo"start();";}?>>
</form>
</html>
<script type="text/javascript">
function start(){
document.getElementById('message').innerHTML = 'hello bob';
return true;
}
</script>
Man people are mean to you!!
Basically you should validate the fields using JavaScript.
When the submit button is clicked do the checks. Continue on success, show an error message on failure.
example
<form id="myForm" onsubmit="return ValidateFields(this)" name="myForm" accept-charset="UTF-8" enctype="multipart/form-data"" action="myPhpScript.php" method="POST">
// html fields
</form>
<script>
function ValidateFields(formObject)
{
var FieldsValid = true;
//Validate the fields and if one of them is not valid set FieldsValid to false
if(!FieldsValid )
{
//show an error message
return false; // Returing false will prevent the form from submitting
}
return true;// the form will be submitted
}
</script>
In order to become a ninja please read the following:
http://www.script-tutorials.com/form-validation-with-javascript-and-php/
http://www.webcredible.co.uk/user-friendly-resources/dom-scripting/validate-forms-javascript.shtml
http://www.w3schools.com/js/js_form_validation.asp
<html>
<div id="message"></div>
<form action="home.html" method="POST" onsubmit="return validate()">
<input type="text" name="name" id="name">
<input type="submit" name="submit" value="conditions-met" >
</form>
</html>
<script type="text/javascript">
function validate(){
name=document.getElementById('name').value;
if(name == "")
{
document.getElementById('message').innerHTML = 'Please Fill Name';
return false;
}
return true;
}
</script>
You can do it with Ajax and beforeSubmit function with Jquery You have:
$.ajax({
url: "your async page in php",
cache: true,
data: $("#formID").serialize(),
type: 'POST',
beforeSend: function(){
/* You can validate your input here*/
},
success: function(response){
/* Based on the response from php you can handle the message to the user*/
},
error: function(response){/*Error Handler*/},
complete: function(){/*If it's complete than you can reset the form*/}
});
I think it's easy and more clear if you use cross Ajax/PHP request
The function bound to the onclick-event must return true if validation is correct, or false otherwise.
The same function must be in javascript. You cannot call a php function in it. If you want php, try ajax.
<input type="submit" onsubmit="return validate();" />
<script>
function validate() {
// do validation in javascript
// or make an ajax request e.g. to
// /validate.php?name=somename&surname=someothername
// and let this request answer with true or false
// return true if valid, otherwise false
}
</script>
Ok, if somebody could take a look at this, I'd really appreciate it. I'm implementing a captcha in an html form. The captcha is php based, so i need to use jquery to post the submitted form to the captcha check script.
The php script returns 1 if the check was correct, or 0 if it was incorrect.
This is all working great, the problems i am having are with actually submitting the form, or preventing it based on what the php script returns. My the code is as follows:
<form id="contactform" action="FormHandler.cgi" method="POST">
<input name="requiredContact" size="25" type="text" />
<input name="requiredEmailFrom" size="25" type="text" />
<input name="requiredTelephone" size="18" tabindex="3" />
<textarea cols="25" name="comments" rows="4"></textarea>
<select length="2" name="requiredContactMethod" tabindex="5">
<option selected="" value="Email">Email</option>
<option value="Telephone">Telephone</option>
</select>
<img src="captcha/captcha.php" style="float:none; margin:0px 0px -8px 0px; height:26px;"></img>
<input type="text" id="CAPTCHA" style="margin-left: -5px; height:26px;">
<p id="caperror"></p>
<p><input name="B1" type="submit" value="Submit" />
<input name="B2" type="reset" value="Clear" /></p>
</form>
<script>
$('#contactform').submit(function(){
var cap = $('#CAPTCHA').val();
cap = 'CAPTCHA=' + cap;
$.ajax({
type: 'POST',
url: 'captcha/capcheck.php',
data: cap,
dataType: "text",
error: postfail,
success: success
});
return false; //Temporary, to stop the form no matter what.
});
function success(result){
if(result == 1){
alert('was correct');
return true;
}
else{
alert("error" + result);
return false;
}
}
function postfail(){
alert('post failed');
return false;
}
</script>
So what i would like to happen, is when my success function returns false, it stops the form from submitting. If it returns true, go ahead and submit the form. This is what I would like
$('#contactform').submit(function(){
//The ajax post here
//check the value of the ajax success function here;
if(success(result)) {
return true;
}
else {
return false;
}
});
I am not good with function scopes in javascript. If I define a variable inside the success function, I can't check the value in the form submit function, because it only has a local scope. I could just use a link to submit the form, and then call submit(); but I want the form to be accessible to those without java.
Is there any way to get the ajax post success function's result back to the scope of the submit() handler?
Unless I'm missing something, you should be submitting the form in the AJAX call's success function. The AJAX call should also not be being thrown upon form submit. The form should not be being submitted in any way until the check has come back true. IE:
$.ajax(
//Parameters and stuff
).success(function() {
//Submit the form
$('#contactform').submit();
}).fail(function() {
//Onoes your call has failed. Do not submit le form :(
});
As far as "scoping" goes, this shouldn't be a "scoping" issue. Let me know if you need further instruction.
I would write the function like this only setting submitForm on a 1 result.
$('#contactform').submit(function(){
var submitForm = False;
var cap = $('#CAPTCHA').val();
cap = 'CAPTCHA=' + cap;
$.ajax({
type: 'POST',
url: 'captcha/capcheck.php',
data: cap,
dataType: "text",
success:function(result){
if(result == 1){
submitForm = True;
}
}
});
return submitForm;
});
I was going to suggest that in your success function you call $('#contactform').submit(), but that would just call your event handler again and you'd be stuck in a loop.
What instead you can do is call the form element's submit function, like this:
$('#contactform').submit(function(){
var cap = $('#CAPTCHA').val();
cap = 'CAPTCHA=' + cap;
myform = this; // added this line
$.ajax({
type: 'POST',
url: 'captcha/capcheck.php',
context: myform, //added this line
data: cap,
dataType: "text",
error: postfail,
success: success
});
return false; //Temporary, to stop the form no matter what.
});
function success(result){
// because we added the context option, we can now access the form with the "this" keyword
if(result == 1){
alert('was correct');
// $('#contactform').submit() // this will make an infinite loop
this.submit(); // this will submit the form
return true;
}else{
alert("error" + result);
return false;
}
}
Try making the ajax call on the submit button click not on the form submit.
If the return of the click call is true, you call the submit function.