0

I am good in php and html, however my I am still learning js. And I am stuck on creating a form which will submit form data to be inserted in mysql without loading page(ajax).

Below is my form:

<form id="panel1" action="rep-submit.php" method="post">
                                 <div class="form-group">
                                    <input type="text" name="rep_author" id="rep_author" placeholder="Your Name" class="form-control">
                                 </div>
                                <div class="form-group">
                                    <input type="email" name="rep_email" id="rep_email" placeholder="Your Email" class="form-control">
                                 </div>
                                 <div class="form-group">
                                      <textarea class="form-control" id="rep_comment" name ="rep_comment"rows="3" placeholder="Your comment"></textarea>
                                </div>
                                    <input type="hidden" value="<?php echo $comment_id; ?>" id ="rep_to">
                                    <input type="hidden" value="<?php echo $postp_id; ?>" id ="rep_post_id">
                               <input id="repsub" type="button" class="btn btn-primary" value="Submit">
                               </form>

Below is my post.js I took a lot of online guide to make such js codes :P, it took 1 day to complete still not working. Please help

$(document).ready(function(){
$("#repsub").on('click', function(event) {
event.preventDefault();
                            $("#repsub").attr("disabled", "disabled");
                            var rep_author = $('#rep_author').val();        
                            var rep_email = $('#rep_email').val();      
                            var rep_comment = $('#rep_comment').val();
                            var rep_to = $('#rep_to').val();
                            var rep_post_id = $('#rep_post_id').val();
                            var url = $("#panel1").attr("action");
                            alert(url);
                            $.ajax({
                                url: url, 
                                type: "POST",
                                data: {
                                rep_author: rep_author, 
                                rep_email: rep_email,
                                rep_comment: rep_comment,
                                rep_to: rep_to,
                                rep_post_id: rep_post_id
            },
            cache: false,   
            success: function(dataResult){
                var dataResult = JSON.parse(dataResult);    
                document.write(rep_comment);    

                if(dataResult.statusCode==200){
                        console.log("success");
                        $("#repsub").removeAttr("disabled");
                        $('#panel1').find('input:text').val('');
                        alert("success");
                        }
                        else if(dataResult.statusCode==201){                     
                        alert("Error occured !");                   
                        }
                        }

                            });
                            });
                            });

Finally below is rep-submit.php

    <?php include_once("includes/connection.php");
if(isset($_POST['rep_submit']))
    {
        global $connection;
        connection();
        $author = $_POST['rep_author'];
        $email = $_POST['rep_email'];
        $comment = $_POST['rep_comment'];
        $rep_to = $_POST['rep_to'];
        $post_id = $_POST['rep_post_id'];
       $com_rep = "yes,".$rep_to;

        $query = "INSERT INTO comment(comment_post_id,comment_author,comment_email,comment_content,comment_reply) ";
        $query .= "VALUES('$post_id','$author','$email','$comment','$com_rep')";
        $result = mysqli_query($connection, $query);

        if(!$result)
            {
                echo "There is some issue posting your reply on that comment<br>";
                echo mysqli_error($connection);
                echo json_encode(array("statusCode"=>201)); 
        }   
            else
            {
                echo "reply sucessfully sent for approval";

        $query = "SELECT * FROM comment WHERE comment_id = '$rep_to'";
        $result = mysqli_query($connection, $query);
        $row = mysqli_fetch_assoc($result);
        $com_count = $row['comment_reply_count'];
        $new_count = $com_count + 1;
        $query = "UPDATE comment SET ";
        $query .= "comment_reply_count = '$new_count' ";
        $query .= "WHERE comment_id = '$rep_to'";
        $result = mysqli_query($connection, $query);
        echo json_encode(array("statusCode"=>200));
        }   


    }
?>
Aman Singh
  • 21
  • 1
  • 6
  • Which specific part is causing problems? What's going wrong? – showdev Jul 19 '19 at 21:50
  • i suspect the javascript function isn't called please try – nbk Jul 19 '19 at 22:19
  • 1
    Thank you so much for assist replies, so form is displaying, when i click submit button it's css attribute changes to disable as defined in js but doesnt execute what is written in rep-submit.php, I believe that success: part is not working in ajax js. For sql injection this is just learning files(localhost) and will soon add escape real strings. I added **#**repsub but it is not working :( – Aman Singh Jul 19 '19 at 22:28
  • I'm curious whether the AJAX is firing and the PHP file is being called. Does the `alert()` fire? Does `success` fire? Do you see the PHP file being requested in your browser console? Are there any associated errors? – showdev Jul 19 '19 at 23:00
  • When i click submit i see that form fields are submitted but there is no response. That alert(url) works great. On success part i added Document.write to test whether it works or not but it didnt worked – Aman Singh Jul 19 '19 at 23:10

1 Answers1

1

Your code is not working as intended because you need to call the preventDefault() method of the click event your Javascript code is listening to.

You have to change this part of your code:

$("#repsub").on('click', function() {

to this:

$("#repsub").on('click', function(event) {
    event.preventDefault();

In this way, you prevent the default behavior of your submit button #repsub, which is to submit the #panel1 form.

Also, you have to add rep_submit: 1 to the data object you send via AJAX:

data: {
    rep_author: rep_author, 
    rep_email: rep_email,
    rep_comment: rep_comment,
    rep_to: rep_to,
    rep_post_id: rep_post_id,
    rep_submit: 1 // Add this
},

Most of your PHP code wasn't executed because the rep_submit element in the AJAX request was missing: isset($_POST['rep_submit']) returned false.

In addition, there is an important error in your HTML code: your #repsub input is of type submit.. You need to remove the dot by changing it to submit in order to correctly show a form submit button.

The last problem is that in the PHP, in case of success, you are echoing some text before echoing the final json-encoded data. You have to remove the line echo "reply sucessfully sent for approval";. This way, your JS code will be able to parse the response and show the "success" alert.


Other considerations

I think it would be better if you handle the submit event of your form instead of the click event of your submit input. To do this, you should simply change your code this way:

$("#panel1").on('submit', function(event) {
    event.preventDefault();

You should't use document.write(), especially if the code which calls it is asynchronous (it will overwrite all the page content). Use Node.insertBefore(), Node.appendChild() or JQuery's append() and prepend() methods.


You should be outputting data from your PHP in a consistent way. If you want to use JSON, then always return correct JSON data and don't use echo for other purposes. In this case, to keep it simple, you could output this data on success:

{
    "success": true
}

In case of error, output this:

{
    "success": false,
    "error_message": "Your error message"
}

In this way, you will be able to handle your server responses in a simple and clean way.


Dharman's comment is correct: you need to prevent SQL injection. You can find some good information on how to do it here.


Useful links

  • Thanks for your reply, I have updated my code in ky question as you said but it is still same as it was before, I have taken a screen recording you can see it here https://gamerli.tk/2019/07/19/video-ajax-form-submission/ sorry i am currently in mobile – Aman Singh Jul 19 '19 at 22:56
  • I see, thanks for the video! I found other problems I didn't notice before and updated my answer, everything should be OK now – mat-owczarek Jul 19 '19 at 23:23
  • Ok now it is inserting data in database :) but that if(dataResult.statusCode==200) doesnt get executed, i tried else (which js has to do if any condition fails) but it didnt do anything. When I click submit button becomes disabled and data gets inserted into database and there is no alert box coming – Aman Singh Jul 20 '19 at 04:24
  • It's a problem with the data you're outputting in the PHP. Check my updated answer :) – mat-owczarek Jul 20 '19 at 11:27
  • Thank you so much it worked, it will help me learning js, I want to give you upvote but whenever i click up arrow it rolls back -_- , i think its because reputation :P – Aman Singh Jul 20 '19 at 11:57
  • I'm happy that we managed to solve the problem :) You don't need to upvote the answer, just [accept it](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work), so others will know that the problem is solved – mat-owczarek Jul 20 '19 at 12:03