Help with jquery ajax call with wordpress

flynny
flynny used Ask the Experts™
on
Hi all,

I am struggling to get my PHP file firing form an jquery ajax call?

I have the following attached code.

Now the first test alert is firing, but the second isn't its not even giving any kind of error??

Any ideas guys


<script type="text/javascript">
	var name;
	var email;
	var telephone;
	var enquiry;
	var allow;
	
	$(function(){
		$('a#scrollLink').click(function(event){
			var clicked = $(this).attr('href');
			var destination = $(clicked).offset().top;
			$('html:not(:animated), body:not(:animated)').animate({ scrollTop: destination-40}, 400 );
			event.preventDefault();
		});
		
		$('#subNav').hide();
		$('#servicesNav').click(function(event){
			event.preventDefault();
			});
		$('#servicesNav').parent().hover(function(){
			$('#subNav').show();
			}, function(){
			$('#subNav').fadeOut('slow');
			});
		
		$('.error').hide();
		
		$('#contactForm form').submit(function(event){
				$('.error').hide();
				$('.row .textInput').css('border-color', '#dfdbdb');
				allow=true;
				$('form .row').each(function(){
					validate($(this));	
				});
				
				if(allow){

//alert($('#contactForm form').serialize());

alert('TEST 1');
						$.post('<?php bloginfo('template_url'); ?>/sendemail.php', $('#contactForm form').serialize(), function(response){

alert('TEST 2');
						//deal with the response from the ajax request
						if(response.result){

alert(response.result);
							$('#contactForm').before("<div class='alpha grid_8' id='thanksDiv'>Thank you! Your email has been received</div>").fadeOut('fast');
							$('#thanksDiv').hide().delay('200').fadeIn('slow');


						}
						else{
alert('HERE!!');
							alert('There was en error sending the form:' + response.result + ':' );
							console.log("error with sending email");
						}
						}, 'json');
				}
				else{
					$('form .row input').first().focus();	
				}
				event.preventDefault();
				
			})
		
	});
	
	function validate(jobj){
		var val = jobj.find('input').val();
		if(val == '' && jobj.find('.textInput')){
			jobj.find('.error').html('Required field').show();
			jobj.find('.textInput').css('border-color', '#a6373a');
			allow = false;
		}
		
		if(jobj.find('#emailInput').length && jobj.find('#emailInput').val() != ''){
			var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; 
			if(!emailPattern.test(jobj.find('#emailInput').val())){
				allow=false;
				jobj.find('.error').html('Invalid email').show();
				jobj.find('#emailInput').css('border-color', '#a6373a');
				allow=false;
			}
		}
		
		if(jobj.find('#telephoneInput').length && jobj.find('#telephoneInput').val() != ''){
			var phonePattern = /[\d ]{10,12}/;
			
			if(!phonePattern.test(jobj.find('#telephoneInput').val())){
				jobj.find('.error').html('Invalid number').show();
				jobj.find('#telephoneInput').css('border-color', '#a6373a');
				allow=false;
			}
		}
	}
</script>

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
How will the HTML result of line 41 look like. Are all the paths correct?
Will bloginfo('template_url'); echo a path or will it return it?

Did u tried a JavaScript debugger to see what happens?

Author

Commented:
Hi,

thanks for the reply. yes I have used firebug to check the path and it si pointing to the correct file.

I have used similar scripts in other site and these have worked with no problem whatsoever.

I haven't tried a javascript debugger because I have no experience with them. Is there one you can recommend?

Please find the PHP file used attached;
<?php

require_once("class.phpmailer.php");

// get posted data into local variables
$From = "web@<domain>.co.uk"; 
$To = "matt@<domain>.co.uk";
$Subject = "Contact Form";
$Body = "<p>" . $_POST['enquiry'] . "</p><p>From: " . $_POST['name'] . "</p><p>Telephone: " . $_POST['phone'] . "</p><p>Email address: ". $_POST['email']. "</p>";
 
$mail = new PHPMailer();

$mail->IsSMTP();                                      // set mailer to use SMTP
$mail->Host = "auth.smtp.1and1.co.uk";  // specify main and backup server
$mail->SMTPAuth = true;     // turn on SMTP authentication
$mail->Username = "user";  // SMTP username
$mail->Password = "pass"; // SMTP password
 
$mail->From = $From;
$mail->FromName = "Mailer";
$mail->AddAddress($To);           

$mail->Subject = $Subject;
$mail->Body    = $Body;

if(!$mail->Send()){
	
	echo 'ERROR';
	//print_r('Error');
}
else{

	echo 'OK!';
	//print_r(json_encode($result));	

}

?>

Open in new window

not sure if it has something to do with it. but on the post u specify it's json. $('#contactForm form').serialize() will not return json as far as i know.
if u put after line 58 a alert. Wil it execute?
Rowby Goren Makes an Impact on Screen and Online

Learn about longtime user Rowby Goren and his great contributions to the site. We explore his method for posing questions that are likely to yield a solution, and take a look at how his career transformed from a Hollywood writer to a website entrepreneur.

Author

Commented:
yes  added an alert and it triggers after line 58.

If is uncomment the .serialize i get the following alert

name=matt&email=matt%40<domain>.co.uk&phone=<number>&enquiry=eee


Also for completion heres the html..
<div id="contactForm" class="alpha grid_8"> <a name="contactForm"></a>
      <form action="sendemail.php">
        <div class='row'>
          <label title="Name" for="nameInput" id="nameLabel"><span class='labelKey'>Name<span class="required">*</span></span></label>
          <input type="text" size="50" id="nameInput" class='textInput' name="name" />
          <label for="nameInput" title="Name is a required field" id="nameError" class="error">Required field</label>
        </div>
        <div class='row'>
          <label title="Email" for="emailInput" id="emailLabel"><span class='labelKey'>Email Address<span class="required">*</span></span></label>
          <input type="text" size="50" id="emailInput" class='textInput' name="email" />
          <label for="emailInput" title="Email is a required field" id="emailError" class="error">Required field</label>
        </div>
        <div class='row'>
          <label title="Telephone" for="telephoneInput" id="telephoneLabel"><span class='labelKey'>Telephone<span class="required">*</span></span></label>
          <input type="text" size="50" id="telephoneInput" class='textInput' name="phone" />
          <label title="Telephone is a required field" id="nameError" class="error">Required field</label>
        </div>
        <div class='row'>
          <label title="Enquiry" for="enquiryInput" id="enquiryLabel"><span class='labelKey'>Enquiry</span></label>
          <textarea id="enquiryInput" cols="50" rows="15" class='textInput' name="enquiry" ></textarea>
          <label title="Enquiry is a required field" id="enquiryError" class="error">Required field</label>
        </div>
        <input type="submit" value="Submit" size="50" id="submitButton" />
      </form>
    </div>

Open in new window

Can u remove the , 'json' on line 58, and try it?

Author

Commented:
Great, that has got it running,

one further question. its now returning an error, however the

alert('There was en error sending the form:' + response.result + ':' );


response.result in the error catcher is returning 'undefined' any ideas how I can get some more info on the error??

Thanks for your help.
That has to do with the response given by the request. The code assumes that a json is returned saving the response is valid. At the moment ur not returning any json. So it will assume there was a error.

2 ways to solve it
1. Return a json and put the return type json back.
2. Change the error handing to compare the string returned.

Just alert the response to see what u get (line 44).

Author

Commented:
Thank for you help, perfect. I can't thank you enough.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial