Post php response in div using ajax not working

Hi, I am currently working on a project. When a user submits a form, he loads the response in a div, rather than loading a new page. I looked at other examples of the ajax form working together with PHP online, but this did not help me solve my problem. (I'm new to this).

When I click the "Send" button, instead of sending a response to the same page and sending an email to the selected email address, it leads me to a php file and repeats the response, but does not send any messages.

Can anyone see where this is happening?

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 separate file called mailer.php) I am trying to return the PHP $ response variable and return to 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 your help!

+4
4

:

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

javascript ( # -, #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>

PHP:

<?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; 

?>
+1

, ,

- "-", JQ "contactform".

$("#contactform")

$("#contact-form")
+2

This is because you are calling the post function, not ajax.

try the following:

$.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 answer in json

return json_encode (answer);

0
source

echo json_encode($response) at the end of the php function

0
source

Source: https://habr.com/ru/post/1620379/


All Articles