简体   繁体   中英

How to send a form with php / ajax without opening a new page when send

I have a little form and I'm trying to return a ajax error if the form is send or when something went wrong.

in connection.php I have a little script that submits the form

if($_POST['postForm'] == 'newsletter'){

    $newsletterSubscriber = new NewsletterSubscriber();
    $newsletterSubscriber->set('CMS_newsletters_id', 2);
    $newsletterSubscriber->set('created', date('Y-m-d H:i:s'));
    $newsletterSubscriber->set('firstName', $_POST['voornaam']);
    $newsletterSubscriber->set('lastName', $_POST['achternaam']);
    $newsletterSubscriber->set('companyName', $_POST['beddrijfsnaam']);
    $newsletterSubscriber->set('emailAddress', $_POST['email']);
    $newsletterSubscriber->set('subscribed', 1);
    $saved = $newsletterSubscriber->save();

    $response = array('error_code'=>0, 
                      'message'=>'subscriber added'
                     );
    echo json_encode($response);
    exit;
}

in my scripts.js I have my ajax:

$.ajax({
    type: "POST",
    url: "connection.php",
    data: {param1: 'aaa'},
    dataType: JSON
})
.done( function(data){
        if(data.error_code == 0) {
           alert(data.message);
        }
    }
});

The error that I receive is:

SyntaxError: Unexpected token '}'. Expected ')' to end a argument list.

Can somebody see what I'm doing wrong?

Your JavaScript code has an error:

$.ajax({
    type: "POST",
    url: "connection.php",
    data: {param1: 'aaa'},
    dataType: JSON
})
.done( function(data){
        if(data.error_code == 0) {
           alert(data.message);
        }
//You had an extra } here.
});

Try the following: replace done with the success property of the jquery ajax

$.ajax({
    type: "POST",
    url: "connection.php",
    data: {param1: 'aaa'},
    dataType: JSON,
    success:function(data){
      if(data.error_code == 0) {
           alert(data.message);
        }
    }
});

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