AJAX email form validation in AJAX loaded div? - php

I've created a pretty straight-forward site which loads all of its content via jquery .load() functions when you click the navigation links, and it works great. What I want now is to load in an email contact form with AJAX-style validation that alert the user about invalid input fields prior to running the php submission.
In other words, user clicks navigation link for "contact me" and a form is loaded into the content div. If the user enters an invalid name or email and hits submit, appropriate error messages will appear next to those input fields. I don't really care what happens after form goes through, whether it be a popup window or redirect page.
I've been trying to figure this out for weeks and I'm ready to give up. The form loads fine, but I can't figure out the basic construct for getting an AJAX loaded form to respond to the user without reloading the page and clearing their fields. I even got the php form submission part working exactly how I want, but getting client-side scripts to function with server-side php functions just seems arduous.
Is this even possible? How should I go about this? What are the basic concepts and tools for something like this?

What is your problem? Why can't you use a simple jQuery validator plugin?
Some examples:
Plugins/Validation/validate
jQuery plugin: Validation
Plugins/Validation

I got my form to work using the jquery validation plugin! Thanks to Praveen for suggesting it. It's a great tool.
The underlying issue was that I really wasn't wrapping my head around .load(). Once I utilized the .load() callback function, the validation ran fine. I created an external javascript file called contact.js which contains the validation plugin rules and submitHandler nested within contactPageScript() function. I called contactPageScript() with the .load() callback and voila:
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script type="text/javascript" src="js/contact.js"></script>
<script>
$(document).ready(function(){
$("div#menu ul li a").click(function() {
var whichPage = $(this).attr('href');
$('div#page_content').load(($(this).attr('href') + ' #contentB'), function(){
if (whichPage == 'contact.html') {
contactPageScript();
}}
);
});
});
</script>
</head>
The validation script of course also worked fine nested within the callback function rather than as an external .js, but it was too lengthy for my tastes. And there were some small details to be worked out regarding the validation rules. Here's the chunk of validation code I used just for reference:
$(document).ready(function() {
$('#mailform').validate( {
rules: {
fullname: {
required: true,
minlength:2
},
email: {
required: true,
email: true
}
},
messages: {
fullname: 'Please enter a valid name',
email: 'Please enter a valid email address'
},
submitHandler: function(form) {
$.post('php/submitForm.php', $('#mailform').serialize(), function() { DO STUFF });
}
});
});
At first I couldn't get the plugin script to work during debugging. Beware of extra commas after the rules! And also be advised that some copypasta tutorials contain hidden invalid characters within them! You'd never know! I had to rewrite the whole code by hand to get it to validate!
I later added nested if/else statements within the callback to call functions for all the other pages on the site which required jquery/javascript. At first I tried using a switch instead of nested if/elses, but it was not ideal. It helps to read the manual!
Cheers.

Related

Validating forms returned by ajax

