简体   繁体   中英

Receiving “Uncaught SyntaxError: Unexpected token (” with AJAX

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM