lundi 1 décembre 2014

Use ajax to process form


Vote count:

0




I am working on a form where visitors can subscribe to a mailing list.


The code is:



function subscribe_form() {
global $my_subme;

$form = '';
$msg = '';

if ( isset( $_GET['status'] ) ) {
if ( 'subscribed' === $_GET['status'] ) {
$msg = __( 'Thank you for confirming your subscription', 'subme' );
} else if ( 'unsubscribed' === $_GET['status'] ) {
$msg = __( 'You have successfully unsubscribed.', 'subme' );
} else {
$msg = __( 'Sorry, but something went wrong.', 'subme' );
}

$form .= '<p>';
$form .= esc_html( $msg );
$form .= '</p>';
} else {
/* Process the form when submitted */
if ( ( isset( $_POST['subscribe'] ) || isset( $_POST['unsubscribe'] ) ) && isset( $_POST['source'] ) && 'widget' === $_POST['source'] ) {
/* Check nonce */
if ( ! isset( $_POST['subme_widget_nonce'] ) || ! wp_verify_nonce( $_POST['subme_widget_nonce'], 'subme_widget' ) ) {
return;
}

if ( ! isset( $_POST['email'] ) ) {
return;
}

if ( ! $my_subme->is_valid_email( strtolower( $_POST['email'] ) ) ) {
$msg = __( 'Sorry, but this does not seem like a valid email address.', 'subme' );

} else {
if ( isset( $_POST['subscribe'] ) ) {
$msg = $my_subme->subscribe( $_POST['email'] );
} else {
$msg = $my_subme->unsubscribe( $_POST['email'] );
}
}
}

$form .= '<form method="post">';
$form .= wp_nonce_field( 'subme_widget', 'subme_widget_nonce', true, false );
$form .= '<input type="hidden" name="source" value="widget" />';
$form .= '<p>';
$form .= __( 'Your email address:', 'subme' ) . '<br />';
$form .= '<input type="text" name="email" /><br /><br />';
$form .= '<input type="submit" name="subscribe" value="' . __( 'Subscribe', 'subme' ) . '" />';
$form .= ' ';
$form .= '<input type="submit" name="unsubscribe" value="' . __( 'Unsubscribe', 'subme' ) . '" />';
$form .= '</p>';
$form .= '</form>';

if ( strlen( $msg ) > 0 ) {
$form .= '<p>';
$form .= esc_html( $msg );
$form .= '</p>';
}
}

echo $form;
echo '</div>';

}


subscribe_form();


How do I change this code so that it is processed using ajax? As you can see, currently it is a simply page refresh when user submits the form.



asked 1 min ago







Use ajax to process form

Aucun commentaire:

Enregistrer un commentaire