If i have a page which has an ajax link and that the code returns a that form needs validating, where do i put the validation code please. Say my form had this validation using the jquery validation plugin
jQuery(document).ready(function() {
$("#basicForm").validate({
showErrors: function(errorMap, errorList) {
// Clean up any tooltips for valid elements
$.each(this.validElements(), function(index, element) {
var $element = $(element);
$element.data("title", "") // Clear the title - there is no error associated anymore
.removeClass("error")
.tooltip("destroy");
});
// Create new tooltips for invalid elements
$.each(errorList, function(index, error) {
var $element = $(error.element);
$element.tooltip("destroy") // Destroy any pre-existing tooltip so we can repopulate with new tooltip content
.data("title", error.message)
.addClass("error")
.tooltip(); // Create a new tooltip based on the error messsage we just set in the title
});
},
submitHandler: function(form) {
var myselect = $('select[name=ddCustomers]');
//alert(myselect.val());
window.location.replace("customer.php?customer_id=" + myselect.val());
}
});
$("#basicForm").removeAttr("novalidate");
});
where do i put it as the document.ready where i would normally out this code has already been called
I hope this makes sense
Could i have it on the page in the initial page load ready for when the form is returned
I've read i coud have the validation in the document.on function but dont really understand. Would i post something like this back with my ajax response for the validation
$(document.body).on('click', '#basicForm', function(){
$("#basicForm").validate({
submitHandler: function() {
// do whatever you need here
}
});
});
Thanks for your help. Its confusing and I cant find a decent example on google
EDIT
I know how to write the validation code for the dynamically generated forms so thanks for those answers but I am alright on that. The question is WHERE that code should i put it in the ajax return?
Perhaps i have a misconception but i am using jquery validate module (base assistance( and i have only ever seen the `form validate method called in doc. ready on the first page - never an ajax postback
document.ready
Options
1) Hard coded in page already writing for when form injected by ajax? not dynamic enough - the injected form is created dynamically so the validation may need to
be
2) Add validation code to
document.on
when i do ajax postback for the new form? Is this even possible? Im not a client side programmer.
I am bemused that such a common scenario doesnt have a design pattern. Though i have read postng back forms via ajax is bad practice as it can confuse the browser and now what ajax whs written for so perhaps that why i cant find a solution
thanks
I've coded and developed many web apps just with jquery, php being the server side script. The way I formed was to have the jquery code and html on the same page since jquery needs to check the html element and respond with the proper error message and sanitize all the data fields before I submit to the "form-process.php" for an example if that was the name of your server side script.
Have:
$(document.body).on('click', '#basicForm', function(){
$("#basicForm").validate({
submitHandler: function() {
// do whatever you need here
}
});
});
code as the same page as say: create-username.html or create-username.php page
html elements. Some prefer to have jquery on the bottom, depends on how you have your
page structured, but I like to put the js on top from old practices although sometimes it doesn't apply to jquery.
include your tooltips code in the same block. I don't like to have jquery all over the place; incase of errors or if you need to modify in future reference it wouldn't be hard to pinpoint to edit, add or fix code. I hope this helps.
You need to initialize the validation plugin first and set up the rules you want. Then when a user submits the form, prevent the default form submission behavior and if all is validated successfully based on the criteria of the rules you set, you manually submit the form to the server using ajax.
$('#basicForm').validate({ // initialize the plugin
rules: {
field1: {
required: true,
email: true
},
field2: {
required: true,
minlength: 5
}
}
});
$('document').on('submit', '#basicForm', function(e){
if($(this).valid()){
//client side is valid, make ajax call
}
e.preventDefault();
});

Submit a Form without Leaving Page

I am working on a survey that will go at the bottom of a FAQ page. My problem is that everytime a form is submitted, it sends you to a different page. I was wondering - is there a way to submit the form and have a little message that replaces the survey that says "Thanks for your feedback" instead of sending the user to another page or refreshing the page?
So far, I have a file that contains the HTML form, CSS, and jQuery and another file that contains the PHP connection to database and insertion of data to the database.
I would appreciate an explanation that is dumbed-down and an example would help since I am relatively new to programming.
An important note: My jQuery is set up to automatically submit if a user answers very helpful/extremely helpful. If not, two more questions appear below with a submit button at the bottom.
More specifically it looks like this:
$(document).ready(function() {
$('.rating').click(function() {
$('.rating').removeClass('selected');
ratingClick(this);
});
});
function ratingClick(that) {
console.log(that.id);
if (that.id == 'rating4' || that.id == 'rating5') {
//$('#questions').fadeOut('slow');
//$('#thankYou').fadeIn('slow');
$('#questions').submit();
} else {
$('#getMore').fadeIn();
$(that).toggleClass('selected');
}
}
$(document).ready(function() {
$('#submit').click(function(){
//$('#questions').fadeOut('slow');
//$('#thankYou').fadeIn('slow');
});
});
What you want is the jquery post function: http://api.jquery.com/jQuery.post/
Make sure your data is JSON.
$("#formdiv").click(function(){
$.post("somepage",{ yourformdata} );
$("#formdiv").replacewith("Thanks for filling out the form!");
});
You can use the replaceWith function to replace the desired content with the thankyou message.
Alex,
from the code you supply, the reason for leaving the page is due to the fact that you don't preventDefault() on the click event. Your page will always reload after that submit unless you take abortive action. No guarantees, but try a quick refactor to:
$(document).ready(function() {
$('#submit').click(function(e){
e.preventDefault();
//$('#questions').fadeOut('slow');
//$('#thankYou').fadeIn('slow');
});
});
This should get you a stage closer. You then just have the ajax logic to define, which should come good with a quick search to match your needs.

jQuery scrollbar plugin not working on Ajax loaded content

The problem is this:
I have a simple, two fields form which I submit with Ajax.
Upon completion I reload two div's to reflect the changes.
Everything is working perfect except a jQuery plugin. It's a simple plugin that can be called with simple
function(){
$('.myDiv').scrollbars();
}
It's simple and easy to use, but it doesn't work on Ajax loaded content. Here is the code I use to post form and reload div's:
$(function() {
$('#fotocoment').on('submit', function(e) {
$.post('submitfotocoment.php', $(this).serialize(), function (data) {
$(".coment").load("fotocomajax.php");
}).error(function() {
});
e.preventDefault();
});
});
I've tried creating a function and calling it in Ajax succes:, but no luck. Can anyone show me how to make it work ? How can that simple plugin can be reloaded or reinitialized or, maybe, refreshed. I've studied a lot of jQuery's functions, including ajaxStop, ajaxComplete ... nothing seems to be working or I'm doing something wrong here.
If you're loading elements dynamically after DOM Document is already loaded (like through AJAX in your case) simple binding .scrollbars() to element won't work, even in $(document).ready() - you need to use "live" event(s) - that way jQuery will "catch" dynamically added content:
$(selector).live(events, data, handler); // jQuery 1.3+
$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+
$(document).on(events, selector, data, handler); // jQuery 1.7+
Source: jQuery Site
Even if I am totally against using such plugins, which tries to replicate your browser's components, I'll try to give some hints.
I suppose you are using this scrollbars plugin. In this case you may want to reinitialize the scrollbars element, and there are many ways to do this. You could create the element again like in the following example
<div class="holder">
<div class="scrollme">
<img src="http://placekitten.com/g/400/300" />
</div>
</div>
.....
$('.scrollme').scrollbars();
...
fakedata = "<div class='scrollme'>Fake response from your server<br /><img src='http://placekitten.com/g/500/300' /></div>";
$.post('/echo/html/', function(response){
$('.holder').html(fakedata);
$('.scrollme').scrollbars();
});
If you want to update the contents of an already initialized widget instead, then things gets more complicated. Once your plugin initialize, it moves the content in some custom wrappers in order to do its 'magic', so make sure you update the correct element, then trigger the resize event on window, pray and hopefully your widget gets re-evaluated.
If it doesn't help, then try to come up with some more details about your HTML structure.
I want to thank everyone of you who took their time to answer me with this problem I have. However, the answer came to me after 4 days of struggle and "inventions" :), and it's not a JS or Jquery solution, but a simple logic in the file.
Originally, I call my functions and plugins at the beginning of the document in "head" tag, like any other programmer out here (there are exceptions also ).
Then my visitors open my blog read it and they want to post comments. But there are a lot of comments, and I don't want to scroll the entire page, or use the default scroll bars, simply because they're ugly and we don't have cross browser support to style that, just yet.
So I .post() the form with the comment, and simply reload the containing all of them. Naturally .scrollbars() plugin doesn't work. Here come the solution.
If I put this :
<script>$('.showcoment').scrollbars();</script>
in the beginning of my loaded document (with load() ), will not work, because is not HTML and it's getting removed automatically. BUT !!! If i do this:
<div><script>$('.showcoment').scrollbars();</script></div>
at the same beginning of loaded document, MAGIC .... it works. The logic that got me there I found it in the basics of javascript. If your script is inside an HTML element, it will be parsed without any problem.
Thank you all again, and I hope my experience will help others.
If I understand you correctly, try this:
var scrollelement = $('.myDiv').scrollbars();
var api = scrollelement.data('jsp');
$(function () {
$('#fotocoment').on('submit', function (e) {
$.post('submitfotocoment.php', $(this).serialize(), function (data) {
$(".coment").load("fotocomajax.php");
api.reinitialise();
}).error(function () {
});
e.preventDefault();
});
});
reinitialise - standart api function, updates scrolbars.

Jquery(ajax) PHP search results not displaying in search_results div under form

For a website I'm making for school, I'm trying my hand at using Jquery extensively for the first time, and even though I managed quite a bit so far, I'm stuck at two (most likely related) problems.
I'm aware that the upcoming case is somewhat long, but I feel it's necessary to submit all relevant code for everyone reading this to get a good image of what is happening.
Basically, the website is one index.html file, with the CSS thrown in, a few buttons, and one div with the ID content. I use this code to make this work:
<script type="text/javascript">
if ($('#content').innerHTML == " "){
$(document).ready(function(){
$('#content').load('main_text.html');
});
}
</script>
<script type="text/javascript">
function loadContent(elementSelector, sourceURL) {
$(""+elementSelector+"").load(""+sourceURL+"");
}
</script>
Then there is one content page, named search.html, which only contains a form that submits a search string to a search.php page (through ajax) that should then place the search results immediately back into a div called search_results in that same search.html file. The jquery that I use for this:
<script type='text/javascript'>
$(document).ready(function(){
$("#search_results").slideUp();
$("#search_button").click(function(e){
e.preventDefault();
ajax_search();
});
$("#search_term").keyup(function(e){
e.preventDefault();
ajax_search();
});
});
function ajax_search(){
$("#search_results").show();
var search_val=$("#search_term").val();
$.post("Functions/search.php", {search_term : search_val}, function(data){
if (data.length>0){
$("#search_results").html(data);
}
})
}
</script>
The issue that I'm having is as followed:
Before I had the first line of code: if ($('#content').innerHTML == " "){; implemented, I would open the site, main_text.html would nicely be loaded in, I could navigate to other subpages fine. But typing in something in the form field in search.html did not display any results (just typing should already trigger the function). When I hit the search button on this form, instead of seeing query results, the main_text.html file load again in the #content div. This made me assume that perhaps, somehow, that the code:
$(document).ready(function(){
$('#content').load('main_text.html');
});
was being called again unwanted. Hency why I implemented that check for whether innerHTML existed.
However, now, when I first load the page, the #content div does not load any initial content at all. (The section on the webpage just becomes black, like my page background) I have to click any button to get some content loaded again in my main content div. Also, when I now go back to the search.html, the typing anything to get results, like previously, still does not work. If I now hit the search button, I get the initial result again of what I'd see when I just opened the page: a blacked out #content div.
So somehow, the biggest issue is in the fact that the jquery to get results from my PHP do not seem to work. My problem with the content.innerhtml check might well be obsolete if the issue with the searchresults not displaying in the #search_result div on the search.html is fixed.
Anyone have any idea's what I could do to fix this. Or otherwise, what other approaches I could take for the kind of website I'm making. Since I'm trying to learn jquery here, better approaches are always appreciated, I'd rather learn myself doing this the right way and all. :)
Thanks for your time.
Few things to note here:
<script type="text/javascript">
if ($('#content').innerHTML == " "){
$(document).ready(function(){
$('#content').load('main_text.html');
});
}
</script>
<script type="text/javascript">
function loadContent(elementSelector, sourceURL) {
$(""+elementSelector+"").load(""+sourceURL+"");
}
</script>
In the above, you are testing to see if there is a space in the innerHTML of the element with an id of content.
jQuery uses .html() or .text() to make comparisons against the data being held within a container, so if you want to maintain using jQuery principles, change this line. Going along the same thought process, you are preparing an IF statement on an element before the document is actually ready and loaded.
You should move the document.ready function to the outside of the if statement. This will allow you to ensure that the element is available at DOM, and you can indeed perform checks against this element.
<script type="text/javascript">
$(document).ready(function(){
if ($('#content').html("")){
$('#content').load('main_text.html');
}
});
</script>
Also, while being readily provided and fully functional, I would recommend starting off using $.ajax instead of $.get / $.post. I have personal preferences as to why I think this, but I won't go into that, it's just that, personal.
$.ajax({
url: "Functions/search.php",
type: 'POST',
data: "search_term="+search_val,
success: function(data){
if (data.length>0){
$("#search_results").html(data);
}
});
Lastly, you should be using the GET method and NOT the POST method. Based on REST/SOAP practices, you are retrieving data from the server, and not posting data to the server. It's best practice to follow those two simple ideas. This isn't because web servers will have a difficult time interpreting the data; but, instead, it's to prepare you for working on larger scale application deployment, or future team-environments. This way everyone on the team has an expectation as to what method will be used for what purpose.
Anyway, long story short, you also leave semicolons off of the end of your closing }) brackets. While this is not an issue, nor will it cause flaws in your development, coding is all about uniformity. You've used the closing ; everywhere else, so try and maintain that same uniform design.
Best of luck.

css popup window incorporating session variables or php file

I have recently installed Simple Mailing List 2 (currently in beta) and I have got everything to work so far. The main thing that was left for me to do was to make a custom php page which the signup form redirects to once submitted. The content that the page shows is based on what the user enters in the email field and returns one of three results:
an error message if the email syntax is incorrect.
a custom message if the user has subscribed telling them to check their email.
a custom message if the user has chosen to unsubscribe.
That's the background out of the way. Now what I intend to do is show a popup window that includes the contents of the redirected php page (ie. one of the three results) instead of going to a new page. Is it possible to do this a css popup box so I don't have to open up a new window?
Thankyou
Adam
You can use JavaScript to send an ajax request to the PHP page that will do the calculations, the result will then be sent to your "window" content and then you show the window to the user
You're mixing metaphors. CSS is just a presentational technology that you use to determine the style of something. There is no such thing as a "css popup box".
What you want to do is have an HTML element (likely a div) that contains the information you intend to show, initially set to not be visible (you use CSS for this with the display:none; style). What you're describing is essentially an AJAX interaction that uses Javascript to parse the contents of the form, send data to the server to be evaluated, and return a message to be displayed (without triggering a postback/going to a new page). That Javascript would also handle the CSS part of setting the display of the HTML element to true.
This is a fairly common scenario, so you should be able to find snippets online.
...but here's a super dumb example
<html>
<head>
<title>AJAX Test</title>
</head>
<body>
<form action="#">
<input type="text" id="enterStuff" />
</form>
<div id="response" style="display:none;">
<p id="message">Put stuff in me</p>
</div>
<script type="text/javascript">
jQuery(document).ready(function(){
registerEventListeners();
});
function registerEventListeners(){
jQuery("#enterStuff").change(getData);
}
function getData(){
jQuery.ajax({
type : 'POST',
data : {
stuff : jQuery("#enterStuff").val(),
},
url : "http://localhost/myprocessor.php",
success : showCool,
complete : updateDisplay
});
}
function showCool(data, textStatus, jqXHR){
var selector = jQuery("#message");
selector.val(data)
}
function updateDisplay() {
jQuery("#response").show();
}
</script>
</body>
</html>
Then your myProcessor.php would have to read the value of the variable, do some logic, and echo a response.
You could use an <iframe> as an in-document 'pop-up', you just set the target of the form to the name/id of the iframe. (You can use some JavaScript to only show the iframe once the form is submitted.)

Categories