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
Answers
Given that your form has elements with the same name as the keys you want to send using AJAX, the simplest approach is to:
add an
id
to the form, so jQuery can identify it. For example, "new-article-form".replace the three
data:
lines with:data: $("#new-article-form").serialize()
to use jQuery’s serialize() function, as described here.
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: