Issue : if i call ajax function i can't able to get return value.
Below is my simple javascript and ajax file.
Javascript Ajax
<script type="text/javascript">
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
return this.responseText;
}
};
xhttp.open("GET", "testAjax.php", true);
xhttp.send();
}
alert(loadDoc());
</script>
PHP
<?php
echo "Hello World !!!";
?>
Can synchronous or asynchronous concept are useful to this problem ?
Thank you.
The problem is the asynchronous nature of ajax requests and the execution flow of code. The callback that is invoked when the conditions of onreadystatechange are met is not guaranteed to complete before the end of the main function has been reached. To achieve a return from the ajax function you need to use Promises
let oPromise = new Promise( ( resolve, reject ) => {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
resolve( this.response );
}
};
xhttp.open('GET', 'testAjax.php', true);
xhttp.send();
});
oPromise.then( ( data ) => {
alert('Whoohoo! -> ' + data );
});
To some the syntax of the above will be unfamiliar and perhaps a little confusing - it could be rewritten in a more familar/tradional way like this:
let oPromise = new Promise( function( resolve,reject ){
var xhr = new XMLHttpRequest();
xhr.onload=function(){
resolve( this.response )
};
xhr.onerror=function(){
reject( this.readyState )
};
xhr.open('GET', 'testAjax.php', true);
xhr.send();
});
oPromise.then( function( response ){
alert('Whoohoo! -> ' + response );
});
You need to change your logic like this:
function doJobWhenAjaxResultIsReturned(ajaxData){
// alrt(ajaxData);
}
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
doJobWhenAjaxResultIsReturned(this.responseText);
}
};
xhttp.open("GET", "testAjax.php", true);
xhttp.send();
}
loadDoc();
then do what you want in doJobWhenAjaxResultIsReturned().
Related
What is wrong with this ajax function.
<script>
function loadDoc() {
var a=document.data.fitem.value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "master_find.jsp?val="+a) ;
xhttp.send();
}
</script>
I tried so many ways to supply a variable to the master_find.jsp script to retrieve the main item from a table., no success.
I am sending two parameters inside the send method to index.php. But the PHP returns an error "Undefined index". echo $_POST['fname'];
submit.addEventListener("click", function(e){
e.preventDefault();
var xhr = new XMLHttpRequest();
xhr.open("POST", "index.php", true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.onreadystatechange = function () {
if(xhr.readyState == 4 && xhr.status == 200) {
var result = xhr.responseText;
console.log(result);
}
}
xhr.send("fname=Henry&lname=Ford");
});
In order to send form data through Ajax, you have to specify the content type of the request. In you case it will be 'application/x-www-form-urlencoded:
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
So your code will be:
submit.addEventListener("click", function(e){
e.preventDefault();
var xhr = new XMLHttpRequest();
xhr.open("POST", "index.php", true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.onreadystatechange = function () {
if(xhr.readyState == 4 && xhr.status == 200) {
var result = xhr.responseText;
console.log(result);
}
}
xhr.send("fname=Henry&lname=Ford");
});
Here is my code in javascript
<script type="text/javascript">
startingListener();
function startingListener() {
setInterval(function(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:32081/", false);
xhr.send();
var result = xhr.response;
console.log(result);
}
}, 100);
}
</script>
And my server on Java
public static void main (String... args) throws IOException, Exception {
String clientSentence;
ServerSocket welcomeSocket = new ServerSocket(32081);
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
PrintWriter outToClient = new PrintWriter(connectionSocket.getOutputStream(), true);
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
System.out.println("begin");
outToClient.println("fu");
System.out.println("Received: done");
}
}
I just want to receive answer string in JS and work with it further.
So when I run server and run JS, they connected and I received in IDE send() from JS
After that I saw in console of Java that begin and done received, but in browser console I didn't see any answer and script just handled. What do I do wrong?
Thank you for your help
Your client code is missing a state change handler and using setInterval with 100 ms it is very heavy on the server. Here is a better JS. Your JAVA issue is another problem. Downvoters: Do comment
function listener() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:32081/", false);
xhr.onreadystatechange = function () {
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log(xhr.responseText);
}
}
}
listener();
If you want to call listener repeatedly, you can do
function listener() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:32081/", false);
xhr.onreadystatechange = function () {
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
if (xhr.responseText != "done") {
console.log("server still busy");
setTimeout(listener,1000); // repeat the call
}
else {
console.log("finally done");
}
}
}
}
I have a PHP script which queries a database and returns a table, depending on the input, e.g.results.php?f=1.
I am trying to call it multiple times from JavaScript:
function go(n,divid) {
document.getElementById(divid).innerHTML = "<img src=\"load.gif\">";
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById(divid).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", n, true);
xmlhttp.send();
}
Call later
go('results.php?print=1&nh=1','d1');
go('results.php?print=2&nh=1','d2');
go('results.php?print=3&nh=1','d3');
go('results.php?print=4&nh=1','d4');
The PHP code connects to a SQLite3 database. The problem with the above is that sometimes it works, but sometimes one of the queries fails to be prepared by SQLite3::prepare().
What could be wrong? A sqlite race condition? A javascript issue?
When results.php is called just once, the query always succeeds.
Thanks.
Use xhttp instead of xmlhttp.
function go(n,divid) {
var xhttp = new XMLHttpRequest();
document.getElementById(divid).innerHTML = "<img src=\"load.gif\">";
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById(divid).innerHTML = xhttp.responseText;
}
}
xhttp.open("GET", n, true);
xhttp.send();
}
go('results.php?print=1&nh=1','d1');
I tried this code :
var xmlHttp = new XMLHttpRequest();
function activecomm(comm_id,a_link_id)
{
var postComm = "id="+encodeURIComponent(comm_id);
var url = 'comments_mgr_proccesser.php';
xmlHttp.open("POST", url, true);
xmlHttp.onreadystatechange = handleInfo(a_link_id);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", postComm.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(postComm);
}
function handleInfo(a_link_id)
{
if(xmlHttp.readyState == 1)
{
document.getElementById("commactiveresult").innerHTML = 'loading ..';
}
else if(xmlHttp.readyState == 4)
{
var response = xmlHttp.responseText;
document.getElementById("commactiveresult").innerHTML = response;
}
}
When readyState == 1 the contents of the commactiveresult element is updated, but when readyState == 4 nothing is shown in the same element.
Does anyone know what the problem is please?
You're calling the handleInfo function instead of assigning a ready state handler. Try
xmlHttp.onreadystatechange = function (){
handleInfo(a_link_id);
};