Receiving "Uncaught SyntaxError: Unexpected token (" with AJAX - javascript

I'm trying to integrate a validation plugin with a form in Bootstrap. When I use the code below, I get the following error:
"Uncaught SyntaxError: Unexpected token (".
I can't figure out whether the issue is with the PHP, the Javascript, or both. Is the PHP coded correctly here?
JavaScript:
$(document).ready(function() {
$('#formBasic').formValidation({
framework: 'bootstrap',
fields: {
firstName: {
validators: {
notEmpty: {
message: 'Name is required'
}
}
},
lastName: {
validators: {
notEmpty: {
message: 'The password is required'
}
}
}
}
})
.on('success.form.fv', function(e) {
e.preventDefault();
var $form = $(e.target);
var bv = $form.data('formValidation');
$.post($form.attr('action'), $form.serialize(), function(result) {
error: function () {
alert("There was an error processing this page.");
return false;
},
success: function (output) {
$('#formBasicResults').html(output.responseText);
alert('success');
}
}, 'json');
});
PHP:
function formBasic(){
$output = 'Output from Form Basic:
';
foreach ($_POST as $key => $value) {
$output .= $key . ': ' . $value . '
';
}
echo $output;
}
if(in_array($_POST['function'], array('formBasic','formAdvanced'))){
$_POST['function']();
}else{
echo 'There was an error processing the form';
}

Your $.post syntax is incorrect where you are declaring the success and error handlers. Try this:
$.post($form.attr('action'), $form.serialize())
.done(function(result) {
$('#formBasicResults').html(result.responseText);
alert('success');
})
.fail(function() {
alert("There was an error processing this page.");
});

You will get the freedom to specify the datatype as json or jsonp or text using $.ajax
So instead of $.post use $.ajax, only additional thing you need to include is the type:post.
$.ajax({
type: "POST",
url: "some.php",
dataType: "json"
data: { name: "John" },
success:function () { //handle success calls},
error:function () { //handle failure calls}
});
REF: http://api.jquery.com/jquery.ajax/

Related

Using Jquery and ajax post method for sending some data and then to fetch a response. response is coming properly, success function not working

JS CODE
$("#getdata").click(function(e) {
console.log("HEY");
var source = $('#origin').val();
console.log(source);
var destination = $('#destination').val();
console.log(destination);
e.preventDefault();
$.ajax({
type:'post',
url:"{{url('/searchDistance')}}",
dataType: 'json',
data: jQuery("#distance_form").serialize(),
success: function(data) {
var x = JSON.parse(data);
console.log(x);
},
error: function(xhr, status, error) {
console.log("Error");
console.log(error);
}
});
PHP Controller code I am MAking this in laravel
public function search (Request $request) {
if($request->ajax()) {
$source = $request->get('from');
echo $source;
$destination = $request->get('to');
echo $destination;
$FindSource = google_api::where('source', '=', $source)->exists();
if(!$FindSource) {
return response()->json(['success'=>false, 'message' => 'Source Not Found']);
}
else {
$FindDestin = google_api::where('destination', '=', $destination)->first();
if(!$FindDestin) {
return response()->json(['success'=>false, 'message' => 'destination not found']);
} else {
return response()->json(['success'=>true, 'message'=> 'success', 'data'=> $FindDestin]);
echo json_encode($FindDestin);
}
}
}
}
}
I am getting a proper response in xhr and network but my success function is not working and error function is running all the time with an error of SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data.

Ajax with validate.js returning undefined result from php

Hello All, I have written a one demo code to check weather the given input user is exist in the list or not using ajax and validate.js, when I'm running the code all functions are executing fine but insted of getting response message in succes function it is jumping to the error function and giving undefined response as sent form php.
Here is my code:
$.validator.addMethod("checkUserExists", function(value, element){
alert("input checking");
var inputElem = $('#hl_form :input[name="username"]'),
data = { "username" : inputElem.val(),"check": "userCheck"},
eReport = ''; //error report
$.ajax(
{
type: "POST",
url: "services.php",
async: true,
dataType: 'json',
data: data,
success: function(result)
{
alert(result);
console.log(result);
if (result.status !== 'true')
{
return '<p>This User is already registered.</p>';
}else{
return true;
}
},
error: function(xhr, textStatus, errorThrown)
{
//alert('ajax loading error... ... '+url + query);
return false;
}
});
}, 'User Alread exist in the DB');
My Validate.js Rules and and Message are
Validate Method Rule
username: {
required: true,
checkUserExists:true
}
Validate.js Method Message
username: {
required: "Please enter your Username",
checkUserExists: "User... already exist"
},
My Php Code (service.php)
<?php
header('Content-Type: application/json');
class form_services{
public $sql;
public $returnResult = array();
function checkUser($requestedUser) {
$registeredUser = array('xyz', 'abc', 'def', 'ghi', 'jkl');
if( in_array($requestedUser, $registeredUser) ){
$returnResult["status"] = 'false';
}else{
$returnResult["status"] = 'true';
}
return $returnResult;
}
} //Class Ends Here
$checkRequest = $_POST['check'];
$frmServices = new form_services();
$data = '';
switch ( $checkRequest) {
case 'userCheck': $requestedUser = $_REQUEST['username'];
$data = $frmServices->checkUser( $requestedUser);
echo json_encode($data);
break;
default: echo json_encode($data);
break;
}
?>
Please help me in resolving my issue, i'm getting undefined result in ajax call from php cod.

"parsererror" SyntaxError: Unexpected token < in JSON at position 0

So I am working on this form that contains both form and files data. I want to submit it through Ajax. So when it can't pass form Validation, use won't loose the whole entry.
create.php
<script type="text/javascript">
$("#add-product-form").submit(function(e){
e.preventDefault();
var formData = new FormData(this);
console.log(formData);
var url="products/ajax_add_single_product";
$.ajax({
type:"post",
url:"<?php echo base_url() ?>"+url,
data:formData,
dataType:'json',
cache: false,
contentType: false,
processData: false,
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR,textStatus,errorThrown);
error = jqXHR.responseJSON.error;
$(".submit-message").html(error);
console.log(error);
$("html, body").animate({ scrollTop: 0 }, 200);
},
success: function (data, textStatus, jqXHR) {
message = jqXHR.responseJSON.success;
$(".submit-message").html(message);
location.href = "/products";
}
})
})
</script>
controller
public function create(){
$data\['title'\] = "Add Product";
$data\['categories'\] = $this->category_model->get_categories();
$data\['children'\] = $this->category_model->get_child_cats(0);
$data\['vendors'\] = $this->vendor_model->get_vendors();
$data\['attributes'\] = $this->product_model->get_attributes();
$this->load->view('templates/header', $data);
$this->load->view('products/create');
$this->load->view('templates/footer');
}
public function ajax_add_single_product(){
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->form_validation->set_rules('productname', 'Product Name', 'required');
$this->form_validation->set_rules('partnumber', 'Part Number', 'required|is_unique\[items.itemSKU\]');
$this->form_validation->set_rules('catID', 'Category', 'required', array('required'=>"You need to pick a %s"));
header('Content-Type: application/json');
if ($this->form_validation->run() === FALSE)
{
$this->output->set_status_header(400);
$errors = validation_errors();
echo json_encode(['error'=>$errors]);
}
else
{
$this->output->set_status_header(200);
$imageData = $this->images_upload();
$this->product_model->create_product($imageData);
echo json_encode(['success'=>'Record added successfully.']);
}
}
With above code, when entry can't pass form validation, It will give me form validation errors. When the entry is success, it will insert data to database as I expected. but it will still give me a error. seems like i am not getting JSON data, and getting html.
So turns out, there was one line in the create_product() function in the model. After insert data to tables, I put redirect('/products')after, that's why I am getting the html source code of page products.

ajax jquery always running Error;

Ajax jquery always running error function, althought success function run and i can get session value,i can't run window.location="profile.php";
$(document).ready(function(){
$("#login").click(function(){
var username=$("#usern").val();
var password=$("#user").val();
$.ajax({
type: "POST",
url: "model/user.php",
data: {
user_log : username,
password : password
},
dataType: 'json',
error: function (xhr,textStatus,errorThrown) {
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
},
success: function(json){
window.location="profile.php";
},
beforeSend:function()
{
$("#error").html("<img src='http://www.chinesecio.com/templates/base/images/loading.gif' /> Loading...")
}
});
return false;
});
});
user.php
<?php
ob_start();
session_start();
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
require_once(dirname(__FILE__).'/../model/connect.php');
?>
<?php
global $pdo;
if(isset($_POST['user_log'])) {
// username and password sent from Form
$username=$_POST['user_log'];
$password=$_POST['password'];
$qr= "SELECT * FROM user where username='$username' AND password='$password'" ;
$stmt= $pdo->query($qr);
$row= $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0)
{
$_SESSION['id']=$row['id'];
$_SESSION['name_mem']=$row['username'];
$_SESSION['level_mem']=$row['level'];
}
header("location:../../../../index.php");
}
?>
Remove this line :
header("location:../../../../index.php");
If above doesn't work, omit this from ajax properties :
dataType: 'json',
you can use ajax like this,
<script>
$("#login").click(function(){
var username=$("#usern").val();
var password=$("#user").val();
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
//progress
xhr.upload.addEventListener("progress", function(e) {
//progress value : you can load progress bar in here
}, false);
return xhr;
},
type: "POST",
url: "model/user.php",
data: {'username' : username, 'password' : password},
dataType:json,
success: function(msg) {
//when success //200 ok
if(msg.status=="done"){
window.location="profile.php";
}else{
$("#error").html("<span style='color:#cc0000'>Error:</span> "+msg.massage);
}
},
error: function(jqXHR, textStatus, errorThrown) {
//when error: this statement will execute when fail ajax
}
});
});
</script>
server side code like this(inside user.php),
$username=$_POST['username'];
$password=$_POST['password'];
...........
//$status="fail" or "done"
//success must be always success
//$massage= "password or username not match"
$respond=array("success"=>"success","status"=>$status,"massage"=>$massage);
echo json_encode($respond);
exit;
I hope you useful this.

