Within the HTML tag on my addtodb.php
file, I have a button that only shows up if a user is logged in:
<?php
if (isset($_SESSION["userid"])){
echo "<button onclick='hiya()'> Add Image to User </button>";
}
?>
Right below that, I have the following script:
<script>
function itsucceeded(){
console.log("great");
document.body.insertAdjacentHTML("beforeend", "<?php echo 'a change hast occured';?>");
}
function hiya(){
$.ajax({
url: "wattapain.php", //page containing php you want to run
type: "POST", //request type
data : {clicked: "john"}, //data to be sent to the server
success: itsucceeded() //function to be called if the request succeeds
})
}
</script>
wattapain.php
includes only the following code:
<?php
$clicked = $_POST['clicked'];
echo "HI".$clicked;
?>
The console.log and the insertAdjacentHTML calls work, but no matter what I put in the PHP, it doesn't run. At first, the PHP stuff was in the same file (addtodb.php) but that wasn't working, and all the examples online were using separate php files anyway, so I created wattapain.php and even stopped checking if isset($_POST["clicked"])
but nothing is working. I can't tell what's wrong and would really appreciate your help.
And please please please don't close this question insisting that a post from 5 years ago answers my question. Trust me, it doesn't, I've been at this for two hours already and an hour and a half of that has been spent on Stack Overflow reading similar questions and not being able to fix this bug.
Thank you!
My Answer:
It looks like the issue might be with how you are handling the success callback in your AJAX request. Instead of passing the function `itsucceeded()` directly to the `success` parameter, you should pass it as a reference like this:
javascript
success: itsucceeded
By passing it as `itsucceeded` without the parentheses, you are telling jQuery to call the function when the AJAX request is successful.
So your updated script should look like this:
javascript
Try making this change and see if it resolves the issue. Let me know if you need further assistance.
Rate this post
3 of 5 based on 2669 votesComments