So I have a form as such:
<form action="URL" name=myform method=post onsubmit="return validateFormOnSubmit(this)" autocomplete=off>
When the form is submitted, it checks for validation.
Earlier though, I have code like this:
<script type="text/javascript">
$(function() {
$("#submitbutton").click(function() {
var fname = $("input#first_name").val();
var lname = $("input#last_name").val();
var email = $("input#email").val();
var leadsource = $("input#leadsource").val();
var country = $("input#country").val();
var phone = $("input#phone").val();
var oid = $("input#oid").val();
var retURL = $("input#retURL").val();
var crazy
= $("input#00N40000001mCkP").val();
var dataString = '&email=' + email + '&phone=' + phone + '&oid=' + oid + '&retURL=' + retURL + '&leadsource=' + leadsource + '&country=' + country; //alert (dataString);return false; $.ajax({
type: "POST",
url: "MYURL.php?first_name="
+ fname + "&last_name=" + lname,
data: dataString,
success: function(response) { $(myform).submit(); }
});
return false; });
}); </script>
Essentially whats happening is, the form data is initially sent to a different url through an AJAX submit prior to completing the real form. On success of the ajax push - the form is submitted, and then the form is validated.
I need the form validation to have right when #submitbutton is clicked though - prior to the ajax request. Any ideas?
That code should work just fine. If you want to add it to a onclick= property on the element (I wouldn't, but if you insist), you can use this syntax to reference the form:
<input type="submit" onclick="return validateFormOnSubmit(this.parentNode)" />
And you'd have to do an e.preventDefault() and return false (maybe just one?) from the validateFormOnSubmit() function.
Take a look at preventDefault . Also, you can call validateFormOnSubmit in the anon function above and return false if it validation doesn't pass.
you should put some " " around your form tags attributes, and give it an id!
just call your validate function as the first line in your button click handler :)
$("#submitbutton").click(function(e) {
if( validateFormOnSubmit($('#myform'))){
//do all the posting stuff
}
else{
e.preventDefault();
return false;
}
Related
For a project, I am trying to make a HTML form that when a movie is searched it can access the Rotten Tomatoes API and queries the user's submitted text and returns with the movie.
The javascript* code from Rotten Tomatoes was provided
<script>
var apikey = "[apikey]";
var baseUrl = "http://api.rottentomatoes.com/api/public/v1.0";
// construct the uri with our apikey
var moviesSearchUrl = baseUrl + '/movies.json?apikey=' + apikey;
var query = "Gone With The Wind";
$(document).ready(function() {
// send off the query
$.ajax({
url: moviesSearchUrl + '&q=' + encodeURI(query),
dataType: "jsonp",
success: searchCallback
});
});
// callback for when we get back the results
function searchCallback(data) {
$(document.body).append('Found ' + data.total + ' results for ' + query);
var movies = data.movies;
$.each(movies, function(index, movie) {
$(document.body).append('<h1>' + movie.title + '</h1>');
$(document.body).append('<img src="' + movie.posters.thumbnail + '" />');
});
}
</script>
I have an API key, my question is how would I be able to create a form that would change out the value for var query = "Gone With The Wind"; as the user submitted an input search with a HTML form such as this:
<input id="search">
<input type="submit" value="Submit">
Also would this be able to lead to another HTML page once searched?
complete rewrite ...
You should wrap the supplied (and modified) code in a function which you can then call through an event binding, like a submit event on your input form.
Below you will find a complete and working example of how you could do it. I replaced the given URL with a publicly available one from spotify. As a consequence I had to modify the callback function a little bit and also the dataType paramater in the $.ajax() argument object was changed to 'json' (instead of originally: 'jsonp').
At the end of the lookformovie() function you will find return false;. This prevents the submit event from actually happening, so the user stays on the same page.
function lookformovie(ev){ // ev is supplied by the triggered event
console.log('go, look!');
// the following WOULD be important, if this function was triggered
// by a click on a form element and you wanted to avoid the event to
// "bubble up" to higher element layers like the form itself.
// In this particular example it is superfluous
ev.stopPropagation();
var apikey = "[apikey]";
var baseUrl = "http://api.rottentomatoes.com/api/public/v1.0";
// construct the uri with our apikey
var moviesSearchUrl = baseUrl + '/movies.json?apikey=' + apikey;
// --- start of spotify-fix ---
moviesSearchUrl="https://api.spotify.com/v1/search?type=track";
// --- end of spotify-fix -----
// the following gets the contents of your changed input field:
var query=$('#search').val();
$.ajax({
url: moviesSearchUrl + '&q=' + encodeURI(query),
dataType: "json", // spotify-fix, was: "jsonp"
success: searchCallback
});
return false; // this prevents the submit event from leaving or reloading the page!
}
// modified callback (spotify-fix!!):
function searchCallback(data){
console.log('callback here');
$('#out').html(data.tracks.items.map(
function(t){ return t.name;}).join('<br>\n'));
}
// original movie callback for Rotten Tomatoes:
function searchCallback_inactive(data) {var str='';
str+='Found ' + data.total + ' results.';
var movies = data.movies;
$.each(movies, function(index, movie) {
str+='<h1>' + movie.title + '</h1>';
str+='<img src="' + movie.posters.thumbnail + '" />';
});
$('#out').html(str);
}
$(function(){
$('form').on('submit',lookformovie);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" id="search" value="james brown">
<input type="submit" value="get tracks">
</form>
<div id="out"></div>
You might have noticed that I placed several console.log() statements at various places into the code. This helped me during debugging to see which part of the functionality actually worked, and where something got stuck. To see the output you need to have your developer console opened of course.
You can construct form, with input element named "q", then handle form submit event.
<form action="http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=API_KEY" method="get">
<input id="search" name="q">
<input type="submit" value="Submit">
</form>
So I got this js code for a form submission, and everything is working fine, however, I don't know where and what to write in the code so the email gets a validation check. What and where should I write to validation check the email?
$(document).ready(function() {
$("#submit").click(function() {
var name = $("#fullname2").val();
var email = $("#fullemail2").val();
var state = $("#selectstate").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'FullName=' + name + '&email=' + email + '&SovereignState=' + state;
if (name == '' || email == '' || state == '') {
$('#required_fields').show();
} else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "demo.php",
data: dataString,
cache: false,
success: function(phpSays) {
if (phpSays == "OK") {
$('#email_error').show();
$('#required_fields').hide();
} else {
$('#sinatra2').hide();
$('#thanks').fadeIn(1000);
$('#spreading_message').delay(1800).fadeIn(1500);
$('#by_social').delay(3000).fadeIn(1500);
$('#email_error').hide();
$('#required_fields').hide();
}
}
});
}
return false;
});
});
Looking at your code I can suggest the below approach to say where you can do email validation
if(name==''||email==''||state=='')
{
$('#required_fields').show();
}//this is fine
else if(!valid(email))//call a function which validates email and returns true or false
{
//Display the message either with same $('#required_fields') changing the text or
//Add one more field to display invalid email message
}
else
{
//Your ajax call here
}
Now your valid function will look like
function valid(email)
{
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return emailReg.test(email); //this will either return true or false based on validation
}
$(document).ready(function(){
$("#submit").click(function(){
var name = $("#fullname2").val();
var email = $("#fullemail2").val();
var state = $("#selectstate").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'FullName='+ name + '&email='+ email + '&SovereignState='+ state;
if(name==''||email==''||state=='')
{
$('#required_fields').show();
}
else
{
// AJAX Code To Submit Form.
// <-- email address should be here
...........
}
return false;
});
});
Better place to validate is where you have 'fullemail2' input field. Even in the javascript file, you should do it before create the dataString. In that way you could validate before submit.
I'm trying to submit a form using Ajax , but it doesn't work here is my Ajax :
$(document).ready(function(){
$("#submit").click(function(event){
var ad1 = $("#ad1").val();
var ad2 = $("ad2").val();
var city = $("city").val();
var state = $("state").val();
var zip = $("zip").val();
var country = $("country").val();
var mm = $("mm").val();
var dd = $("dd").val();
var yy = $("yy").val();
var lname = $("lname").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'name1='+ name + '&ad11='+ ad1 + '&ad21='+ ad2 + '&city1='+ city + '&state1='+ state + '&zip1='+ zip + '&country1='+ country + '&mm1='+ mm + '&yy1='+ yy + '&dd1='+ dd + '&lname1=';
if(name=='')
{
alert("");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "action.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
and it's not giving any result just giving data in header
the result is like :
I copied the javascript to the form page it's now working ,but the ajax is returning a blank alert while it should be "Form Submitted Succesfully"
I guess that it's an error of inclusion of the file , but i'm using the right directories.
here is action.php :
<?php
$con = mysqli_connect("server","user","pass","db");
$name=$_POST['name1'];
$ad1=$_POST['ad11'];
$ad2=$_POST['ad21'];
$city=$_POST['city1'];
$state=$_POST['state1'];
$zip=$_POST['zip1'];
$country=$_POST['country1'];
$mm=$_POST['mm1'];
$dd=$_POST['dd1'];
$yy=$_POST['yy1'];
$dob=$dd."/".$mm."/".$yy;
$mm=$_POST['mm1'];
$name=$_POST['name1'];
$lname=$_POST['lname1'];
$r2=rand(10000,90000);
$query = mysqli_query($con,"insert into users values('$r2','$name','$lname','$ad1','$ad2','$city','$state','$zip','$country','$dob')");
mysqli_close($con);
echo "Form Submitted Succesfully";
?>
This name variable is not have defined in ajax file var dataString = 'name1='+ name + so name would be an empty string
=> if(name=='')
{
alert("");
} executed. Please add string into alert and check again :)
I have a form with JS functions for checking empty fields and submit form without refreshing all page, I'm looking for a way to integrate email check function into what I'm having now:
$(function() {
$('.error').hide();
$('input.text-input').css({backgroundColor:"#EBEBEB"});
$('input.text-input').focus(function(){
$(this).css({backgroundColor:"#EBEBEB"});
});
$('input.text-input').blur(function(){
$(this).css({backgroundColor:"#EBEBEB"});
});
$(".button").click(function() {
// validate and process form
// first hide any error messages
$('.error').hide();
}
var name = $("input#name").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email == "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
var phone = $("textarea#phone").val();
if (phone == "") {
$("label#phone_error").show();
$("textarea#phone").focus();
return false;
}
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "process.php",
data: dataString,
success: function() {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Email sent</h2>")
.hide()
.fadeIn(1000, function() {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
}
});
return false;
});
});
runOnLoad(function(){
$("input#name").select().focus();
});
Thanks for help.
To check an email, you can use:
var emailReg = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i
function isEmail(email) {
return emailReg.test(email);
}
//call isEmail wherever you need it
If I may comment further on your code, I would recommend you cache your selectors and reuse them:
var input = $('input.text-input');
input.css({backgroundColor:"#EBEBEB"}).focus(function() //... and so on
Also, if your DOM is correctly structured, you do not have to call your ids with input selectors, it just slows down your implementation because its iterating over every input in the DOM than just getting it directly. That means:
$("label#phone_error") // don't do this
$("#phone_error") // do this
Also, you can use a data object to pass to jquery, so rather than
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone;
Do this:
$.ajax(yoururl, {data:
{
name: name,
email: email,
phone: phone
}, // and so on
I am trying to do this:
Have the user click some action. The action checks whether the user is logged in or not. If not, open a login dialog box, and if the user logs in correctly, update the original page.
I got almost all this working except the part of after successful login. The problem is that the code seems to not have access to the item_id which I was trying to update. Instead, when I try to set the item id (problem_id in this case) in the login form of the popup box, the id is the number of the id that is the last one on the page, and not the one that was clicked.
Here is what I am trying to do in the jQuery:
<script type="text/javascript">
$(document).ready(function()
{
var $dialog = $('#loginpopup')
.dialog({
autoOpen: false,
title: 'Login Dialog'
});
var $problemId = $('#theProblemId', '#loginpopup');
$("#newprofile").click(function ()
{
$("#login_div").hide();
$("#newprofileform").show();
});
// Called right away after someone clicks on the vote up link
$('.vote_up').click(function()
{
var problem_id = $(this).attr("data-problem_id");
//alert ("In vote up click, problem_id: " + problem_id );
voteUp(problem_id);
//Return false to prevent page navigation
return false;
});
var voteUp = function(problem_id)
{
alert ("In vote up function, problem_id: " + problem_id );
var dataString = 'problem_id=' + problem_id + '&vote=+';
$.ajax({
type: "POST",
url: "/problems/vote.php",
dataType: "json",
data: dataString,
success: function(data)
{
alert ("vote success, data: " + data);
// ? :)
},
error : function(data)
{
alert ("vote error");
errorMessage = data.responseText;
if ( errorMessage == "not_logged_in" )
{
//set the current problem id to the one within the dialog
$problemId.val(problem_id);
// Try to create the popup that asks user to log in.
$dialog.dialog('open');
alert ("after dialog was open");
// prevent the default action, e.g., following a link
return false;
}
else
{
alert ("not");
}
//alert(JSON.stringify(data));
} // Closing error case
}); // Closing AJAX call.
};
$('.vote_down').click(function()
{
alert("down");
problem_id = $(this).attr("data-problem_id");
var dataString = 'problem_id='+ problem_id + '&vote=-';
//Return false to prevent page navigation
return false;
});
$('#loginButton', '#loginpopup').click(function()
{
alert("in login button fnction");
$.ajax({
url:'url to do the login',
success:function() {
//now call cote up
voteUp($problemId.val());
}
});
});
});
</script>
and here is the login form:
<div id="login_div">
<form id="login_form" method="post" action="">
<p>
<label for="name"><span>Your Email:</span></label> <input type="text" name="email" id="email" />
</p>
<p>
<label for="name"><span>Your Password:</span></label> <input type="password" name="user_pass" id="user_pass">
</p>
<input type="hidden" id="problem_id" name="problem_id" value="<?php echo $problem_id; ?>" />
<span class="no_such_user" style="color: red; display:none">The login and password does not match our records.</span>
<span class="password_error" style="color: red; display:none">The password much be 5 characters or more.</span>
<span class="login_success" style="color: green; display:none">You successfully logged in.</span>
<p>
<input type="submit" value="Log In" />
</p>
</form>
</div>
But the problem_id which is being set in this form isn't the one being clicked on, even though I am trying to save it in my jQuery.
Also, here is the code that gets executed for login:
$(function()
{
$("#login_div input[type=submit]").click(function()
{
var email = $("#email").val();
var password = $("#user_pass").val();
//alert("Email: " + email);
//alert("password: " + password);
var dataString = 'email='+ email + '&password=' + password;
if( !email )
{
alert ("1");
$('.login_success_email_empty').fadeOut(200).hide();
$('.login_error_email_empty').fadeOut(200).show();
}
else
if( !password || password.length < 5)
{alert ("2");
$('.password_success').fadeOut(200).hide();
$('.password_error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "../auth/login_ajax.php",
dataType: "json",
data: dataString,
success: function(json)
{
$('.password_error').fadeOut(200).hide();
$('.no_such_user').fadeOut(200).hide();
$('.login_success_email_empty').fadeOut(200).hide();
$('.login_success').fadeIn(200).show();
// Closing the dialog bosx
$('#loginpopup').dialog('close');
// Swapping out the header div
$('#header_logged_out').hide();
$('#header_logged_in').show();
// Now also need to retrieve the problem_id
problem_id = $("#problem_id").val();
//$problemId = $('#theProblemId', '#loginpopup').val();
var $problemId = $('#theProblemId', '#loginpopup');
alert ("After login, problem_id: " + problem_id + " and problemId was: " + $problemId);
},
error : function(json)
{
alert ("error");
// Output the result.
errorMessage = json.responseText;
alert ("ErrorMessage: " + errorMessage );
if ( errorMessage == 'no_such_user' )
{
$('.no_such_user').fadeOut(200).hide();
$('.no_such_user').fadeOut(200).show();
}
}
});
}
return false;
});
});
and I am just not sure how to get that problem_id which was set in the original jQuery code to be recognized in the jQuery code that executes after login.
Because what I really need to do is update that particular problem depending on whether the user was logged in.
And how do I know in the original code that processes the votes, whether the login in the dialog box was successful or not?
By the way, I am working on this page: http://www.problemio.com
It seems that you might be better served using the jquery forms /ajax submit plugin:
http://be.twixt.us/jquery/formSubmission.php
$('loginDiv > form').submit(function() {
var options = {
url = "../auth/login_ajax.php",
[...]
};
$(this).ajaxSubmit(options);
return false; //this line is required to make sure that the page doesn't get redirection to /auth/login_ajax.php
});
This way it won't reload any of the javascript, preserving any variables that have already been set. You can therefore set the problem ID before the login, and then do stuff with it afterward.