Error Unexpected Token < In Json Response
Iam trying to get in users information into database via javaScript file by linking it to a .php file its throwing 'unexpected token <' but when i directly give action as .php
Solution 1:
There are several things I would like to point out.
Your form validation
var status = $('form')[0].checkValidity();
won't work because you didn't includerequired
attribute in your<input ...>
elements. Include them like this:<inputtype="text" placeholder="Current address"class="form-control required"id="ca" name="ca" required>
- Use
e.preventDefault();
to prevent your form from being submitted in the first place. - If you're uploading file through AJAX, use FormData object. But keep in mind that old browsers don't support FormData object. FormData support starts from the following desktop browsers versions: IE 10+, Firefox 4.0+, Chrome 7+, Safari 5+, Opera 12+.
- Set the following options,
processData: false
andcontentType: false
in your AJAX request. Refer the documentation to know what these do. - And finally, do proper validation of your form inputs on
form_citizenship.php
page because right now it's a complete mess.
So your jQuery should be like this:
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
var status = $('form')[0].checkValidity();
if(status){
var formData = newFormData($('form')[0]);
$.ajax({
url: "form_citizenship.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
async: false,
dataType: "JSON",
success: function(json){
if(json.error){
alert(json.error_msg);
}else{
alert(json.docno);
}
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
}
});
});
And process your AJAX request like this:
<?php
session_start();
define('HOST','localhost');
define('USER','root');
define('PASS','');
define('DB','miisky');
$response = array();
$con = mysqli_connect(HOST,USER,PASS,DB) ordie('Unable to Connect');
if(!mysqli_connect_errno()){
$error_flag = false;
foreach($_POSTas$value){
if(empty($value)){
$error_flag = true;
break;
}
}
if(!$error_flag){
//receiving post parameters$ca =$_POST['ca'];
$hno = trim($_POST['hno']);
$rno = trim($_POST['rno']);
$location = trim($_POST['location']);
$country = trim($_POST['country']);
$state = trim($_POST['state']);
$city = trim($_POST['city']);
$pin = trim($_POST['pin']);
$doctitle = trim($_POST['doctitle']);
$docno = trim($_POST['docno']);
$ia = trim($_POST['ia']);
$doe = trim($_POST['doe']);
$pno = trim($_POST['pno']);
$pissuedby = trim($_POST['pissuedby']);
$pdoe = trim($_POST['pdoe']);
$vno = trim($_POST['vno']);
$vissuedby = trim($_POST['vissuedby']);
$vdoe = trim($_POST['vdoe']);
if(isset($_FILES["doc"]["name"]) && !empty($_FILES["doc"]["name"])){
//image insertion$target_dir = 'doc_uploads/';
$target_file = $target_dir . basename($_FILES["doc"]["name"]);
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$check = getimagesize($_FILES["doc"]["tmp_name"]);
if($check !== false){
if (!file_exists($target_file)){
if($_FILES["doc"]["size"] <= 2097152){
$permissible_images = array('jpg', 'png', 'jpeg', 'gif');
if(in_array($imageFileType, $permissible_images)){
if (move_uploaded_file($_FILES["doc"]["tmp_name"], $target_file)){
// create a new user profile$sql = "INSERT INTO citizen_info(ca, hno, rno, location, country, state, city, pin, doctitle, docno, ia, doe, pno, pissuedby, pdoe, vno, vissuedby, vdoe, doc, created_at) VALUES ('$ca', '$hno', '$rno', '$location', '$country', '$state', '$city', '$pin', '$doctitle', '$docno', '$ia', '$doe', '$pno', '$pissuedby', '$pdoe', '$vno', '$vissuedby', '$vdoe', '$target_file', NOW())";
if(mysqli_query($con,$sql)){
$response["error"] = false;
$response['docno'] = $docno;
echo json_encode($response);
}else{
$response["error"] = true;
$response["error_msg"] = "INSERT operation failed";
echo json_encode($response);
}
}else{
// Throw Error Here$response["error"] = true;
$response["error_msg"] = "File could not be uploaded";
echo json_encode($response);
}
}else{
$response["error"] = true;
$response["error_msg"] = "Only jpg, png and gif images are allowed";
echo json_encode($response);
}
}else{
$response["error"] = true;
$response["error_msg"] = "file size is above 2MB";
echo json_encode($response);
}
}else{
$response["error"] = true;
$response["error_msg"] = "file already exists";
echo json_encode($response);
}
}else{
$response["error"] = true;
$response["error_msg"] = "invalid image format";
echo json_encode($response);
}
}else{
$response["error"] = true;
$response["error_msg"] = "Empty file";
echo json_encode($response);
}
}else{
$response["error"] = true;
$response["error_msg"] = "Few fields are missing";
echo json_encode($response);
}
}else{
$response["error"] = true;
$response["error_msg"] = "Database connection failed";
echo json_encode($response);
}
?>
Solution 2:
This mostly happens due to the javascript expecting a json response, and server throwing some error enclosed with '<html></html>'
.
Check inside the chrome inspector if the ajax response is correct. Headsup:
Inside Chrome>
F12>
Network >
XHR.
Check the response as follows..
$.ajax({
url: "form_citizenship.php",
type: "POST",
//form serialization of the all parametersdata: $("#form").serialize(),
async: false,
//data passed in jsondataType: "JSON",
/*Give out the alert box
to display the results*/success: function (json){
console.log(json); // <<< you can view in the console the response.
.......
},
//through out error from back-end if existerror: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
Post a Comment for "Error Unexpected Token < In Json Response"