简体   繁体   中英

Converting PHP contact form to AJAX

I currently am using the sms service twilio to send a message to users with details. The form submits and delivers when submitted using action and post method whilst submitting. I would like to change this to an AJAX submitted form. Any ideas please? I have included some code below as of how it currently works:

**** Contact form ****

<form action="sendsms.php" method="post" id="sms">
     <input type="text" name="name" id="name" value="Sam"/>
     <input type="phone" name="phone" id="phone" value="0000000000"/>
     <textarea name="message" style="width: 500px; height: 300px;"> Test Message</textarea>
        <input type='submit' value='submit'/>
    </form>

**** PHP ****

<?php
    if($_POST)
    {

        require "Services/Twilio.php";


        $AccountSid = "ACaa1c********";
        $AuthToken = "ae6c269********";


        $client = new Services_Twilio($AccountSid, $AuthToken);

        $from = '+44**********';
        $name = $_POST['name'];
        $phone = $_POST['phone'];

        // Send a new outgoing SMS */
        $body = htmlspecialchars($_POST['message'].$name );
        $client->account->sms_messages->create($from, $phone, $body );
        echo "Sent message to $name";
    }
?>

**** AJAX ****

$('#sms').submit(function(event) {
    // Stop the browser from submitting the form.
    event.preventDefault();
    //get input field values
    var user_name       = $('input[name=name]').val(); 
    var user_phone      = $('input[name=phone]').val();
    var user_message    = $('textarea[name=message]').val();

    var proceed = true;

    if(proceed) 
               {
                 //data to be sent to server
                 post_data = {'userName':user_name, 'userPhone':user_phone, 'userMessage':user_message};

                 //Ajax post data to server
                 $.post('sendsms.php', post_data, function(data){  

                     alert(data);


                        }).fail(function(err) {  //load any error data
                            $("body").hide().html('<div class="error">'+err.statusText+'</div>').slideDown();
                        });
                    }          
                    return true;
                });
 $(function(){
                $('#sms').submit(function(e){
                    e.preventDefault();

                    var d = $(this).serialize();

                    $.ajax({
                        type        :       'post',
                        url         :       'sendsms.php',
                        data        :       d
                    }).done(function(data){
                       alert('done');
                    }).fail(function(x,y,z){
                        alert('error');
                    });

                });
            });

its that easy.

Make use of jquery to get the action and data from the form directly, with attr('action') and serialize() :

 $(function(){
    $('#sms').submit(function(event) {
        event.preventDefault();

        $.post($(this).attr('action'), $(this).serialize(), function(data){
            console.log(data); //alert(data);
        }).fail(function(err){
            console.log(err); //alert(err);
        });
    });
});

As noted, alert is a poor method of debugging. All modern browsers have a javascript console (Ctrl + Shift + J in google chrome, or rightclick > inspect element to bring up full dev tools). console.log() will send your data to the console. Other javascript errors will also show.

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