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>
Related
I am quite new in using Ajax requests using Php. Currently i am having two Php pages called getdata.php and getdata1.php with 2 Div tags called txtHint and uniHint.
I want both the div tag should display the results from both the php pages. Unfortunately, I am not sure about the usage of two XMLHTTP request at the same, Kindly help.
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
document.getElementById("uniHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getdata.php?q1="+topping,true);
xmlhttp.open("GET","getdata1.php?q1="+topping,true);
xmlhttp.send();
I have a checkbox that whenever it is checked it calls another php script using Ajax, now on the php script I got 3 text boxes with a button, and whenever the Button is pressed, Ajax will be preformed to call another php script. all of that are preformed in the same page!, it is just like this
PHP -> Ajax -> PHP -> Ajax -> PHP
Is it possible, or too much to process?!
my first Ajax is:
<script type = 'text/javascript'>
function load(cb, pos)
{
if (cb.checked == false)
{
document.getElementById(pos).innerHTML="";
return;
}
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
document.getElementById(pos).innerHTML = xmlhttp.responseText;
}
xmlhttp.open('GET', "trying.inc.php?pass='true'", true);
xmlhttp.send();
}
</script>
The second Ajax that is in "Tring.inc.php":
<script type = 'text/javascript'>
function check()
{
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
document.getElementById('adiv').innerHTML = xmlhttp.responseText;
}
Parameters = "OldPass="+document.getElementById('OldPass').value+"&newPass="+document.getElementById('newPass').value+"&Confirm="+document.getElementById('ConfirmPass').value;
xmlhttp.open('POST', 'Trying2.inc.php', true);
xmlhttp.setRequestHeader ('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.send(Parameters);
}
</script>
that calls "Trying2.inc.php".
now when I am at "trying.inc.php" page, Ajax works in calling "trying2.inc.php", but from the main page I can call "trying.inc.php" however, "trying.inc.php" can't call "trying2.inc.php", I hope it is clear because I don't know how to explain it more. If it is possible what can I do to achieve it, please support it with code. Im doing this for learning purposes please don't be harsh on me, Thanks in advance.
If you are using jquery, you could use bind/live on the elements newely added to the dom, thus you must be able to do this.
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.
Just beginner in php, I want to call php method using AJAX. I tried every thing but don't know what error is. Not getting any response from object xmlhttp.
Heres my java script code :
function loadData(){
var mID=ddItems;
var method=2;
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
if (xmlhttp.readyState == 4 || xmlhttp.readyState == 0) {
xmlhttp.open("GET", "../code/GetItemsInDD.class.php?id=" + mID + "&method=" + method, true); **// is this statement correct**
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200) **//conditin is false,**
{
document.getElementById("ddItems").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.send();
}
}
My js file is on "projectname/javascript/script.js" and my php file is in "projectname/code/GetItemsInDD.class.php" dir.
Why don't you use jQuery for making AJAX requests? Its as simple as this, include jQuery in your page
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
and JS code,
$.ajax({
type: 'GET',
url: '../code/GetItemsInDD.class.php?id=" + mID + "&method=" + method',
success: function (data) {
document.getElementById("ddItems").innerHTML = data;
}
});
This way, you don't need to check for the readyState and status thing
jQuery follows object oriented approach for declaring XMLHttpRequest objects, so you won't have to worry about creating multiple objects for making more than one AJAX requests.
function loadData(){
var xmlhttp;
var mID=ddItems;
var method=2;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("ddItems").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", "../code/GetItemsInDD.class.php?id=" + mID + "&method=" + method, true);
xmlhttp.send();
}
I have made 2 desired changes to your code, try running it now. Make sure the URL is correct.
function loadData()
{
var mID=ddItems;
var method=2;
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else //For some versions of IE
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200) **//conditin is false,**
{
document.getElementById("ddItems").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", "../code/GetItemsInDD.class.php?id=" + mID + "&method=" + method, true); **// is this statement correct**
xmlhttp.send();
}
}
Change 1 : You may be running the code in an older version of IE, where ActiveXObject is used.
Change 2 : The open() method should not be called if the readyState changes ( as you have written it within the IF block), readyState changes only after the ajax call is initialized by the open() method and then send by the send() method.
I have two divisions, <div id=statuslist></div><div id=customerlist></div>
The function sendReq() creates a xmlhttprequest and fetches the data into the division.
sendReq('statuslist','./include/util.php?do=getstatuslist','NULL');
sendReq('customerlist','emphome.php?do=getcustomerlist','NULL');
I have a problem,
The data fetched into the 'customerlist' gets copied onto 'statuslist'
If i change the order of function calls,
sendReq('customerlist','emphome.php?do=getcustomerlist','NULL');
sendReq('statuslist','./include/util.php?do=getstatuslist','NULL');
Now the data of 'statuslist' gets into 'customerlist'..
Whats the problem with the code?
That's also my problem right now. After a thorough research, I've found out that:
If you have more than one AJAX task on your website, you should create ONE standard function for creating the XMLHttpRequest object, and call this for each AJAX task
- W3Schools.com
Also, thanks to Two xmlHttpRequests in a single page which redirects me to this question Using two xmlhttprequest calls on a page, I was able to solve the problem. By the way, it is a modification of Addsy's answer.
First, create a ONE standard function for creating the XMLHttpRequest object, and call this for each AJAX task. Example:
function sendReq(url, callbackFunction)
{
var xmlhttp
if (window.ActiveXObject)
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status=='200')
{
if (callbackFunction) callbackFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
Second, call the function and pass the necessary parameters. For example:
sendReq("orders_code_get.php?currentquery="+sql, function processResponse( response )
{
document.getElementById("orders_content").innerHTML="";
document.getElementById("orders_content").innerHTML=response;
});
I have proven and tested this code and it works.
I have had this before.
Basically you have a scope problem - you have something like this in your sendReq() function?
if (window.ActiveXObject)
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
And so when you make a second request, the xmlhttp object is over-ridden
You need to create a closure where your xmlhttp objects don't clash
eg
function sendReq(url, callbackFunction)
{
var xmlhttp
if (window.ActiveXObject)
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
... probably some other stuff here, setting url etc ...
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4&&xmlhttp.status='200')
{
if (callbackFunction) callbackFunction(xmlhttp.responseText);
}
}
.. probably more stuff here ( including xmlhttp.send() ) !! ...
}
you can then pass the callback function as a parameter and when the data is successfully loaded, it will be passed to the callback function. Note that you will need to pass the actual function, not just its name (so no quotes around the function name)
Alternatively, you could do what i do which is just use jQuery - works for most of my js problems ;)
Hope this helps
In fact it is possible to run multiple async xhr call but you have to give them an unique id as parameter to be able to store and load them locally in your DOM.
For example, you'd like to loop on an array and make a ajax call for each object. It's a little bit tricky but this code works for me.
var xhrarray={};
for (var j=0; j<itemsvals.length; j++){
var labelval=itemsvals[j];
// call ajax list if present.
if(typeof labelval.mkdajaxlink != 'undefined'){
var divlabelvalue = '<div id="' + labelval.mkdid + '_' + item.mkdcck + '" class="mkditemvalue col-xs-12 ' + labelval.mkdclass + '"><div class="mkdlabel">' + labelval.mkdlabel + ' :</div><div id="'+ j +'_link_'+ labelval.mkdid +'" class="mkdvalue">'+labelval.mkdvalue+'</div></div>';
mkdwrapper.find('#' + item.mkdcck + ' .mkdinstadivbody').append(divlabelvalue);
xhrarray['xhr_'+item.mkdcck] = new XMLHttpRequest();
xhrarray['xhr_'+item.mkdcck].uniqueid=''+ j +'_link_'+ labelval.mkdid +'';
console.log(xhrarray['xhr_'+item.mkdcck].uniqueid);
xhrarray['xhr_'+item.mkdcck].open('POST', labelval.mkdajaxlink);
xhrarray['xhr_'+item.mkdcck].send();
console.log('data sent');
xhrarray['xhr_'+item.mkdcck].onreadystatechange=function() {
if (this.readyState == 4) {
console.log(''+this.uniqueid);
document.getElementById(''+this.uniqueid).innerHTML = this.responseText;
}
};
}
}
You have to set each xhr object in a global variable object and define a value xhrarray['xhr_'+item.mkdcck].uniqueid
to get its unique id and load its result where you want.
Hope that will help you in the future.