Synchronous request with ajax in a loop - php

I have a for loop which contains ajax request. The request is working aynchronously. So i can't reach the result of request in time. How can i solve this problem without using any library?
Thanks.
var availables = document.getElementsByClassName("available");
for(var i=0;i<availables.length;i++){
var element = availables[i];
var xmlhttp;
if(window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest;
else
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET", "control.php?user=" + element.innerText, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
var result = xmlhttp.responseText;
console.log(result);
element.setAttribute("class" , "result available " + result);
if(result == "online")
element.innerHTML = "" + element.innerText + "";
}
}
}

First of all, I'd suggest putting your xmlhttp.onreadystatechange function before you do xmlhttp.open and xmlhttp.send. It's possible that it's sending and returning and since it's running asynchronously, it's getting back before you're onreadystatechange function can be defined/executed. Something like that.
Anyway, you can always do it all synchronously by setting the last argument in xmlhttp.open to false. This will make javascript wait after xmlhttp.send before continuing, but either way you'll still need to put onreadystatechange before open and send.
var availables = document.getElementsByClassName("available");
for(var i=0;i<availables.length;i++){
var element = availables[i];
var xmlhttp;
if(window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest;
else
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
var result = xmlhttp.responseText;
console.log(result);
element.setAttribute("class" , "result available " + result);
if(result == "online")
element.innerHTML = "" + element.innerText + "";
}
}
xmlhttp.open("GET", "control.php?user=" + element.innerText, true);
//xmlhttp.open("GET", "control.php?user=" + element.innerText, false); //If you want to do it synchronously
xmlhttp.send();
}

It is very bad practice to make your ajax calls synchronously xmlhttp.open("GET", "control.php?user=" + element.innerText, true) because you cannot interact with your application until an ajax request ends. I think in your case it is better to send every next request in the onreadystatechange callback of the previous one.

Related

How can I optimize javascript code against fetch api?

I want to use fetch api on my wordpress site. I watched many tutorials like Promise, Callbacks Async / Await. Fetch api related examples are usually on json post requests. How can I develop this code in the most make sense way? I am using it in Wordpress and it has to get information from 2 php codes.
<script type="module">setTimeout(function (){function s(id, endpoint) {
var xmlhttp;
var params = "/ajax/fetch/api/id/" + id + "/" + Math.floor((Math.random() * 100000));
if (window.XMLHttpRequest) xmlhttp = new XMLHttpRequest(); else xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
}
};
xmlhttp.open("GET", params, true);
xmlhttp.send()
}s(<?php echo get_the_ID();?>,'<?php echo get_site_url(); ?>');}, 2000
)
</script>

Adding video to playlist with Youtube API

I successfully added a video to a playlist but it is added multiple times (sometimes twice and sometimes more). Can anybody help?
$resourceId = new Google_Service_YouTube_ResourceId();
$resourceId->setVideoId($videoID);
$resourceId->setKind('youtube#video');
$playlistItemSnippet = new Google_Service_YouTube_PlaylistItemSnippet();
$playlistItemSnippet->setPlaylistId($playlistId);
$playlistItemSnippet->setResourceId($resourceId);
$playlistItem = new Google_Service_YouTube_PlaylistItem();
$playlistItem->setSnippet($playlistItemSnippet);
$playlistItemResponse = $youtube->playlistItems->insert('snippet,contentDetails', $playlistItem, array());
Solved it myself and I'm pretty proud of it :)
I realised that the ajax was triggering the above php script on mouseover. So every time I hovered away from the checkbox element the php script triggered multiple times.
I changed the mouseover code with the following:
$(function() {
$('input.Chilltrap').on('click', function(e) {
var chilltrap = this.id;
if( $("input[name=" + chilltrap + "]").prop('checked') ) {
checkboxstatusCt = "Yes";
}
else {
checkboxstatusCt = "No";
}
var url = "url.php";
var params = "c="+checkboxstatusCt+"&s="+chilltrap;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
$("#error").html(xmlhttp.responseText);
$("#error"). fadeIn('fast');
setTimeout(function(){
$("#error"). fadeOut('slow');
},2000);
}
};
xmlhttp.open("GET", url+"?"+params,true);
xmlhttp.send();
});
});

