Jump to content
Sign in to follow this  
justin7410

SyntaxError: Unexpected token < error due to a parsererror condition

Recommended Posts

Hey guys,

 

i am trying to create a contact form that by passes the page refresh and uses Jquery and Ajax to direct to a php file server side. 

 

So far i have everything work fine. until the final part where i pass the json data type into PHP and look to catch an error, success, or completion value.

 

Currently i have an error coming back with the following: SyntaxError: Unexpected token < error due to a parsererror condition

 

I do not see any errors in the console of of chrome, and i have no idea why i am getting this syntax error. 

 

These does not seem to be any conflicting data going into the json or out to php. really been stuck on this for a day now :(

 

This is my .js file 

$(document).ready(function(){

$('form #alertMessage').hide();

$('#submit').click(function(e){

e.preventDefault();

var valid = '';
var name = $('form #name').val(); 
var email = $('form #email').val(); 
var subject = $('form #subject').val(); 
var message = $('form #message').val(); 
var honeypot = $('form #honeypot').val(); 
var humancheck = $('form #humancheck').val();

if(name = '' || name.length <= 5 ){

valid += '<p>Sorry, Your name is required!</p> '; 
}
if(!email.match( /^([a-z0-9._-]+@[a-z0-9._-]+\.[a-z]{2,4}$)/ )){

valid += '<p>A Valid Email is required</p> ';
}
if(subject = '' || subject.length <= 2 ){

valid += '<p>A Valid name is required</p> ';
}
if(message = '' || message.length <= 5 ){

valid += '<p>A brief description of you is required.</p> '; 
}
if(honeypot != 'http://'){

valid += '<p>Sorry spambots not allowed.</p> ';
}
if(humancheck != ''){

valid += '<p>Sorry only humans allowed past this point.</p> ';
}

if(valid != ""){

$('form #alertMessage').removeClass().addClass('error')
.html('<br><br>' + valid).fadeIn('fast')

}else{

$('form #alertMessage').removeClass().addClass('processing')
.html('<br><br>We are processing your form now...').fadeIn('fast')

var formData = $('form').serialize();
submitForm(formData);

}

});
});

function submitForm(formData){

$.ajax({

type: 'POST',
url: 'feedback.php',
data: formData,
dataType: 'json',
cache: false,
timeout: 7000,
success: function(data){

$('form #alertMessage').removeClass().addClass((data.error === true) ? 'error' : 'success' )
.html(data.msg).fadeIn('fast');

if($('form #alertMessage').hasClass('success')){
setTimeout("$('form $alertMessage').fadeOut('fast')", 5000);
}
},
error: function(XMLHttpRequest, testStatus, errorThrown){
$('form #alertMessage').removeClass().addClass('error')
.html(' <p>There was an ' + errorThrown + ' error due to a  ' + testStatus + ' condition.</p>').fadeIn('fast');
},
complete: function(XMLHttpRequest, status){

$('form')[0].reset();
}
});
};

 

Here is the php script. 

<?

sleep(3);

$name = trim($_POST['name']);
$name = trim($_POST['email']);
$name = trim($_POST['subject']);
$name = trim($_POST['message']);
$name = $_POST['honeypot'];
$name = $_POST['humancheck'];

if ($honeypot == 'http://' && empty($humancheck)){

	$errorMsg = '';
	$reg_exp = "/^([a-z0-9._-]+@[a-z0-9._-]+\.[a-z]{2,4}$/ ";
	
	if(!preg_match($reg_exp, $email)){
			$errorMsg .=  "<p>A valid email is required</p>";
		
	}
	if(empty($name)]){
			$errorMsg .= '<p>Please provide your name</p>';
		
	}
	if(empty($message)]){
			$errorMsg .= '<p>Please provide a message</p>';
		
	}
	if(!empty($errorMsg)){
		
		$return['error'] = true;
		$return['msg'] = 'Sorry the request was successful but your form was not correctly filled.' . $errorMsg;
		echo json_encode($return);
			
		exit();
		
	}else{
		
		$return['error'] = false;
		$return['msg'] = 'Thank you for your feedback ' .$name . ' ' . $errorMsg;
		echo json_encode($return);
			
	}

	
} else {

		$return['error'] = true;
		$return['msg'] = 'Oops...there was a problem with your submission. Please try again' ;
		echo json_encode($return);

}

?>

HTML side.

                    <form id="contact_us" class="contact-form"  action="feedback.php" enctype="multipart/form-data" method="post">
					
					<div id="alertMessage">
					
					</div>
							
                        <div class="row">
                            <div class="col-md-6">
                                <input type="text" name='name' class="form-control" id="name" placeholder="Full Name">
                                <input type="email" name='email' class="form-control" id="email" placeholder="Your Email">
                                <input type="text" name='subject' class="form-control" id="subject" placeholder="Company or Project name">                                
                            </div>
                            <div class="col-md-6">
                                <textarea class="form-control" name="text" id="message" rows="25" cols="10" placeholder="  Brief Description"></textarea>
                                <input id='submit' name='submit' type="submit" class="btn btn-default submit-btn form_submit">                             
                            </div>
							<input type="hidden" name="honeypot" id="honeypot" value="http://" />
							<input type="hidden" name="humancheck" id="humancheck" value="" />
							
                        </div>
                    </form>

