1

Reading and re-reading I do not know why 2 variables do not get passed but one does. JQuery Ajax call (LAMP env):

<script type="text/javascript">
$(document).ready(function() {
   $('#postComment').click(function(e) {
        e.preventDefault();
        var articleId = $('#articleId').val();
        var commTitle = $('#commTitle').val();
        var commBody = $('#commBody').val();
         alert(articleId + commTitle + commBody);
        $.ajax({
            type: "POST",
            url: 'https://www.d o m a i n.com/content/inc/postComment.php',  // removed actual domain for this posting
            data: {"articleId": articleId},   // this var does not pass to postComment.php
            data: {"commTitle": commTitle},  // this var does not pass to postComment.php
            data: {"commBody": commBody},    // this var DOES pass to postComment.php        
            success: function(response)
            {
                $('#responseComm').css('color', 'green');
                $('#responseComm').val('Comment submitted successfully!');
                $("#response").html('There is outcome while submit' + commTitle + '<p>' + commBody);
            }
        });
    });
 });
 </script>

The HTML is:

                    <form action="#">
                        <div class="row g-4">
                            <div class="col-lg-6">
                                <input type="hidden" name="articleId" id="articleId" value="<?php echo $articleid; ?>">
                                <input type="text" class="form-control py-3" placeholder="<?php echo $_SESSION['username']; ?>" disabled>
                            </div>
                            <div class="col-lg-6">
                                <input type="text" class="form-control py-3" placeholder="<?php echo $articleTitle; ?>" value="<?php echo $articleTitle; ?>" name="commTitle" id="commTitle">
                            </div>
                            <div class="col-12">
                                <textarea class="form-control" name="commBody" id="commBody" cols="30" rows="7" placeholder="Write Your Comment Here"></textarea>
                            </div>
                            <div class="col-12">
                                <button class="form-control btn btn-primary py-3" type="button" id="postComment">Submit Now</button>
                            </div>
                        </div>
                    </form>

The variables are not being used elsewhere on the script

both above code snippets are in the same script

Thanks ahead of time?

2
  • alert(articleId + commTitle + commBody); all 3 variables are output in this alert file appropriately Commented Nov 2, 2024 at 23:27
  • 3
    There can only be one data: in your ajax call. Try this: data: { articleId: articleId, commTitle: commTitle, commBody: commBody }. instead of the three data: you have now. Commented Nov 2, 2024 at 23:48

4 Answers 4

2

The issue with your Ajax call lies in how you've defined the data parameter in the $.ajax() function. When you define multiple data objects consecutively, only the last one will be sent in the request, as each new assignment to data overrides the previous one.

To send multiple variables in the Ajax call, you should combine all the data into a single object, like this:

$(document).ready(function() {
   $('#postComment').click(function(e) {
        e.preventDefault();
        
        var articleId = $('#articleId').val();
        var commTitle = $('#commTitle').val();
        var commBody = $('#commBody').val();
        
        alert(articleId + " " + commTitle + " " + commBody);
        
        $.ajax({
            type: "POST",
            url: 'https://www.d o m a i n.com/content/inc/postComment.php',
            data: {
                "articleId": articleId,
                "commTitle": commTitle,
                "commBody": commBody
            },
            success: function(response) {
                $('#responseComm').css('color', 'green');
                $('#responseComm').val('Comment submitted successfully!');
                $("#response").html('There is outcome while submit: ' + commTitle + '<p>' + commBody);
            }
        });
    });
});
Sign up to request clarification or add additional context in comments.

Comments

2

Instead of assigning data multiple times, you should create a single data object that includes all three parameters, like this:

data: { "articleId": articleId, "commTitle": commTitle, "commBody": commBody },

This is necessary because each time you assign data, you overwrite the previous assignment, which is why only the last parameter appears and the other two do not.

Comments

1

Given that your form has elements with the same name as the keys you want to send using AJAX, the simplest approach is to:

  1. add an id to the form, so jQuery can identify it. For example, "new-article-form".

  2. replace the three data: lines with:

    data: $("#new-article-form").serialize()

to use jQuery's serialize() function, as described here.

Comments

-2
<script type="text/javascript">
$(document).ready(function() {
$(document).on('click', '#postComment', function(e){
e.preventDefault();
var articleId = $('#articleId').val();
var commTitle = $('#commTitle').val();
var commBody = $('#commBody').val();
if(articleId ! = 0){ 
var formData = { action: "updateComment", articleId: articleId, commTitle: commTitle, commBody: commBody };
} 
else { 
var formData = { action: "addComment", commTitle: commTitle, commBody: commBody };
}

//alert(articleId + commTitle + commBody);
$.ajax({
type: "POST",
url: 'https://www.d o m a i n.com/content/inc/postComment.php',       
data:formData,
dataType: 'json',
success:function(response){
console.log(response);
if(response.status == 1){ alert(response.message); console.log(response.message); }
else { alert(response.message); console.log(response.message); }
}
});
});
});
</script>



<?php 
session_start();
include 'config.php';
$created_on = date('Y-m-d H:i:s');
$updated_on = date('Y-m-d H:i:s');

/* insert comment */

if(!empty($_POST['action']) && $_POST['action'] == "addComment") {

$commTitle = mysqli_real_escape_string($con, $_POST['commTitle']);
$commBody = mysqli_real_escape_string($con, $_POST['commBody']);  
$created_by = $_SESSION['username'];  

$query = "INSERT INTO `tbl_article`(`id`, `title`, `comment`, `created_on`, `created_by`, `status`) VALUES (null, '{$commTitle}', '{$commBody}', '{$created_on}', '{$created_by}', 1)";
$insert = mysqli_query($con, $query) or die(mysqli_error($con));
if($insert){
echo json_encode( array("status" => 1,"message" => "article created successfully!", 'title' => 'success', 'type' => 'success' ) ); exit;
} else { echo json_encode( array('status' => 0, 'message' => 'created failure', 'title' => 'failure', 'type' => 'error' )); exit; }
}

/* comment update */
if(!empty($_POST['action']) && $_POST['action'] == "updateComment") {
$articleId = mysqli_real_escape_string($con, $_POST['articleId']);
$commTitle = mysqli_real_escape_string($con, $_POST['commTitle']);
$commBody = mysqli_real_escape_string($con, $_POST['commBody']);  
$updated_by = $_SESSION['username']; 


$record = mysqli_query($con,"SELECT `id` FROM `tbl_article` WHERE `id`='{$articleId}'") or die(mysqli_error($con));
if(mysqli_num_rows($record) > 0){

$name = mysqli_escape_string($con, $_POST['name']);

$query = "UPDATE `tbl_article` SET `title`='{$commTitle}', `comment`='{$commBody}', `updated_on`='{$updated_on}', `updated_by`='{$updated_by}' WHERE `id`='{$articleId}'";
$update = mysqli_query($con, $query) or die(mysqli_error($con));
if($update){
echo json_encode( array("status" => 1,"message" => "article successfully updated!") ); exit;
} else { echo json_encode( array("status" => 0, "message" => "article could not be updated")); exit; }
} else { echo json_encode( array("status" => 0, "message" => "Invalid article id.") ); exit; }
}
?>

2 Comments

Please explain how this code-of-wall addresses the issue. Code-only answers are not good answers. Furthermore, please have a look at the following articles: Is mysqli_real_escape_string safe? and Is "mysqli_real_escape_string" enough to avoid SQL injection or other SQL attacks?
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.