Reputation: 718
I want to make an ajax request to allow the user to send some data from input field to database and then return it to the input field, as same as the comment box, so the data should inserted into the database and then displayed in the input field without reloading the page, here is my code:
function getHTTPObject(){
if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
else if (window.XMLHttpRequest) return new XMLHttpRequest();
else {
alert("Your browser does not support AJAX.");
return null;
}
}
// Implement business logic
function doWork(){
httpObject = getHTTPObject();
if (httpObject !== null) {
httpObject.open("GET", "a page or a controller action"
, true);
httpObject.send(null);
// httpObject.onreadystatechange = setOutput;
}
}
so, how I can make a request that can call a controller action without leaving the entire page?
Upvotes: 0
Views: 247
Reputation: 1995
First, to make the Ajax request I suggest you to use jQuery. It will be a lot easier.
Here is an example (using jQuery) :
jQuery.getJSON('/path/to/your/controller/someAction/',function(response) {
console.log('Server reply : ',response);
}
In your controller's action do not forget to send output as json :
public function actionSomeAction()
{
die(json_encode("This is my response"));
}
edit : If you don't need jQuery, see this SO answer for making Ajax call without jQuery : https://stackoverflow.com/a/8567149/911718
Upvotes: 3