I am trying to send a JSON object via ajax to the same page. While running my code, the ajax function does seem to send the data, as I can see on the response, that the $id in the PHP code, is changed to 200, but I am unable to display it on the webpage. I have included the jquery.js file (I'm not sure if I need to add another js library or not). I tried looking at a lot of stackoverflow answers but was unable to solve my problem. Any help would be appreciated.
PHP Code:
<?php
if(isset($_POST['area_id'])){
$id = $_POST['area_id'];
echo "Area ID: ".$id;
} else {
echo "test";
}
?>
JQuery AJAX
var dat = {area_id: 200, title: 'title'};
$.ajax({
type:"POST",
data: dat,
success:function(res){
alert(res);
}
});
[based on comments to the question...]
Your page isn't being updated because you've written no code to update it. echo
simply emits text to the output, and alert()
simply displays text to the user in a message box. In order to update the page client-side you'll need to write code which does that.
For example, if you have an element with id="output"
and want to set the response text to that element, you'd do this:
$('#output').text(res);
That element would then get that text:
<div id="output">Area ID: 200</div>
Server-side code has no way of altering a page that's already been sent to the browser. When your client-side code receives new data via AJAX, that client-side code needs to use that data in whatever way you want it to.
0 comments:
Post a Comment