AJAX transfer large amount of data using $_POST method

I would like to transfer a large amount of text to the server using AJAX. I would like to attach this text using the POST method, but I get the following error:
request failed: URI too long (longer than 8190)
My javascript code:
function loadXMLDoc(data) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "http://www.mydomain.com/test2.php?blob=" + data, true);
xmlhttp.send();
}
My php code:
$dataraw = $_GET["blob"];
file_put_contents('/path/to/my/file/newfile.txt', $dataraw);
echo 'file saved';
You should change this
xmlhttp.open("POST","http://www.mydomain.com/test2.php?blob=" + data,true);
xmlhttp.send();
to this:
xmlhttp.open("POST", "http://www.mydomain.com/test2.php", true);
var payload = "blob=" + data;
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.setRequestHeader("Content-length", payload.length);
xmlhttp.send(payload);
In POST, parameters should go in the body of the message, not the URL.
At the same time, you should expect the parameters on the server-side in $_POST - that's where the body parameter will end up in in PHP.
You don't add post-data to the URL. Please check this link to find an example of a post-request:
http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");

auto update data from AJAX posting form

I am using an AJAX script to post data from a form and return the processed data from a php file. The script is below.
function loadXmlDoc(hashtag){
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("ajaxify").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "demo_ajax3.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("hashtag=" + hashtag);
}
However I want to auto update the results. how would I get this to auto update so it checks for more data? Or what would be the best way?
There seems to be nothing about getting AJAX forms to auto refresh from what I've seen so any help would be greatly apprecaited
Try this way. It should auto-update the result every 10 seconds.
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("ajaxify").innerHTML = xmlhttp.responseText;
}
}
function loadXmlDoc(hashtag){
var repeat = function () {
xmlhttp.open("POST", "demo_ajax3.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("hashtag=" + hashtag);
};
repeat.hashtag = hashtag;
setInterval(function() { repeat(); },10000);
}

AJAX and php POST problems

I am trying to pass to a PHP file cellnumber. My AJAX isn't even working, when I try
alert("test"); in the ajax.onreadystatefunction() it won't print.
My javascript getrow(t) function gets called every time someone clicks on a cell in a table
and the result is the cell turning into green. I want to ultimately enter this data into a postgres table using php.
Thanks for all the help!
Vlad
<script type="text/javascript">
//gets the row and column number
function getRow(t)
{
var col=t.cellIndex;
var row=t.parentNode.rowIndex;
var testTable = document.getElementById("testTable");
t.style.backgroundColor = "#33CC66";
var cellnumber = (row*15 + col);
var ajax = new XMLHttpRequest();
//use ajax to enter into visitedCells
ajax.onreadystatechange = function()
{
// Call a function when the state changes.
if(ajax.readyState == 4 && ajax.status == 200)
{
ajax.open("POST", insertCoordinates.php, true);
ajax.send(cellnumber);
}
else
{
alert("Error:" + ajax.status + "and " + ajax.statusText);
}
}
}
</script>
</body>
</html>
ajax.open("POST", insertCoordinates.php, true);
ajax.send(cellnumber);
should be outside ajax.onreadystatechange
just befor }//getRow
you actually don't have the request executed
should be like that:
var ajax = new XMLHttpRequest();
//use ajax to enter into visitedCells
ajax.onreadystatechange = function() {//Call a function when the state changes.
if(ajax.readyState == 4 && ajax.status == 200) {
alert('success');
} else {
alert("Error:" + ajax.status + "and " + ajax.statusText);
}
}//onreadyState
ajax.open("POST", insertCoordinates.php, true);
ajax.send(cellnumber);
probably won't work in IE
should use a construction like that:
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
but the best way is to use jQuery ...easy and safe

Categories