0

I tried many example from stackoverflow.com jQuery ajax success error

I pick code from this examle enter image description here

but always gives me error.

whenever i run below code if ajax code error then ajax shows error message but when php have error code ajax always show success: function ( data ) code.

as i know data.status == 'success' not comparing from php so my code gives error

i know this question is duplicate but i saw all questions from stackoverflow these not resolve my problem so i post again

please help

AJAX CODE

 $(document).ready(function () {
    $(function () {
        $('.contactf').submit(function (e) {
            e.preventDefault();
            if (!contactvalid())
                return false;
            $(this).find(":submit").prop("disabled", true);
            $('#gif').css('display', 'block');
            var form = $(this);
            var post_url = 'contactmail1.php';
            var post_data = form.serialize();
            $.ajax({
                type: 'POST',
                url: post_url,
                data: post_data,
                success: function (data) {
                    if (data.status == 'success') {
                        alert(data);
                    } else if (data.status == 'error') {
                        alert(data);
                    }
                },
                error: function (data) {
                    alert('failed client side');
                }
            });
        });
    });
});

PHP

<?php

//
header('Content-type: application/json');

if ( $_SERVER[ 'REQUEST_METHOD' ] == 'POST' ) {

    require 'phpmailer/PHPMailerAutoload.php';
    $name = $_POST[ 'Name' ];
    $email = $_POST[ 'Email' ];
    $phone = $_POST[ 'number' ];
    $sub = $_POST[ 'contact_subject' ];
    $msg = $_POST[ 'Message' ];


    if ( !( isset( $_POST[ 'Name' ] )and isset( $_POST[ 'Email' ] )and isset( $_POST[ 'number' ] )and isset( $_POST[ 'contact_subject' ] )and isset( $_POST[ 'Message' ] ) ) ) {
        echo "Some Field is Blank";
    } else {


        $mail = new PHPMailer;

        $mail->setFrom( $email, $name );


        $mail->addAddress( 'mail@gmail.com', 'Inderjeet' );

        $mail->Subject = 'Mail from site';

        $mail->msgHTML( '<html><body><table border=0 width=554><tr><td colspan=2><p><b>Enquiry from Contact Page Thorsoncne.com</b><br><br></p></td></tr><tr><td colspan=2 class=text4>FORM submitted at ' . date( 'd F Y h:i:s A' ) . '<br></td></tr>   
<tr><td width=200 class=text3>Name :</td><td class=text3>' . $name . '</td></tr>   
<tr><td>Email Id :</td><td>' . $email . '</td></tr>   
<tr><td>Phone/Mobile :</td><td>' . $phone . '</td></tr>   
<tr><td>Subject :</td><td>' . $sub . '</td></tr>   
<tr><td>Message :</td><td>' . $msg . '</td></tr>   
</table></body></html>' );

        if ( !$mail->send() ) {


            $response_array['status'] = 'failed';
            echo "Mailer Error: " . $mail->ErrorInfo;
            echo json_encode($response_array);

        } else {
            $response_array['status'] = 'success';
            echo json_encode($response_array);
            echo "Query Submitted";

        }
    }
}
Aravind Cheekkallur
  • 3,157
  • 6
  • 27
  • 41
Inderjeet
  • 1,488
  • 2
  • 17
  • 30
  • 3
    Remove `echo "Query Submitted";` after `echo json_encode($response_array);` – B. Desai Sep 27 '17 at 11:21
  • dont use screenshots, copy the code into the question please – endo.anaconda Sep 27 '17 at 11:22
  • 1
    And JSON encode `"Some Field is Blank";` or use $response_array['status'] = 'blank'; – mplungjan Sep 27 '17 at 11:22
  • And add `dataType: "json"` to the post – mplungjan Sep 27 '17 at 11:25
  • you have to encode the whole response, not just bits of it, otherwise the final result that comes back to the client will not be valid JSON. The strings you're currently outputting directly via "echo" need incorporating into the encoded object instead (or removing, if they're superfluous). You didn't say what error it's giving you but I guess its something about invalid JSON. – ADyson Sep 27 '17 at 11:27
  • Read and reply on @B.Desai comment – Niklesh Raut Sep 27 '17 at 11:27
  • If you look in your browser's network tab (in the dev tools) to examine the ajax request, you can easily see the response and whether it's valid JSON or not. Yours will be part JSON and part raw string, which confuses the browser, it doesn't know how to interpret it. – ADyson Sep 27 '17 at 11:28
  • @B.Desai i removed all echo from php (excluding echo json_encode($response_array); ) now alert show [object object] – Inderjeet Sep 27 '17 at 11:30
  • so now your code working. if you want to alert message then do `alert(data.status);` – B. Desai Sep 27 '17 at 11:34
  • @B.Desai Very Big Thanx to you its work... – Inderjeet Sep 27 '17 at 11:42

1 Answers1

1

Change your Java script code - Add dataType: "json"

$(document).ready(function() {
  $(function() {
    $('.contactf').submit(function(e) {
      e.preventDefault();
      if (!contactvalid()) return false;
      $(this).find(":submit").prop("disabled", true);
      $('#gif').css('display', 'block');
      var form = $(this);
      var post_url = 'contactmail1.php';
      var post_data = form.serialize();
      $.ajax({
        type: 'POST',
        url: post_url,
        dataType: "json",
        data: post_data,
        success: function(data) {
          if (data.status == 'success') {
            alert(data);
          } else if (data.status == 'error') {
            alert(data);
          }
        },
        error: function(data) {
          alert('failed client side');
        }
      });
    });
  });
});

And Remove echo "Query Submitted"; after echo json_encode($response_array);

Sanjay Chaudhari
  • 420
  • 4
  • 13