Image of the error output

 

 

post-144747-0-93841600-1449371168_thumb.png

Share this post


Link to post
Share on other sites

Are you sure your PHP accepts the deprecated “<?” short tags? This is not the default. Try replacing them with proper “<?php” tags.

 

You also have stray “]” brackets in line 21 and 25. And you keep overwriting your $name variable with different values from $_POST.

Edited by Jacques1

Share this post


Link to post
Share on other sites

Are you sure your PHP accepts the deprecated “<?” short tags? This is not the default. Try replacing them with proper “<?php” tags.

 

 

I changed this just in case that was the issue. nothing was solved.

 

 

You also have stray “]” brackets in line 21 and 25. And you keep overwriting your $name variable with different values from $_POST.

 

this was a great catch on the variable names, sadly i had shortcut the duplication of them and did not change them to the proper variable name.

 

Nether of these solutions solved the problem. The actual processing of the script is taking longer ( i see the loading gif longer ) , but the final result is the same error.

 

Any other suggestions ?

Share this post


Link to post
Share on other sites

So to spell out what Jacques sees,

 

That error message is being shown with some sort of Javascript code. It isn't a browser thing. Now, the most reasonable way that would happen is because your form did an AJAX request, but the response had an error. Specifically, the unexpected

It just so happens that the very first character in your PHP code (which generates the AJAX response) is a <. and it part of the deprecated short tags. if tags are not enabled then all that php code will be returned in response. evaluated.>

 

The best thing to do is to fix the to use the standard, long-form <?php opening instead. If that doesn't do it, use Chrome's Network tab to see exactly what response was being returned during the AJAX; to catch the request you need to open the Network tab, or at least the inspector window, before submitting the form.

Share this post


Link to post
Share on other sites

you are also getting php error messages being sent back. primarily because there are no $_POST['message'] and $_POST['honeypot'] in the data you are sending to the php code. you can find these if you look at the response sent back to the browser's developer tools -

 

<br />
<b>Notice</b>:  Undefined index: message in <b>your_server\feedback.php</b> on line <b>8</b><br />
<br />
<b>Notice</b>:  Undefined variable: honeypot in <b>your_server\feedback.php</b> on line <b>12</b><br />
{"error":true,"msg":"Oops...there was a problem with your submission. Please try again"}

 

 

Share this post


Link to post
Share on other sites

So to spell out what Jacques sees,

 

That error message is being shown with some sort of Javascript code. It isn't a browser thing. Now, the most reasonable way that would happen is because your form did an AJAX request, but the response had an error. Specifically, the unexpected < is found in the AJAX response.

It just so happens that the very first character in your PHP code (which generates the AJAX response) is a <. And it's part of the deprecated <? short tags. If short tags are not enabled then all that PHP code will be returned in the response. Not evaluated.

 

The best thing to do is to fix the <? to use the standard, long-form <?php opening instead. If that doesn't do it, use Chrome's Network tab to see exactly what response was being returned during the AJAX; to catch the request you need to open the Network tab, or at least the inspector window, before submitting the form.

 

So the issue that was bringing this message was my regular expression variable was missing a character so the function of match was not working.

$reg_exp = "/^([a-z0-9._-]+@[a-z0-9._-]+\.[a-z]{2,4}$/ ";
	
	if(!preg_match($reg_exp, $email)){
			$errorMsg .=  "<p>A valid email is required</p>";
		
	}

so that fixed this issue.

 

 

you are also getting php error messages being sent back. primarily because there are no $_POST['message'] and $_POST['honeypot'] in the data you are sending to the php code. you can find these if you look at the response sent back to the browser's developer tools -

 

 

 

 

What you bring up is a whole other issue within itself, that i realized once solving the problem above. The data for $message is not being sent to with the submission and client side php is not seeing that data.

 

Not sure why that would be happening.

 

EDIT:

 

I changed the if(empty($message)) -> if(!isset($message)) and that seemed to have fixed it.

 

Any reason why that would be ?  

Edited by justin7410

Share this post


Link to post
Share on other sites

the php error on line 8 is because the name='...' attribute for your <textarea> is 'text'

 

the php error on line 12 is/was because of the repeated $name = assignments.

 

i recommend that you first get your form and your form processing code to work correctly, then add any javascript validation and using ajax to submit the form data.

 

edit: the only thing changing the code testing $message is doing is hiding the fact that your form field isn't named 'message.'  the $message variable is set, because your code is setting it. !isset() will never cause your 'please provide a message' to ever be output. 

Edited by mac_gyver

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Sign in to follow this  

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.