0

I know this question has been asked a lot before but i've tried all the solutions and nothing worked for me so my problem is that i can not load json response from the server using ajax i have my script.js in a js folder and my sendMail.php in includes folder and the index.php is in root folder also when i submit some infos the status is 200 means all ok but also i can not check them with my php code because of json response

index.php

<!DOCTYPE html>
<html>
<head>
    <title>Booking</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="js/script.js"></script>
</head>
<body>
    <form action="includes/sendMail.php"  method="POST" name="reservation-form"  id="reservation-form">
        <div>
            <select class="select-dropbox" name="mail-hour">
                <option value="" disabled selected>Hour</option>
                <option value="1">1</option>
                <option value="2">2</option>
            </select>
        </div>

        <div>
            <input type="text" name="mail-phone" placeholder="Phone Number"
            >
        </div>
        <div>
            <input type="text" name="mail-email" placeholder="Email Address" >
        </div>
        <div>
            <textarea name="mail-msg" placeholder="Your Message"  ></textarea>
        </div>
        <div id="check-form">
        </div>
        <div>
            <button id="mail-submit" name="mail-submit" type="submit">BOOK A TABLE</button>
        </div>
    </form>
</body>
</html>

script.js

$(document).ready(function(){
  $('#mail-submit').click(function(event){
    event.preventDefault();
    $.ajax({
      contentType: "application/json; charset=utf-8",
      dataType: 'JSON',
      url: 'includes/sendMail.php',
      type: 'POST',
      data: $('#reservation-form').serialize(),
      beforeSend: function(xhr){
        $('#mail-submit').html('SENDING...');
      },
      success: function(response){
       if(respo,se){
        alert(response);
        if(response['signal'] == 'ok'){
         $('#check-form').html('<div>'+ response['res-msg']  +'</div>');

       }
       else{
        $('#check-form').html('<div>'+ response['res-msg'] +'</div>');
      }
    }
  },
  error: function(xhr, status, thrown){
    alert("xhr: "+xhr+" status: "+status+" thrown: "+thrown);
    $('#check-form').html('<div>An Error occurs. Please try again.</div>');
  },
  complete: function(){

    $('#mail-submit').html('BOOK A TABLE');
  }
});
  });
});

sendMail.php

<?php
if (isset($_POST['mail-submit'])) {
    $hour = trim($_POST['mail-hour']);
    $phone = trim($_POST['mail-phone']);
    $email = trim($_POST['mail-email']);
    $message = trim($_POST['mail-msg']);
    if($hour != null && $phone != null && $email != null){
        if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $signal = 'bad';
            $msg = 'Invalid email. Please check';
        }
        else {
            $signal = 'ok';
            $msg = 'Form submitted';
        }
    }
    else{
        $signal = 'bad';
        $msg = 'Please fill in all the fields.';
    }
    $data = array(
        'signal' => $signal,
        'res-msg' => $msg
    );
    echo json_encode($data);
}   
?>

JSON ERROR

UPLOADING DATA IS FINE

blabla
  • 69
  • 8
  • Can you help me please i really need this code to be fixed today and it doesn't work for me – blabla Aug 25 '18 at 17:16
  • What’s the JSON payload you are trying to send? – dj079 Aug 25 '18 at 17:27
  • i'm trying to send `$data['signal']` and `$data['res-msg']` – blabla Aug 25 '18 at 17:30
  • You don't need `var response=parseJSON(res);` when you have `dataType: 'JSON'` ... the .ajax method is already returning `res` as an object to use in the `success` callback. Also due to telling ajax what to expect, you really don't need `header("Content-Type: application/json", true);` at all in the php side. – IncredibleHat Aug 25 '18 at 17:37
  • @IncredibleHat i've removed all the code you said and still not working – blabla Aug 25 '18 at 17:40
  • Did you change the variable name reference as well? Change `success: function(res){` to `success: function(response){` ... so you are using the right variable name. If thats "not working" ... then you need to provide better information about what "is not working". Like, debug lines from browser devtool console and network response tabs, and also making sure your php is returning nothing BUT a json-correct string. Which you have not provided in your question. – IncredibleHat Aug 25 '18 at 17:43
  • Your button does not have a value consequently on the server side $_POST["mail_submit"] is never set and your conditional code never runs. In the screenshot of your devtools we see the response is 0 bytes which is consistent with this analysis. – James Aug 25 '18 at 18:16

2 Answers2

1

You basically need a different serialization method for your form data. Something similar mentioned here: Convert form data to JSON object

Below is the code that you should use for your JS. Notice serializeObject being used instead of serialize. I was not able to execute the PHP code, but the serialization issue you are facing will be fixed now and that should fix your PHP code as well.

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};


$(document).ready(function(){
  $('#mail-submit').click(function(event){
    event.preventDefault();
    var d = $('#reservation-form').serializeObject();
    d = JSON.stringify(d);
    $.ajax({
      contentType: "application/json; charset=utf-8",
      dataType: 'JSON',
      url: 'includes/sendMail.php',
      type: 'POST',
      data: d,
      beforeSend: function(xhr){
        $('#mail-submit').html('SENDING...');
      },
      success: function(res){
       if(res){
        var response=parseJSON(res);
        alert(response);
        if(response['signal'] == 'ok'){
         $('#check-form').html('<div>'+ response['res-msg']  +'</div>');

       }
       else{
        $('#check-form').html('<div>'+ response['res-msg'] +'</div>');
      }
    }
  },
  error: function(xhr, status, thrown){
    alert("xhr: "+xhr+" status: "+status+" thrown: "+thrown);
    $('#check-form').html('<div>An Error occurs. Please try again.</div>');
  },
  complete: function(){

    $('#mail-submit').html('BOOK A TABLE');
  }
});
  });
});

Working HTML/JS code here: https://jsfiddle.net/7jm568ay/5/

Hope this helps!

dj079
  • 1,389
  • 8
  • 14
  • That's 404 error, cause it did not find the .php file. :) I just updated the code there with an alert for your reference: https://jsfiddle.net/7jm568ay/6/ – dj079 Aug 25 '18 at 18:06
1

I've tested your code and I think problem in your php script (sendMail.php) at line: 2 (if (isset($_POST['mail-submit']))), where "mail-submit" was not serialized (**As serialize does not include submit button value), that's why code was not fulfilling first if condition and giving error. So, if you use "mail-email" instead of "mail-submit" ((if (isset($_POST['mail-email'])))), I think it'll work.

Or you can change your script a little bit like below:

index.php

        <div>
        <input type="hidden" id="mail-submit-hidden" name="mail-submit" value="0" >
        <button id="mail-submit" type="submit">BOOK A TABLE</button>
    </div>
</form>

script.js

event.preventDefault();
$('#mail-submit-hidden').val('1');
$.ajax({

Please have a try.

rony2k6
  • 75
  • 5