0

Ajax call is not responding give me a empty result (PHP) code is properly working only issue i have is with ajax. I'll already check all the CDN is working fine

My html code :

<form method="post">
    <input type="hidden" name="product_id" id="product_id" value="<?= $id ?>" >
    <input type="hidden" name="user_id" id="user_id" value="<?= $_SESSION['id'] ?>">

    <textarea name="comment" id="comment" cols="30" rows="10"></textarea>
    <input type="hidden" name="rating" id="rating">
    <input type="submit" name="c_submit" id="c_submit">
</form>
<ol id="comment"> </ol>

My php code :

<?php
    include "../../functions/dbs.php";

    if (isset($_POST["c_submit"])){
        $product_id = $_POST['product_id'];     $user_id = $_POST['user_id'];
        $comment = $_POST['comment'];           $rating = $_POST['rating'];

        $query = "INSERT INTO user_profile (product_id,user_id,comment,ratting) values ('$product_id','$user_id','$comment','$rating')";
        print_r($query);exit();
        $sql=mysqli_query($con->connect(),$query);
    ?>

    <li class="box">
        <?= '<span class="email">' . $product_id. '</span>' ?>
        <?= '<span class="comment">' . $comment . '</span>' ?>
    </li>
<?php } ?>

My ajax code : If user can click on submit all the result that we have in input field will be shone in ol#comment.

$(function () {
    $("#c_submit").click(function() {
        var product_id = $("#product_id").val();    
        var user_id = $("#user_id").val();
        var comment = $("#comment").val();          
        var rating = $("#rating").val();

        var dataString = 'product_id =' + product_id + '&user_id=' + user_id + '&comment=' + comment + '&rating=' + rating;
        if (product_id == '' || user_id == '' || comment == '' || rating ==''){
            alert('Please Give Valid Details');
        }else {
            $.ajax({
                type: "POST",
                url : "include/comm.php",
                data : dataString,
                cache: false,
                success : function(html){
                    console.log(html);
                    $("ol#comment").append(html);
                    $("ol#comment li:last").fadeIn("slow");
                }
            });
        }
    });
});

Ignore :

"The quick, brown fox jumps over a lazy dog. DJs flock by when MTV ax quiz prog. Junk MTV quiz graced by fox whelps. Bawds jog, flick quartz, vex nymphs. Waltz, bad nymph, for quick jigs vex! Fox nymphs grab quick-jived waltz. Brick quiz "

