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?
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
Related
I have ajax that is communicating with php to receive tweets from a twitter account. The code is working fine.
The only thing is I want the ajax to intermittently call the php so that any updated tweets automatically come back and get printed to my page without having to refresh or re-enter a twitter id.
Do I need to keep calling the getStatuses() function or something?
Or do I need to use the getUpdates() which I have started to make somehow?
Here are my ajax functions:
// the setInterval function added in the getStatusesX function
function getStatusesX()
{
setInterval(getStatuses(),300000);
}
//Create a cross-browser XMLHttp Request object
function getXMLHttp() {
var xmlhttp;
if (window.ActiveXObject) {
XMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else if (window.XMLHttpRequest) {
XMLHttp = new XMLHttpRequest();
} else {
alert("Your browser does not support XMLHTTP!");
}
return XMLHttp;
}
//function that searches for the tweets via php
function getStatuses(){
XMLHttp1 = getXMLHttp();
var userID = document.getElementById("userid").value;
//ajax call to a php file that will extract the tweets
XMLHttp1.open( 'GET', 'twitterTest2.php?userid='+userID, true);
// Process the data when the ajax object changes its state
XMLHttp1.onreadystatechange = function() {
if( XMLHttp1.readyState == 4 ) {
if( XMLHttp1.status ==200 ) { //no problem has been detected
document.getElementById("tweetbox").innerHTML=XMLHttp1.responseText;
}
}
}
XMLHttp1.send(null);
}
//function to intermittently call php to check for updated tweets?
function updateInfo() {
if(XMLHttp1.readyState == 4) {
document.getElementById("tweetbox").innerHTML=XMLHttp1.responseText;
}
}
</script>
I then added the getStatusesX() function to my form as follows:
<form>
Input Twitter ID: <input type="text" name="userid" id="userid">
<button type="button" onClick="getStatusesX()";>Get recent tweets</button>
</form>
It's still not working. Am i using the setInterval in the wrong way?
Use the setTimeout or setInterval functions.
From what I can see in your code, getStatuses has too much responsability since in addition of getting the data, it also modifies the DOM.
I would suggest something like:
function getStatuses(callback) {
//...
XMLHttp1.onreadystatechange = function () {
//...
callback && callback(XMLHttp1); //execute callback if any
};
}
function updateStatuses(callback) {
getStatuses(function (xhr) {
document.getElementById("tweetbox").innerHTML = xhr.responseText;
callback && callback;
});
}
//this function update the statuses and as soon as it's finished, it sets
//a timeout to redo the process in ~10 seconds.
function startUpdatingStatuses() {
updateStatuses(function () {
setTimeout(startUpdatingStatuses, 10000);
});
}
startUpdatingStatuses(); //kick-start everything
i am having trouble making this part of code to work, basically i want to call this function which sends a variable to a php page. Ive tested that the variable is there and also tested that my php page is accepting information as it should be , however i cant make this Ajax thing work.
function ajaxRequest(myname) {
var AJAX = null; // Initialize the AJAX variable.
if (window.XMLHttpRequest)
{ // Does this browser have an XMLHttpRequest object?
AJAX=new XMLHttpRequest(); // Yes -- initialize it.
} else
{ // No, try to initialize it IE style
AJAX=new ActiveXObject("Microsoft.XMLHTTP"); // Wheee, ActiveX, how do we format c: again?
} // End setup Ajax.
if (AJAX==null)
{ // If we couldn't initialize Ajax...
alert("Your browser doesn't support AJAX."); // Sorry msg.
return false // Return false, couldn't set up ajax
}
AJAX.onreadystatechange = function()
{ // When the browser has the request info..
if (AJAX.readyState==4 || AJAX.readyState=="complete")
{ // see if the complete flag is set.
callback(AJAX.responseText, AJAX.status); // Pass the response to our processing function
} // End Ajax readystate check.
}
alert("Alert1");
var url='http://localhost/main.php?Name=myname';
AJAX.open("POST", url, true); // Open the url this object was set-up with.
alert("Alert2");
AJAX.send(); // Send the request.
}
This is my php part which should accept the variable
<?php
$var=$_GET['Name'];
echo $var;
?>
Okay firstly you need to change your request to GET from POST
like
AJAX.open("GET", url, true); // Open the url this object was set-up with.
and you also need to update this line
from
var url='http://localhost/main.php?Name=myname';
to
var url='http://localhost/main.php?Name='+myname;
my full script is:
<script type="text/javascript">
function ajaxRequest(myname) {
var AJAX = null; // Initialize the AJAX variable.
if (window.XMLHttpRequest)
{ // Does this browser have an XMLHttpRequest object?
AJAX=new XMLHttpRequest(); // Yes -- initialize it.
} else { // No, try to initialize it IE style
AJAX=new ActiveXObject("Microsoft.XMLHTTP"); // Wheee, ActiveX, how do we format c: again?
} // End setup Ajax.
if (AJAX==null)
{ // If we couldn't initialize Ajax...
alert("Your browser doesn't support AJAX."); // Sorry msg.
return false // Return false, couldn't set up ajax
}
AJAX.onreadystatechange = function()
{ // When the browser has the request info..
if (AJAX.readyState==4 || AJAX.readyState=="complete")
{ // see if the complete flag is set.
callback(AJAX.responseText, AJAX.status); // Pass the response to our processing function
} // End Ajax readystate check.
}
alert("Alert1");
var url='http://localhost/main.php?Name='+myname;
AJAX.open("GET", url, true); // Open the url this object was set-up with.
alert("Alert2");
AJAX.send(); // Send the request.
}
</script>
you might also be missing the callback function so add it so that it looks like this
function callback(x, y) {
alert(x);
}
And call your AJAX function by
ajaxRequest("ashley");
Here is your required main.php code (even though this isn't what you should be using AJAX for
<?php
session_start();
if(isset($_GET["Name"])) {
$_SESSION["Name"] = $_GET["Name"];
}
if(isset($_SESSION["Name"])) {
echo $_SESSION["Name"];
} else {
echo "The AJAX has not been run!";
}
?>
There are two ways to send an ajax request to server
Either GET or POST
1. GET Method:
var url='http://localhost/main.php?Name='+myname; // you can add any numner of vars here
AJAX.open("GET", url, true);
AJAX.send();
Code in main.php
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo $_GET['Name'];
}
2. POST Method:
AJAX.open("POST","ajax_test.asp",true);
AJAX.setRequestHeader("Content-type","application/x-www-form-urlencoded");
AJAX.send("Name="+myname);
Code in main.php
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo $_POST['Name'];
}
I think I'm getting ahead of myself, but I tried AJAX tutorials to read from a PHP file. The PHP file simply has an echo statement for the time, and I want to pass that to initialize a javascript clock.
But this is my first time trying AJAX and I can't even seem to get it to activate a test alert message.
Here is the code, it's at the bottom of my PHP page after all of the PHP.
<script type='text/javascript'>
function CheckForChange(){
//alert("4 and 4");
//if (4 == 1){
//setInterval("alert('Yup, it is 1')", 5000);
//alert('Now it is changed');
//}
var ajaxReady = new XMLHttpRequest();
ajaxReady.onreadystatechange = function(){
if (ajaxReady.readystate == 4){
//Get the data
//document.getElementById('clocktxt').innerHTML = ajaxReady.responseText;
alert("here");
alert(ajaxReady.responseText);
}
}
ajaxReady.open("GET","ServerTime.php",true);
ajaxReady.send(null);
}
setInterval("CheckForChange()", 7000);
</script>
Can somebody tell me why this isn't working? No idea what I'm doing wrong.
The problem in your code is an uncapitalized letter. (Oops!) You check ajaxReady.readystate; you need to check ajaxReady.readyState.
Because ajaxReady.readystate will always be undefined, your alerts never fire.
Here's your code fixed and working.
As an aside, have you considered using a library to handle the ugliness of cross-browser XHR? jQuery is your friend:
function CheckForChange(){
$.get('ServerTime.php', function(data) {
$('#clocktxt').text(data);
});
}
You should probably have something like:
setInterval(CheckForChange, 7000);
On an unrelated note, it's common naming convension in JavaScript to have function and methods names' first letters not capitalized, and the rest is in camelCase. i.e. checkForChange().
I'm not sure the exact problem with your code; here's what I use -- I'm sure it will work for you. (plus, it works with more browsers)
var xhr = false;
function CheckForChange(){
/* Create xhr, which is the making of the object to request an external file */
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
if(window.ActiveXObject){
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){}
}
}
/* End creating xhr */
/* Retrieve external file, and go to a function once its loading state has changed. */
if(xhr){
xhr.onreadystatechange = showContents;
xhr.open("GET", "ServerTime.php", true);
xhr.send(null);
}else{
//XMLHTTPRequest was never created. Can create an alert box if wanted.
}
/* End retrieve external file. */
}
function showContents(){
if(xhr.readyState==4){
if(xhr.status==200){
alert(xhr.responseText);
}else{
//Error. Can create an alert box if wanted.
}
}
}
setInterval(CheckForChange, 7000);
Good day to all. I have the flowing problem.
I have 2 domains. On one domain I send an ajax post to the other and expect some results. The problem is that the response is always empty. If I inspect the net tab the request looks alright (the post data is fine), it doesn't receive any error, it ends (I put an alert on the handle response function to check what the response is). I tried sending a request to random domains (like example.com) to see if I get anything. The response is the same... none.
Here is the script I use:
function sendReqPost(url) {
http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
// set type accordingly to anticipated content type
//http_request.overrideMimeType('text/xml');
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}
//http_request.onreadystatechange = handleResponseAccept;
http_request.open('POST', url, true);
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Content-length", parameters.length);
http_request.setRequestHeader("Connection", "close");
//parameters is a global variable with the post data.
http_request.send(parameters);
}
I double checked everything in the script... I also inserted echos in the requested php page to see if I get anything. Whatever I do the response is empty.
P.S. On another domain the ajax script worked fine. Exactly the same.
I have 2 domains. On one domain I send an ajax post to the other and expect some results.
There's your problem. This is because of the Same Origin Policy in JavaScript. And thats why...
...on another domain the ajax script worked fine.
There are some workarounds though, called Cross Domain Ajax.
For your needs, since you apparently want HTML and not JSON, I would suggest a small PHP script to get the content from the other domain and forward it to your client side. This would be called Ajax proxy.
See this question
I don't see your http_request.responseText, it returns what is echo'ed in the request URL.
So try add this:
http_request.onreadystatechange = function () {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
alert(http_request.responseText);
} else {
alert("An error occurred: "+ http_request.statusText);
}
}
};
Before:
//parameters is a global variable with the post data.
See if it works.
In a Form, I am calling a PHP file if the validation passes. My Form header looks like this:
<form method="POST" action="inst.php" style="margin:0px;"name="form1" onSubmit="return CheckUsername(document.getElementById('username').value);">
</form>
The problem is that even if the validation fails, it shows a blank page in an attempt to open the PHP file, when it must remain on the same page. The PHP file contains code to access the database to check whether the user exists or not.
Is there any way to check the database for value without refreshing the page?
It is very likely that the JavaScript function has an error. The validation function will then not be executed and the form sent (!). Check Firefox's Javascript console for errors, they will appear there even if the page has already reloaded.
You should however never rely on client side validation. I would highly recommend checking in the PHP script as well.
While you should never rely upon client-side verification alone and should definitely treat all data as "dirty" in the PHP, there is another way using JavaScipt that you can prevent the browser from directly posting the form. Rather than setting the form's method and action, simply define its onsubmit function to construct an XmlHttpResponse object, set the method to POST and set data to your form.serialize(), and send the appropriate POST request. Or, if the PHP script will accept GET or REQUEST parameters, you can (after your verification) construct the URL query and simply set window.location to redirect to the PHP page with the appropriate data.
EDIT - Here is my illustration - this uses Prototype's Form.serialize function.
<form id="my_form" onSubmit="return checkUsername();">
Username: <input type="text" name="username" id="username" />
</form>
<script type="text/javascript">
var xhr; // global XMLHttpRequest object
var formElem = $('my_form'); // our form element
function checkUsername() {
var formData = formElem.serialize();
sendPOSTRequest('http://mydomain.com/mypath/myscript.php', formData);
}
function sendPOSTRequest(toURL, sendData) {
xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!xhr) {
alert('Cannot create XHR');
return false;
}
xhr.onreadystatechange = handleResponse;
xhr.open('POST', toURL, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", sendData.length);
xhr.setRequestHeader("Connection", "close");
xhr.send(sendData);
}
function handleResponse() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var result = xhr.responseText;
// result is now whatever content was returned by the PHP script
// do whatever you want with the result here
// for example, you might have the PHP return 'true' or some such thing, and then
// change window.location, or perhaps if it returns 'false' you put up an alert('No!')
// use your imagination, go nuts
} else {
alert('The script returned an error.');
}
}
}
</script>
There are some more sophisticated ways to create and handle the XMLHttpRequest object. I might post an update later with some pointers.
Once the POST request has been sent then it is up to the browser how it handles the response, but in every browser I have come across it will display the result of the request in some for be it a message saying it recieved a response (200,404, etc), a blank page or whatever, so I'm afraid you will have to reconstruct your page and send it back to the client (complete with invalid entries in the form elements) as a response.
Its a pain, but that's how HTTP works.