Even though my alert($userId) prints out 1 ( which is the id of the user ), I still get an error as if userId is not defined. Any idea why?
$('.postComment').on('click', function(event){
event.preventDefault();
$userId = $("input[name=user_id]").val();
$imageId = $("input[name=image_id]").val();
$comment = $("textarea[name=comment]").val();
alert($userId);
$.ajax({
method: 'POST',
url: urlComment,
data: {userId: userId, imageId: imageId, comment: comment}
}).done(function(){
alert('Works');
})
});
You are using jQuery and $ has very different use here:
Here's the cleanest way you can try:
$('.postComment').on('click', function(event){
event.preventDefault();
$.ajax({
method: 'POST',
url: urlComment,
data: {
userId: $("input[name=user_id]").val(),
imageId: $("input[name=image_id]").val(),
comment: $("textarea[name=comment]").val()}
}).done(function(){
alert('Works');
})
});
In your code, you had variable by the name of $userId and you were using userId which wasn't declared that's why you got error.
Try the following
$('.postComment').on('click', function(event){
event.preventDefault();
var userId = $("input[name=user_id]").val();
var imageId = $("input[name=image_id]").val();
var comment = $("textarea[name=comment]").val();
alert(userId);
$.ajax({
method: 'POST',
url: urlComment,
data: {userId: userId, imageId: imageId, comment: comment}
}).done(function(){
alert('Works');
})
});
Or
$('.postComment').on('click', function(event){
event.preventDefault();
var $userId = $("input[name=user_id]").val();
var $imageId = $("input[name=image_id]").val();
var $comment = $("textarea[name=comment]").val();
alert($userId);
$.ajax({
method: 'POST',
url: urlComment,
data: {userId: $userId, imageId: $imageId, comment: $comment}
}).done(function(){
alert('Works');
})
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.