Muhammad Usman
  • 357
  • 2
  • 14
  • 2
    check the developer tools console/network tab - you'll see that hitting a submit button will make a request - as you have no `action` attribute for the form, the request will be made to the current URL – Jaromanda X Dec 26 '17 at 07:20
  • 1
    There are 2 identical IDs in your page. **One** => ` – Nana Partykar Dec 26 '17 at 07:22
  • Handle `error` event of your Ajax and log the error to see what happened... – Aria Dec 26 '17 at 07:23
  • 2
    See @JaromandaX comment. You need to prevent submit default behaviour: `$("#c_submit").click(function(e) { e.preventDefault(); ... });` – A. Wolff Dec 26 '17 at 07:23
  • leave `print_r($query);exit();` – Alex Dec 26 '17 at 07:29
  • So there are several problems with your code as all we pointed... – Aria Dec 26 '17 at 07:32
  • And, from where `$email` is coming in this line `= '' ?>` ?? – Nana Partykar Dec 26 '17 at 07:32
  • Alex - Ajax don't post us on ( url : "include/comm.php" ) I was try your method before like i said we don't get any response – Muhammad Usman Dec 26 '17 at 07:32
  • You're not using an `action` attribute in the form tag so your either add one or add your php code in the same php url of the form (and remove `exit()`) – Alex Dec 26 '17 at 07:34
  • @Alex OP wants to send request using ajax, so no need to set `action` attribute of `form`. But his server side code is wrong too. There are many problems in his posted code that need to be fixed – A. Wolff Dec 26 '17 at 07:36

5 Answers5

3

I tried your code snippet and found several problems with it:

  1. Since you're using a , and you attach an event listener to the submit button and do not use preventDefault(), the button click will make the browser to send the form data without AJAX. I suggest you to use preventDefault() to prevent the synchronous process and use AJAX instead.
  2. The PHP code relies on the c_submit POST data which does not exist in the formed data the javascript is submitting. So PHP will ignore the if() block entirely. This is why you do not see the expected result. I suggest you either update the if condition or just use other variable.
  3. There is a typo in your javascript code, you included an excess whitespace in the dataString variable.
  4. I concur with Alex's suggestion to attach the AJAX event to the form submit event instead of attaching to a button in the form. It is a form submit after all.

My code suggestion:

$(function () {
    $("form").on('submit', function(e) {
        e.preventDefault();
        ...
        var dataString = 'product_id=' + product_id + '&user_id=' + user_id + '&comment=' + comment + '&rating=' + rating;
        ...
    });
});

For the PHP counterpart, assuming product_id data is always submitted, I suggest:

if (isset($_POST["product_id"])){
    ....
}
Wiguno
  • 66
  • 5
2

You must first prevent the default behavior of the click or submit event. You can do this by adding this line at the beginning of your event handler. Also, I never saw the way you called an anonym function using the $ sign of jQuery object. I will assume that this function is the root or the wrapper function for your whole application and I will show you how I am doing it and how people do it.

(function($) {
    $(document).ready(function() {

        $(document).on('submit', '#info_form', function(event) {
            event.preventDefault();
            // Add this line.

            var product_id = $("#product_id").val();
            var user_id = $("#user_id").val();
            var comment = $("#comment_input").val();
            var rating = $("#rating").val();

            var data = {
               product_id: product_id,
               user_id: user_id,
               comment: comment,
               rating: rating
            };

            if (product_id == '' || user_id == '' || comment == '' || rating == '') {
                alert('Please Give Valid Details');
            }
            else {
                $.ajax({
                    type: "POST",
                    url: "include/common.php",
                    data: data,
                    cache: false,
                    success: function(html) {
                        console.log(html);
                        $("ol#comment").append(html);
                        $("ol#comment li:last").fadeIn("slow");
                    }

                });
            }
        });
    });

})(window.jQuery);

As per the way you are listening to the submit event. I think the way you are doing it now, will cause some problems if you start changing the HTML content or manipulating the DOM related to the form itself. I prefer to use $(document).on('submit', "#my-form-id", function(e){}); this way the listener will be bound to the document not to the element itself. I don't know if this is a bad practice or not but it solved lots of my issues in the past. Also, I tend to wrap my event listeners code inside the $(document).ready(function(){}); function to avoid executing the code before the DOM tree finish loading or the needed libraries that I am going to be using in my app.

For the data also, because you are using a post request to send your data. You have to preserve the structure of your data in the way you want to access them in the backend. In your front-end code, you are concatenating your parameters using string concatenation which is wrong. The AJAX function in jQuery take the data and serialize them. So in your case you have to do it like follow:

 var product_id = $("#product_id").val();    
 var user_id = $("#user_id").val();
 var comment = $("#comment").val();
 var rating = $("#rating").val();

 var data = {
   product_id: product_id,
   user_id: user_id,
   comment: comment,
   rating: rating
 };

And then pass it to the data parameter or field in the ajax function object. You can find an example based on your solution here, and the code here.

mohessaid
  • 390
  • 2
  • 14
  • Ok, you can find the page here: https://ajax-the-rigthway.herokuapp.com and I will be updating the code here: https://github.com/mohessaid/ajax-the-right-way – mohessaid Dec 26 '17 at 08:40
1

Change your ol id to comment_answer or anything else you want because you already have comment id on your input.

<ol id='comment_answer'></ol>

you need to prevent the default behavior of form submit, right now the page should be getting refreshed when you call on submit button which should not be done so, for that just write return false; after the ajax call, and change ol#comment to ol#comment_answer in ajax success function

$(function () {
    $("#c_submit").click(function() {
        var product_id = $("#product_id").val();
        var user_id = $("#user_id").val();
        var comment = $("#comment").val();
        var rating = $("#rating").val();

        var dataString = 'product_id =' + product_id + '&user_id=' + user_id + '&comment=' + comment + '&rating=' + rating;
        if (product_id == '' || user_id == '' || comment == '' || rating ==''){
            alert('Please Give Valid Details');
        }else {
            $.ajax({
                type: "POST",
                url : "include/comm.php",
                data : dataString,
                cache: false,
                success : function(html){
                    console.log(html);
                    $("ol#comment_answer").append(html);
                    $("ol#comment_answer li:last").fadeIn("slow");
                }

            });
        }
        return false;
    });
});
Prateik Darji
  • 2,297
  • 1
  • 13
  • 29
1

Changes

1) IDs can't be same through out the page. a) <textarea name="comment" id="comment" & <ol id="comment"></ol>. Which is changed it to <ol id="show_comment"></ol>.

2) Since, no action is provided in the form and no e.preventDefault();, it will take current URL. For preventing it, add e.preventDefault(); in the script.

3) In include/comm.php file, first condition you are checking if (isset($_POST["c_submit"])){. No c_submit attribute is passed in ajax script. So, it is not enetering in the condition. Pass c_submit in ajax script.

4) In <?= '<span class="email">' . $email . '</span>' ?> this line.

Undefined Index $email

will come as no where $email is defined. So, check it. I've replaced it with $user_id

Form

<form method="post">
   <input type="hidden" name="product_id" id="product_id" value="<?= $id ?>" >
   <input type="hidden" name="user_id" id="user_id" value="<?= $_SESSION['id'] ?>">
   <textarea name="comment" id="comment" cols="30" rows="10"></textarea>
   <input type="hidden" name="rating" id="rating">
   <input type="submit" name="c_submit" id="c_submit">
</form>

<ol id="show_comment"></ol>

include/comm.php

<?php
include "../../functions/dbs.php";
if (isset($_POST["c_submit"])){
  $product_id = $_POST['product_id'];
  $user_id = $_POST['user_id'];
  $comment = $_POST['comment'];
  $rating = $_POST['rating'];

  $query = "INSERT INTO user_profile (product_id,user_id,comment,ratting) values ('$product_id','$user_id','$comment','$rating')";
  $sql= mysqli_query($con->connect(),$query);?>

  <li class="box">
    <?= '<span class="email">' . $user_id . '</span>' ?>
    <?= '<span class="comment">' . $comment . '</span>' ?>
  </li>
<?php }?>

Script

<script>
$(function () {
  $("#c_submit").click(function(e) {

    e.preventDefault();

    var product_id = $("#product_id").val();
    var user_id = $("#user_id").val();
    var comment = $("#comment").val();
    var rating = $("#rating").val();

    if (product_id === '' || user_id === '' || comment === '' || rating === ''){
      alert('Please Give Valid Details');
    } else {
      $.ajax({
        type: "POST",
        url : "include/comm.php",
        data : {
          product_id : product_id, user_id : user_id, comment: comment, rating:rating,
          c_submit: true
        },
        cache: false,
        success : function(html){
          console.log(html);
          $("ol#show_comment").append(html);
          $("ol#show_comment li:last").fadeIn("slow");
        }
      });
    }
  });
});
</script>

Quick Links

  1. Can multiple different HTML elements have the same ID if they're different elements?
  2. preventDefault() Event Method
Nana Partykar
  • 10,556
  • 10
  • 48
  • 77
0

Until you don't echo the output in PHP, response will be blank.

Take the below code in a variable and echo the output:

$output = '<li class="box">
            '<span class="email">' . $email . '</span>'
            '<span class="comment">' . $comment . '</span>'
        </li>';

and echo the output : echo $output

Also in JS ajax content type should be html/text as you are sending html content in response.

Vivek Tankaria
  • 1,301
  • 2
  • 15
  • 35