I learn MVC and Ajax, by building a site in PHP and MySQL. I made a new controller method to handle ajax, and am now able to update the database successfully from my Ajax HTTPRequest. When I get the response, i am able to update the division by replacing the current contents of the division with a javascript string like "Hello", but I can't figure out how to replace the contents with my updated database data. How do I update the division correctly? For now I want to do it without JQuery, and am not using a PHP framework. The data in the division is a list of places a member has been. Before Ajax, the list was sent to the "view" when the page loaded:
//this is controller->index()
public function index() {
//the properties will be pulled up from the db as neccessary so we need to set them first
$this->member->setMembername();
$this->member->setMemberProfile();
$this->member->setMyPlacesList();
$this->member->setMemberData(); //puts the above data into one array for convenience
$this->view->setData($this->member->getmemberData());
$this->view->render('welcomepage/index'); //builds the view with the data
}
Now in my ajax call, my controller tells the member model to update the list of places the member has been:
public function AjaxAddVisit() {
$details['sitename'] = $_POST["sitename"];
$details['datetime'] = date("Y-m-d H:i:s");
$details['comments'] = $_POST['comments'];
$this->member->addMemberVisit($details); This successfully adds the place to the database.
//I suppose I should now do something like ?
//$this->member->setMyPlacesList();
//$this->member->setMemberData();
//$this->view->setData($this->member->getmemberData());//this would update the views data
}
I now want to modify the list in the view from the Ajax code but don't know how, do I do something like the following, where I just embed php code in a javascript string like this?:
function AddVisitResponse() {
if (myReq.readyState == 4) {
if(myReq.status == 200) {
var phpString = "<?php echo $this->data['myPlacesList'][0][1] ?>";
document.getElementById('myPlacesList').innerHTML = phpString;
//this would just print out one element of the list, but just for example
} else {
alert("got no response from the server");
}
}
}
The output of the above is something like: myPlacesList'][0][1] ?> So i think there must be something wrong. It seems I can't send back a string with php code at all, even when I echo "hello" it doesn't work. How do I update the division correctly? should I format the string in my php controller method using XML? Thank you very much, this is my first question here, and any help would be greatly appreciated!!!