AJAX form not submitting that gives error

I have my AJAX code here
$("#add-student").click(function(e) {
e.preventDefault();
formData = $("#student-form").serialize();
if (cleanFormInput()) {
sendTheInfo(formData);
} else {
shakeForm();
}
});
function sendTheInfo(formData) {
$.ajax({
type: "POST",
url: "../classes/ajax/postNewStudent.php",
data: formData,
statusCode: {
404: function() {
alert( "page not found" );
}
},
success: function(formData) {
console.log("New student submitted:\n" + formData);
//clearForms();
},
error: function(result, sts, err) {
console.warn("Connection error:\n" + err + " : " + sts);
console.log(result);
shakeForm();
},
complete: function() {
console.log("Everything complete");
}
});
}
Always without fail outputs this error:
Connection error:
SyntaxError: Unexpected end of input : parsererror
But still gives the complete message: Everything complete
Update, PHP code here:
require '../../core/init.php';
require '../../classes/Config.php';
header('Content-Type: application/json');
if (!empty($_POST)) {
$id = $_POST["sid"];
$first = $_POST["first"];
$last = $_POST["last"];
$fav = "0";
$sql = "INSERT INTO `students` (`id`, `first`, `last`, `active`) VALUES ('{$id}', '{$first}', '{$last}', '{$fav}')";
$link = mysql_connect(Config::get('mysql/host'),Config::get('mysql/username'),Config::get('mysql/password')) or die("could not connect");;
mysql_select_db(Config::get('mysql/db'), $link);
$result = mysql_query($sql, $link);
if ($result) {
header('Content-Type: application/json');
$student_data = $id . $first . $last . $fav;
echo json_encode($student_data);
}
}
I'm a bit confused, am I doing my ajax set up wrong? Or is it something else in by backend code wrong? I'm using MySQL and jQuery 2.0.3
Updated code here: here
I have had a look at your code. I saw that from the PHP side you are sending a JSON object. but you didn't specified the return dataType for the response. Try to add the dataType in the ajax call. Maybe that will solve the problem
function sendTheInfo(formData) {
$.ajax({
type: "POST",
url: "../classes/ajax/postNewStudent.php",
data: formData,
dataType : 'json',
statusCode: {
404: function() {
alert( "page not found" );
}
},
success: function(formData) {
console.log("New student submitted:\n" + formData);
//clearForms();
},
error: function(result, sts, err) {
console.warn("Connection error:\n" + err + " : " + sts);
console.log(result);
shakeForm();
},
complete: function() {
console.log("Everything complete");
}
});
}
It should be noted that the Ajax COMPLETE method will fire even if the back end does not return a result.
complete: function() {
console.log("Everything complete");
}
will thus show the log'ed entry every time an ajax call is 'finished executing', even if the submit failed.
I would also suggest NOT having 2 headers or the same declaration (you have one up top, and one in the if(result) call.
In a comment thread, you pointed out that you're working on the server but not locally, And thus that implies you have some pathing issues. Check your
../
relative path style urls and make sure that you have the same basepoints.
removed my old answer. I don't think it is an ajax/javascript error. it's definitely a PHP error. It's this lines:
$student_data = $id . $first . $last . $fav;
echo json_encode($student_data);
You $student_data is not an array, it's just a string. You need to pass an array into the json_encode function

Categories

Resources