Submit a form with ajax

HI guys, I have a form that I need submit with ajax and then hook up to some PHP script that’s doing the validation and will email the content to an email address. So let’s focus on the ajax part first (I’ve done ajax before but never submitted forms with it admittedly). Here is the full code as it is now with no ajax submission (bear in mind that the php email code will change because I will use PHPmailer):
[php]

<?php //create variables for validation $titleError = ""; $firstNameError = ""; $lastNameError = ""; $emailAddressError = ""; $messageError = ""; $websiteError = ""; $titleError = ""; $title = ""; $firstName = ""; $lastName = ""; $emailAddress = ""; $message = ""; $website = ""; //mail variables $successMsg = ""; $to = "[email protected]"; $subject = "New request"; $currentTitle = $_POST["title"]; $currentMessage = "Title: " . $_POST["title"] . "\r\n"; $currentMessage .= "First Name: " . $_POST["firstName"] . "\r\n"; $currentMessage .= "Last Name: " . $_POST["lastName"] . "\r\n"; $currentMessage .= "Email address: " . $_POST["emailAddress"] . "\r\n"; $currentMessage .= "Website: " . $_POST["website"] . "\r\n"; $currentMessage .= "Message: " . $_POST["message"] . "\r\n"; //keep track of how many errors $errors = 0; $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; //mail($to,$subject,$currentMessage,$headers); if($_SERVER["REQUEST_METHOD"] == "POST"){//has the form been submitted? //validate title if($_POST["title"] == "0"){ $titleError = "Select a title"; $errors = 1; } else{ $title = $_POST["title"]; $errors = 0; } /* if( 0 != $_POST['title'] ) { $title = $_POST['title']; } else { $titleError = "required"; } */ //validate firstName if (empty($_POST["firstName"])){//if empty $firstNameError = "First name is required"; $errors = 1; } else{ $firstName = test_input($_POST["firstName"]); // check if firstName only contains letters and whitespace if(!preg_match("/^[a-zA-Z ]*$/",$firstName)){ $firstNameError = "Only letters and white space allowed"; $errors = 1; } else{ $errors = 0; } } if (empty($_POST["lastName"])){//if empty $lastNameError = "Last name is required"; $errors = 1; } else{ $lastName = test_input($_POST["lastName"]); // check if lastName only contains letters and whitespace if(!preg_match("/^[a-zA-Z ]*$/",$lastNameError)){ $lastNameError = "Only letters and white space allowed"; $errors = 1; } else{ $errors = 0; } } if(empty($_POST["emailAddress"])){ $emailAddressError = "Email is required"; $errors = 1; } else{ $emailAddress = test_input($_POST["emailAddress"]); // check if e-mail address is well-formed if(!filter_var($emailAddress, FILTER_VALIDATE_EMAIL)){ $emailAddressError = "Invalid email format"; $errors = 1; } else{ $errors = 0; } } if(empty($_POST["website"])){ $website = ""; $errors = 0; } else{ $website = test_input($_POST["website"]); // check if URL address syntax is valid (this regular expression also allows dashes in the URL) if(!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) { $websiteError = "Invalid URL"; $errors = 1; } else{ $errors = 0; } } if(empty($_POST["message"])){ $messageError = "Message required"; $errors = 1; } else{ $message = test_input($_POST["message"]); $errors = 0; } if($errors == 0){ mail($to,$subject,$currentMessage,$headers); reset_fields($title, $firstName, $lastName, $emailAddress, $message, $website); $successMsg = "

Thank you. The form has been submitted.

"; } /* else{ return false; } */ } function test_input($data){ $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } function reset_fields(&$title, &$firstName, &$lastName, &$emailAddress, &$message, &$website){ $title = null; $firstName = null; $lastName = null; $emailAddress = null; $message = null; $website = null; } ?>[/php]

[code]


Contact us


We’re always excited to work on a new project, so give us a shout!


Fill in the form or drop us a line at [email protected]



<?php echo $successMsg;?>

<form method=“post” action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

Title*


