I am fairly new to posting on StackOverflow so I hope that my post follows the correct criteria, if it doesn't I apologise. I shall try to keep my question and explanation of my issue as short as possible.
I am trying to create a input field which allows the user to update their About section on their profile for other users to be able to see. I have looked at similar posts but none of them really had solutions that matched my problem from what I could find.
I am using a form with a POST method which has a hidden field that includes the value of the userId and stores the string from the input field. I am using an Onclick function associated to the button with the id = "post"
which calls an Ajax request which stores the value of the input into a variable known as var text
which I want then to be stored into a database with the userId and the comment. However, the console returned "an empty string" (image linked at the very bottom). I am not to sure how to figure it out since I am still very new to using Ajax, and I'm trying to learn as much as I can.
myAccount.php
<h2>About</h2>
<form method='POST' id="postForm">
<input type='hidden' name='posterId' value="<?php echo $user['userId']?>">
<input name="post" id='post' value="">
<br/>
<br/>
<button type="button" onclick='setComment()' name='submit'>Post it</button>
</form>
main.js
function setComment() {
var text = $("#post").val();
$.ajax({
type: 'POST',
url: 'setAbout.php',
data: {'text': text},
success: function(data) {
console.log(data);
}
});
}
Note: If you post a solution please include an explanation as to why you took that particular approach since I am here to learn. Thank you!
<input type='hidden' name='posterId' value="<?php echo $user['userId']?>" id = 'posterId'>
function setComment() {
var text = $("#post").val();
var posterId=$('#posterId').val();
$.ajax({
type: 'POST',
url: 'setAbout.php',
data: {'text': text, 'posterId':posterId},
success: function(data){
console.log(data);
}
});
}
you are checking for the variable posterId
in your PHP script, which you have not set while doing the ajax call.
and in the script you are just running the prepared query, you are not returning anything as response to your request. So even if the request succeeds, you will not get anything in the response to print in your console
You, post with AJAX: {text} variable but in PHP code, you want to get {posterId} variable. Why? Change your variable name and sure in JS and PHP code the same name variable. And in AJAX request, PHP cannot return nothing. So in PHP code, you should use 'echo' for returning.