简体   繁体   中英

post php response into div using ajax not working

Hi I am currently working on a project. When a user submits a form, it loads a response into a div rather than loading a new page. I have looked at other examples of an ajax form working along with PHP online but it didn't help me solving my problem. (I am rather new to this).

When I click submit, instead of posting the response onto the same page and sending an email to the chosen email address, it takes me to the php file and echo the response there, but does not send any email.

Can anyone see where this is going wrong?

Form code:

<form name="contactform" id="contact-form" action="mailer.php">

            <input type="text" class="textbox" name="name" value="Name" required="required" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Name';}">

            <input type="text" class="textbox" name="email" value="Email" required="required" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Email';}">

            <textarea name="message" value="Message:" required="required" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Message';}">Message</textarea>

           <input type="submit" value="Send Now">

</form>
                    <div id="response"></div>

Javascript code:

<script>
 $("#contactform").submit(function(event) 
 {
     /* stop form from submitting normally */
     event.preventDefault();

     /* get some values from elements on the page: */
     var $form = $( this ),
         $submit = $form.find( 'button[type="submit"]' ),
         name_value = $form.find( 'input[name="name"]' ).val(),
         email_value = $form.find( 'input[name="email"]' ).val(),
         message_value = $form.find( 'textarea[name="message"]' ).val(),
         url = $form.attr('action');

     /* Send the data using post */
     var posting = $.post( url, { 
                       name: name_value, 
                       email: email_value, 
                       message: message_value 
                   });

     posting.done(function( data )
     {
         /* Put the results in a div */
         $( "#response" ).html(data);

     });
});
</script>

PHP code: (my php is stored in a seperate file called mailer.php) I am trying to get the PHP $response variable to be posted back and placed into the response div.

<?php


    // Get the form fields and remove whitespace.
    $name = $_POST["name"];
    $email = $_POST["email"];
    $message = $_POST["message"];

    $to = "your-emailaddresshere@email.com";
    $subject = "New DPS Email from $name";

    // Build the email content.
    $email_content = "Name: $name\n";
    $email_content .= "Email: $email\n\n";
    $email_content .= "Message:\n$message\n";

    // Build the email headers.
    $email_headers = "From: $name <$email>";

    $mailed = (mail($to, $subject, $email_content, $email_headers));

    if( isset($_POST['ajax']) )
    $response = ($mailed) ? "1" : "0";
    else
    $response = ($mailed) ? "<h2>Thank You! Your message has been sent.</h2>" : "<h2>Oops! Something went wrong and we couldn't send your message.</h2>";

    echo $response; 

?>

Thanks in advance for any help!

correct this and report what happened,

your form ID is "contact-form" and your JQ selector have been set for "contactform".

$("#contactform")

to

$("#contact-form")

Here is what you can do: The Form Code

<form name="contactform" id="contact-form">
    <!--Your form elements here -->
</form>

The javascript code (Use #contact-form and not #contactform )

<script>
$("#contact-form").submit(function(event) 
{
 /* stop form from submitting normally */
 event.preventDefault();

 /* get some values from elements on the page: */
 var $form = $( this ),
     $submit = $form.find( 'button[type="submit"]' ),
     name_value = $form.find( 'input[name="name"]' ).val(),
     email_value = $form.find( 'input[name="email"]' ).val(),
     message_value = $form.find( 'textarea[name="message"]' ).val(),
     url = 'your_url_here';

 /* Send the data using post */
 var posting = $.post( url, { 
                   name: name_value, 
                   email: email_value, 
                   message: message_value 
               });

 posting.done(function( data )
 {
     /* Parse JSON */
     var response = JSON.parse(data);
     $("#response").html(response.msg);

    });
 });
</script>

Your PHP Code :

<?php


// Get the form fields and remove whitespace.
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];

$to = "your-emailaddresshere@email.com";
$subject = "New DPS Email from $name";

// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";

// Build the email headers.
$email_headers = "From: $name <$email>";

$mailed = mail($to, $subject, $email_content, $email_headers);

if( $mailed )
$response = json_encode(array("status"=>true,"msg"=>"<h2>Thank You! Your message has been sent.</h2>"));
else
$response = json_encode(array("status"=>false,"msg"=>"<h2>Oops! Something went wrong and we couldn't send your message.</h2>"));

echo $response; 

?>

It is because you're calling post function, not ajax.

try this:

$.ajax({
   url: <your_url>,
   type:'GET',
   data: {'name': name_value, 'email' : email_value, 'message': message_value},
   success: function(data){
        yourdivcontent =  eval(data)
        $( "#response" ).html(yourdivcontent);
   }, 
   error: function(){
        console.log("error");
   }
})

In your php function, just encode your response in json

return json_encode(response);

在php函数结束时echo json_encode($response)

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