<option <?php if($title == 0) echo 'selected'; ?> value=“0”>Please select
<option <?php if($title == 1) echo 'selected' ?> value=“1”>Mr
<option <?php if($title == 2) echo 'selected' ?> value=“2”>Mrs
<option <?php if($title == 3) echo 'selected' ?> value=“3”>Ms
<option <?php if($title == 4) echo 'selected' ?> value=“4”>Sir

<?php echo $titleError;?>



First name*


<?php echo $firstNameError;?>



Last name*


<?php echo $lastNameError;?>



Email address*


<?php echo $emailAddressError;?>



Website


<?php echo $websiteError;?>



Enter your message*

<?php echo $message;?>
<?php echo $messageError;?>









		</form>
	</div>
</div>

[/code]
The above sits inside index.php.
OK so, presumably the first thing to do in my js script is

$(".contactForm form").submit(function(e){ e.preventDefault(); });
so that the form won’t submit. And then add the ajax call, so that we have:

$(".contactForm form").submit(function(e){ e.preventDefault(); $.ajax({ type: "POST", url: ?, data: $(".contactForm form").serialize(), // serializes the form's elements. success: function(data) { alert("form submitted successfully"); // show response from the php script. } }); });
I’m not sure what the url parameter should contain though as the form should submit to the page where it sits in.
Could anybody give me a hand with this please? Also let’s bear in mind that this needs to be integrated with the php script somehow and the javascript and the php script sits in different files.
thanks

You want to pull the form handling logic out of that page into it’s own formhandler.php (very generic name) script. Reason is you don’t want this script to return HTML as it’s much easier to just return JSON and use that in javascript to show success/error messages.

Note that there is a shorthand post method in Jquery, which has a syntax I prefer over the generic one. Another great tip is using $(this), which refers to the element you’re currently “in”. So in a form submit handler, $(this) is the form. In a button click handler, $(this) is the button, etc…

[php]$.post("/formhandler.php", $(this).serialize())
.then(function (data) {
// alert(“success”);
})
.fail(function () {
// alert(“error”);
});[/php]

Then in the formhandler you’ll have your form validation/save stuff. Just note that instead of echoing data you should output a single json response.

[php]$errors = array();

// ternary operator. $var = condition ? if true : if false;
$title = isset($_POST[‘title’] && $_POST[‘title’] !== ‘0’ ? $_POST[‘title’] : null;

if ($title === null) {
$errors[] = ‘You must select a title’;
}

// …

if (!empty($errors)) {
// change the http status code to something else than 200 OK - this tells javascript it should run the fail block instead of the done block
// https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
http_response_code(400);
echo json_encode($errors);
exit();
}

// will be sent as a 200 OK
// could add data here as well if needed
echo json_encode(’’);[/php]

Thanks but I’m very unfamiliar with all that syntax and I feel I’m getting out of my depths in here. At the beginning I was thinking to use an off-the-shelf solution to handle my form, the validation and the email but I was told (not on this forum but elsewhere) that building my own was easy and quick even if I didn’t know too much php, but it seems that this is growing out of proportions.
So you’re suggesting to have this in my js script
$.post("/formhandler.php", $(this).serialize()) .then(function (data) { // alert("success"); }) .fail(function () { // alert("error"); });
which is essentially the ajax call. The success message is essentially a div that needs to be added to the form, can I just add it with jquery then like so:

.then(function (data) { // add my div with the success message here })

The formhandler.php file deals with errors etc. I will expand this
[php]$errors = array();

// ternary operator. $var = condition ? if true : if false;
$title = isset($_POST[‘title’] && $_POST[‘title’] !== ‘0’ ? $_POST[‘title’] : null;

if ($title === null) {
$errors[] = ‘You must select a title’;
}[/php]
to cover all the other fields (firstname, last name etc).
This block:
[php]if (!empty($errors)) {
// change the http status code to something else than 200 OK - this tells javascript it should run the fail block instead of the done block
// https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
http_response_code(400);
echo json_encode($errors);
exit();
}[/php]
tells javascript to run the fail function, how does it do that? Just by returning anything other than 200OK?
What does the json code return exactly and when the fail function in the javascript runs, what should it do? I thought the errors were output in the php function and not in the javascript?
Finally when this runs (incidentally shouldn’t it be part of an else statement?)
[php]// will be sent as a 200 OK
// could add data here as well if needed
echo json_encode(’’);[/php]
what json object does it return? what do I do with it and what happens when this is returned?

Ah sorry I forgot to mention. Perhaps it might be better if the javascript logic goes onto the HTML file, the reason being that the site is multilingual and if I put it into the main script that means that I have to replicate the whole javascript. If I instead put it as an internal javascript inside the index.php it means I have to replicate only that (currently I have 2 .php files one for each language used.)

Yes, the jquery ajax functions expect the web service to return data. And if the response code is 200 OK that request will be considered successful, but any other codes will mean it will be considered unsuccessul.

In my example it returns an array of strings. So you could iterate over them in JS and write them to the page

Not if you move the form handling to ajax, then the request is handled by javascript so any potential errors will only be visible to javascript (though you can write them to the page from the ajax handler).

It could, just remove the exit and add the else statement. Doesn’t matter.

It returns an empty json object (nothing). The important part this time was just to know if it was successful so we could reset the form. If you ie were opening a modal to edit / add rows to a table then you could return the object that was inserted into the database here so you could write it to the table in JS.

Normally you want javascript in .js files :slight_smile:

OK thanks.
So let’s start from the beginning here because there are issues with files that I maybe didn’t make clear.
My site structure isn’t that simple, in the sense that at the moment I have only one main js file used by both index.php pages (these php pages are essentially the same but in two different languages so if I use any form of error message in the main js file - which at the moment is unique - I have to either duplicate the entire js file and have two (one for each language) or I find another way to handle the error, that’s why I suggested to have the script inside the page (I wouldn’t normally do that)).
SO the options are:

  1. take the js form bit out of the main script, create 1 script for each language (only two luckily) and put the form handling there and call that js script from each index.php. Then create 2 separate formhandler.php files, again one per language and link the form js to those. I don’t know it’s messy and it’s a lot of files
    2)Can we ditch the formhandler.php files and do everything inside the index.php files? Same for the ajax, can we have it inside each index.php?
    I think I need to sort out this first.

You can return the error messages from PHP so as long as your server side knows which language the user wants you can translate there.

  1. yeah it’s messy. One of the most fundamental concepts of coding is keeping it DRY (Don’t Repeat Yourself). The moment you’re writing the same code twice you know you’re doing something wrong.

  2. You could but it would again be a mess. If you want to handle the form with ajax then that part of the PHP needs to return JSON while the rest of it needs to return the actual HTML for the page.

[hr]

Here’s a working example for you

I’ve added “required” to the required fields so modern browsers will help you with client side validation.

I’ve added PHPMailer (just download, extract it somewhere in the project and require the autoloader file in the top phpmailer folder).

Create a app spesific password for your gmail account
https://security.google.com/settings/security/apppasswords

[php]?>


Contact us


We’re always excited to work on a new project, so give us a shout!


Fill in the form or drop us a line at [email protected]






Title


Please select
Mr
Mrs
Ms
Sir
*



First name

*



Last name

*



Email address

*



Website





Enter your message

*













    <script src="/assets/js/contactForm.js"></script>[/php]

[php]$(function () {
$(document).on(“submit”, “#contactForm”, function (e) {
e.preventDefault();

    $form = $(this);
    
    $.post("/formhandler.php", $form.serialize())
    .then(function (msg) {
        $form[0].reset();
        $("span.success").html(msg).show().delay(2500).fadeOut(1000);
    })
    .fail(function (jqXHR) {
        var errors = JSON.parse(jqXHR.responseText);
        $("span.error").html(errors.join('<br>')).show().delay(2500).fadeOut(1000);
    });
});

});[/php]

[php]<?php
header(‘Content-Type: application/json’);

$errors = array();

$title = isset($_POST[‘title’]) ? $_POST[‘title’] : ‘’;
$firstName = isset($_POST[‘firstName’]) ? $_POST[‘firstName’] : ‘’;
$lastName = isset($_POST[‘lastName’]) ? $_POST[‘lastName’] : ‘’;
$emailAddress = isset($_POST[‘emailAddress’]) ? $_POST[‘emailAddress’] : ‘’;
$website = isset($_POST[‘website’]) ? $_POST[‘website’] : ‘’;
$message = isset($_POST[‘message’]) ? $_POST[‘message’] : ‘’;

if ($title === ‘’) {
$errors[] = ‘You must select a title’;
}

if ($firstName === ‘’) {
$errors[] = ‘You must enter a first name’;
}

if ($lastName === ‘’) {
$errors[] = ‘You must enter a last name’;
}

if ($emailAddress === ‘’ || filter_var($emailAddress, FILTER_VALIDATE_EMAIL) === false) {
$errors[] = ‘You must enter a valid email address’;
}

if ($website !== ‘’) {
if(strpos($website, ‘://’) === false) {
$website = ‘http://’ . $website;
}

if (filter_var($website, FILTER_VALIDATE_URL, array('flags' => null)) === false) {
    $errors[] = 'You must enter a valid website address';
}    

}

if ($message === ‘’) {
$errors[] = ‘You must enter a message’;
}

if (empty($errors)) {
require DIR . ‘/phpmailer/PHPMailerAutoload.php’;

//SMTP needs accurate times, and the PHP time zone MUST be set
//This should be done in your php.ini, but this is how to do it if you don't have access to that
date_default_timezone_set('Etc/UTC');

$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = "[email protected]";
$mail->Password = "YOUR APP SPESIFIC PASSWORD";

$mail->setFrom($emailAddress, $firstName . ' ' . $lastName);
$mail->addAddress('[email protected]', 'Bassa Basso');
$mail->Subject = 'New request';
$mail->Body = $message . "\r\n\r\nWebsite: " . $website;
    
if ($mail->send()) {
    echo json_encode('Form submitted successfully!');
    exit();
}

// You may want to log this somewhere
// $mail->ErrorInfo;

$errors[] = 'Could not send email, please try again later';    

}

http_response_code(400);
echo json_encode($errors);
[/php]

oh thanks for that mate, much appreciated, I will try to implement your code then (I wrote the validation based on your previous post but I got stuck with the problem of multiple files).
OK, so you say I can detect the language and return the error in the appropriate language, how does it work? Presumably there will be a locale function of some kind, but do I have to hardcode the error messages in the different language presumably right? And then what’s the mechanism to choose? On the site I’m working at - can’t remember if I shared the URL sorry http://antonioborrillo.co.uk/agency_test/test/en/index.php - I have a php language switcher that allows users to swap between languages, is there some kind of detecting method?

How does the switcher work? Does it just point to a different directory? A better solution would definitely be to have the same code base for all languages, then get the language code somehow (set it in session, parse it from the url, etc) and select language strings based on that.

well something like that - but I really wouldn’t want to change the way it works as it’s done and dusted now and it works quite well for me because I have only 2 languages to worry about, (fully aware that if I had more this solutions wouldn’t really work).
Basically, here is my file structure:

en cookies.js index.php images ... it cookies.js index.php PHPMailer-master ... styles.css formhandler.php tablet.css mobile.css .htaccess form_en.js script.js etc

The htaccess file has this in it:

#language redirects RewriteEngine on RewriteCond %{HTTP:Accept-Language} ^it [NC] RewriteRule ^$ /it/ [L,R=301] RewriteRule ^$ /en/ [L,R=301]

and here is the content of the two index.php files:
[php]


<?php
echo ‘
    ’;
    if ($thisLanguage==‘it’) echo ‘
  • IT
  • EN
  • ’;
    if ($thisLanguage==‘en’) echo ‘
  • IT
  • EN
  • ’;
    echo ‘
’;
?>
[/php] and [php]
<?php echo '
    '; if ($thisLanguage=='it') echo '
  • IT
  • EN
  • '; if ($thisLanguage=='en') echo '
  • IT
  • EN
  • '; echo '
'; ?>
[/php] So basically when the language link is clicked the appropriate page is loaded. Now, on to the code you kindly provided me with. I integrated it, but I have some issues. I've changed the validation slightly [php]$title = (isset($_POST['title']) && ($_POST['title'] != '0')) ? $_POST['title'] : null; $firstName = (isset($_POST['firstName']) && !(empty($_POST["firstName"]))) ? $_POST['firstName'] : null; $lastName = (isset($_POST['lastName']) && !(empty($_POST["lastName"]))) ? $_POST['lastName'] : null; $emailAddress = (isset($_POST['emailAddress']) && !(empty($_POST["emailAddress"]))) ? $_POST['emailAddress'] : null; $website = isset($_POST['website']) ? $_POST['website'] : ''; $message = (isset($_POST['message']) && !(empty($_POST["message"]))) ? $_POST['message'] : null;

if ($title === null) {
$errors[] = ‘You must select a title’;
}

if ($firstName === null) {
$errors[] = ‘You must enter a first name’;
}

if ($lastName === null) {
$errors[] = ‘You must enter a last name’;
}

if ($emailAddress === null || filter_var($emailAddress, FILTER_VALIDATE_EMAIL) === false) {
$errors[] = ‘You must enter a valid email address’;
}

if ($website !== ‘’) {
if(strpos($website, ‘://’) === false) {
$website = ‘http://’ . $website;
}

 if (filter_var($website, FILTER_VALIDATE_URL, array('flags' => null)) === false) {
     $errors[] = 'You must enter a valid website address';
 }    

}

if ($message === null) {
$errors[] = ‘You must enter a message’;
}[/php]

I will have to change the default error messages as well (the one generated by the required attribute becasue not all browsers support it and because it is causing me issues on the mobile version of the site), but let’s leave this for later.
The issue is with the form submission. Now, let me say first that I couldn’t set up that password for my account, it just says that that service isn’t available to my account (I’ve tried with 2 different gmail accounts so definitely not a problem with the account itself). When I attempt to submit the form, I get a few errors on the form itself:

[code]Warning: Cannot modify header information - headers already sent by (output started at /home/antoniob/public_html/agency_test/test/formhandler.php:1) in /home/antoniob/public_html/agency_test/test/formhandler.php on line 3

Fatal error: Cannot redeclare PHPMailerAutoload() (previously declared in /home/antoniob/public_html/agency_test/test/PHPMailer-master/PHPMailerAutoload.php:24) in /home/antoniob/public_html/agency_test/test/PHPMailer-master/PHPMailerAutoload.php on line 31
[/code]
Now, I believe the second one is because I have inserted a required statement, as you said, at the top of the php file
[php]<?php
require ‘PHPMailer-master/PHPMailerAutoload.php’;
header(‘Content-Type: application/json’);[/php]
But I’ve notice that you have one already:
[php] if (empty($errors)) {
require DIR . ‘/PHPMailer-master/PHPMailerAutoload.php’;[/php]
(I changed the path because that’s where the autoload file sits in)
So I removed mine from the top and left yours in. And what happens is pretty odd. If I fill the form in, it takes about 1-2- minutes to submit it, it just hangs, I can see in the console panel in firebug that the formhandler.php just hangs for a few minutes and then eventually it submits the form and I get a 200 OK message (still in the console): but the form never makes it to my email address, presumably because of the password problem?
For simplicity, here is the full php file http://pastebin.com/GNUc8zau, but if you want to see the thing in action might be best if you try on the live site

EDIT: ah, in fact the form doesn’t get submitted, after two minutes at the bottom of the form you get this:
Request Timeout

This request takes too long to process, it is timed out by the server. If it should not be timed out, please contact administrator of this web site to increase ‘Connection Timeout’.

Even though the console says 200 OK

You can’t send mail with PHPMailer using gmail without the password, either change to smtp and add some smtp account, another of the types phpmailer offer, or use a different mail method. I’ve never had the problem of not being able to create application spesific passwords though :\

I’m not sure why it times out, it must be constantly trying to log in with “YOUR APP SPESIFIC PASSWORD”, which is kinda strange - but at the same time it should probably expect you know what your credentials are ^^

You can add this to set a lower timeout for PHPMailer so the timeout happens there instead of in PHP

[php]$mail->Timeout = 30; // set the timeout (seconds)[/php]

right, after having tried with 2 separate gmail accounts (I’ve added my login password here )
$mail->Password = “xxxxxxxx”;
the email still doesn’t send (and no, I can’t create this two verification password, it says that my account isn’t set up for that service). Nevermind gmail, I’ve tried hotmail, here is the configuration that, apparentlym should be used (I removed my password from the below but it is set up correctly):
[php]$mail = new PHPMailer;
$mail->Timeout = 30; // set the timeout (seconds)
$mail->isSMTP();
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = “tls”; // sets the prefix to the servier
$mail->Host = “smtp.live.com”; // sets hotmil as the SMTP server
$mail->Port = 587; // set the SMTP port for the hotmail server
$mail->Username = "[email protected]"; // hotmail username
$mail->Password = “xxxxxxxxxx”; // hotmail password
$mail->setFrom($emailAddress, $firstName . ’ ’ . $lastName);
$mail->addAddress(‘[email protected]’, ‘Bassa Basso’);
$mail->Subject = ‘New request’;
$mail->Body = $message . "\r\n\r\nWebsite: " . $website; [/php]
Also, since it kept complaining about the application/json, I commented it out, so here is the full formhandler.php http://pastebin.com/a21JFWLT
The error now has changed: now it says [“Could not send email, please try again later”] which is one of the messages we have in the script. No idea.

I am presently working on making a few application multi-lingual. It really isn’t that difficult, but you will want a JSON file that has the languages, strings, and constants.

When the js hits a constant, it will check which language it should be using and retrieve the appropriate language string.

Hi, thanks, I think I have the languages sorted as far as the site is concerned, for me it will be only the php form errors to sort out and make sure that they are in the right language when users attempt to submit the form. In any case, I still can’t get the form submission to work as there is something that is preventing it from submitting I think, and for the life of me I can’t understand what it is

I’ve been looking at the server logs and it seems that it’s looking in the wrong folder for the formhandler.php:

2015-12-18 20:02:31.368 [INFO] [82.44.225.54:43274] File not found [/home/antoniob/public_html/404.shtml] 2015-12-18 20:02:31.368 [INFO] [82.44.225.54:43274] File not found [/home/antoniob/public_html/agency_test/test/en/formhandler.php]
but in fact that file sits inside
antonioborrillo.co.uk/agency_test/test/formhandler.php and not inside the en subfolder, but all the references in the scripts seem to point to the right file because in the firebug console I do get this http://antonioborrillo.co.uk/agency_test/test/formhandler.php which is where it is supposed to be.
If you remember the site structure

test en index.php cookies.js images it index.php cookies.js PHPMailer-master PHPMailerAutoload.php formhandler.php form_en.js (contains the ajax call) script.js
then all the files seem to be pointing to the right place as I don’t get any error in the console:
form_en.js has $.post("../formhandler.php", $form.serialize())
and formhandler.php has[php] require DIR . ‘/PHPMailer-master/PHPMailerAutoload.php’;[/php]
but nada

The javascript URL is relative to the public html / web root.

Should probably be: /agency_test/test/en/formhandler.php

all right, wait a minute!!! I got it to work, now it submits the email. It’s this line, $mail->isSMTP();, this was the problem. What on earth is that line supposed to do?!! :smiley:
I got a few submissions. Not all the data comes through though, let me have a look and then I will repost

it sets the mail send method as smtp, which means you will have to supply a valid smtp server and credentials. removing that sets phpmailer to use $mail->isMail() (default) - which is using the normal PHP mail function.

that’s odd, as I believe I did supply valid credentials…in any case it works without that line :-), hope it’s not bad! And now I’ve added more fields to the email, so that it looks like:
[php]$mail->Body = "Title: " . $title . "\r\n\r\nFirst Name: " .$firstName . "\r\n\r\nLast Name: " . $lastName . "\r\n\r\nEmail address: " .$emailAddress . "\r\n\r\nMessage: " . $message . "\r\n\r\nWebsite: " . $website;[/php]
and that sends the data I need. Strange that every email sent goes to the spam folder though…but the email address will change when the site goes live, well before that.
Now, first of all, thanks for helping me out with that. Then with this sorted, the other things I need to do are:
1)remove the required attribute as I want more control on the validation message: I will see what I can do and then, more likely than not, post back for help…
2)Style the success/fail messages a bit.
3)deal with the localisation. We got caught into other things earlier on, so we didn’t have a chance to finish the conversation about the localisation. Now, ideally, as mentioned before, I’d love to keep the language switching functionality as it is, if possible, for two reasons:

  1. it works for me even if I reckon it isn’t the most efficient way.
  2. my knowledge of php, as you’ve noticed, is almonst equal to zero, and the thought of having to redo the whole language switching functionality really makes my heart sink
    But somehow, I need to get the error messages in the form to be translated to italian: do you reckon it would be possible to leave the language functionality there and instead get somehow to retrieve the error messages based on the language of the page? [member=72272]astonecipher[/member] could your solution be implemented here (sorry I didn’t mean to ignore you earlier on, I was just stressed out because I couldn’t get the mail to work!), or any other solution indeed? I’m opened to almost any solution, just bear with me though as I luck the skills to build it probably…sorry!

Um, it appeared that my attempt to remove the required" attribute and replacing the error message with a custom one didn’t quite work. Basically, if I remove the require attribute I get the error messages set up in the formhandler.php file:

[php] $errors = array();

$title = (isset($_POST[‘title’]) && ($_POST[‘title’] != ‘0’)) ? $_POST[‘title’] : null;
$firstName = (isset($_POST[‘firstName’]) && !(empty($_POST[“firstName”]))) ? $_POST[‘firstName’] : null;
$lastName = (isset($_POST[‘lastName’]) && !(empty($_POST[“lastName”]))) ? $_POST[‘lastName’] : null;
$emailAddress = (isset($_POST[‘emailAddress’]) && !(empty($_POST[“emailAddress”]))) ? $_POST[‘emailAddress’] : null;
$website = isset($_POST[‘website’]) ? $_POST[‘website’] : ‘’;
$message = (isset($_POST[‘message’]) && !(empty($_POST[“message”]))) ? $_POST[‘message’] : null;[/php]
Which is great but the problem is that they are all displayed in the top area of the form, where I placed my success message, and I think they should be separate: the error messages should be each below the input field it is referring to. Now, I remember a few posts ago you said that I would have to look through the error messages, which is great, I will try to do that, but there is a problem: even if I loop through them (I will have a look a the php manual for how to do it) the issue is still that this code

[code]$(function(){
$(document).on(“submit”, “#contactForm”, function(e){
e.preventDefault();

      $form = $(this);
      
      $.post("../formhandler.php", $form.serialize())
      .then(function (msg){
          $form[0].reset();
         $("span.success").html(msg).show().delay(2500);//fadeOut(1000)
     })
     .fail(function (jqXHR) {
         var errors = JSON.parse(jqXHR.responseText);
         $("span.error").html(errors.join('<br>')).show().delay(2500);
     });
 });

});[/code]
displays the error messages and success messages in the same container span.success for some reasons. I would have thought that the error (validation errors I mean) would go into the span.error container, have a look at the live site here so you know what I mean http://antonioborrillo.co.uk/agency_test/test/en/index.php
How do I get the validation errors to be displayed in the error container?
thanks

Sponsor our Newsletter | Privacy Policy | Terms of Service