How to call PHP function from Javascript (ideally without AJAX) [duplicate] - javascript

This question already has answers here:
Call php function from JavaScript
(5 answers)
Closed 5 years ago.
Don't really know AJAX that well.. Here is the issue.
I am reading a database within the PHP function that populate some global variables, I can access the variables ok, but I need the php function to be called regularly.
<?php
function thatIwant()
{
//read database
return 10;
}
echo("
<script>
function refreshDiv()
{
//// this is where I need to call the above function.
var refresher = setTimeout('refreshDiv()', 2000);
}
</script>
");
?>

You can't call a PHP function regularly from Javascript without the use of an XmlHttpRequest. PHP is executed when the page is first requested. With an XHR, you could do the following:
function refreshDiv() {
setTimeout(function() {
var xhr = new XmlHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
document.getElementById("refreshDiv").innerHTML =
xhr.responseText;
}
};
xhttp.open("GET", "yourPHPEndpoint.php", true);
xhttp.send();
}, 1000);
}
This would allow you to query your PHP file continuously, and update the contents of the div with the result of the query. This can also be done through jQuery with $.ajax or $.get.

Related

Using a json value as a global variable in a script outside of a function [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 4 months ago.
I can't find a way to use the value obtained from the JSON function from ipify.org.
I need to use this value in another function, not just write it in HTML like in the examples on ipify.org.
I'm trying to assign a value to the window variable, but it can also be done in another way. I am trying to use the "javascript" example on the site: https://www.ipify.org/
<script type="text/javascript">
function getIP(json) {
window.ipa = json.ip;
}
alert(window.ipa); //return "undefined"
</script>
<script type="text/javascript" src="https://api.ipify.org?format=jsonp&callback=getIP"></script>
You have to make the request to and capture the response from api.ipify.org in your script, there are many ways to do this, I used the old, native XMLHttpRequest API.
You also need to attach this function call to an event (I used "onload" bellow).
Example:
function xhrget(items, route, callback){
const xhr = new XMLHttpRequest();
xhr.open('GET', route);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.timeout = 1000;
xhr.send(encodeURI(items));
xhr.ontimeout = function(e){
callback('404');
};
xhr.onreadystatechange = function () {
if(xhr.readyState === 4 && xhr.status === 200) {
callback(xhr.responseText);
}
if(xhr.status >= 500 && xhr.status < 600){
callback('An error occurred, please wait a bit and try again.');
}
if(xhr.status === 404) {
callback('404');
}
};
}
function getIP() {
xhrget(null, "https://api.ipify.org", (ip) => {
console.log(ip);
window.ipa = ip;
alert(window.ipa); //return "undefined"
});
}
window.addEventListener('load', (event) => {
getIP();
});

Deprecation Synchronous XMLHttpRequest, pure JavaScript [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
i use this javascript code for a API request to get a JSON.
function loadJSON(url) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType('application/json');
xobj.open('GET', url, false);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == '200') {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
returnval = JSON.parse(xobj.responseText);
}
};
xobj.send(null);
return returnval;
}
The code is in a mouse-click event. The full URL is generated with data from the mouse click. The code is only work with sync. I have tested the code with async, but with this the code don't work.
xobj.open('GET', file, true, null, null);
With sync, the console write:
[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
OK, hey! There a many Threads with this question, but i don't found a solution. I use pure JavaScript, no Ajax, no JQuery.
You almost have it written asynchronously. Pass in a callback function to get your returnval.
function loadJSON(url, callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType('application/json');
xobj.open('GET', url);
xobj.onreadystatechange = function() {
if (xobj.readyState == 4 && xobj.status == '200') {
returnval = JSON.parse(xobj.responseText);
callback(returnval);
}
};
xobj.send(null);
}
loadJSON('https://jsonplaceholder.typicode.com/users', function(result) {
console.log(result)
});

Unique function for ajax request not working [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I'd like to create unique function for ajax post request.
This is actual source code:
function doAjax(url, postData) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
return xhttp.responseText;
}
};
xhttp.open("POST", url, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(postData);
}
console.log( doAjax('shipment.php', 'fname=test1&lname=test2') );
But it's not working, the console shows "undefined".
But, if I change return on alert() - everything is OK.
So, why return now working ?
Your function doAjax does not actually return something. When you do xhttp.onreadystatechange = function() {...}; you just set a callback for an event that means this function isn't triggered immediately. No matter what you want to do, you will have to do (or trigger) it inside your callback.

JQM - How to get dynamic data when page loads using XMLHttpRequest? [duplicate]

This question already has answers here:
How to return AJAX response Text? [duplicate]
(2 answers)
Closed 9 years ago.
I use pageinit to load page. I call an XMLHttpRequest to send and get request to PHP programs on Linux, using RESTful API on server side. The server side accept an array I send to it and echo an JSON back. It all work well. However, HTTP_GET functions returns back to page and displays content before it finished and got a response from server.
How can I prevent it from going back before it responded?
pageinit
$(document).on("pageinit","#quote_open1",function(){
alert('pageinit quote_open1');
openPage(); });
openPage
function openPage(url, jsontest){
var jsonResponse=HTTP_GET( url, jsontest);
alert('!!!!!!!!!!!!!!!!-->'+jsonResponse);
}
HTTP_GET
function HTTP_GET( url, jsonToSend){
alert('START HTTP_GET');
var jsonResponse;
//send get request to server
xhr = new XMLHttpRequest();
xhr.open("GET",url+"jsonToSend",true); //open server connection
xhr.send();//this is where json string will be sent out
//
//this function send
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4) //read server response
{
alert(xhr.readyState);
jsonResponse=xhr.responseText;
alert("!!!jsonResponse="+jsonResponse);
alert("!!!xhr.responseText"+xhr.responseText);
return "server returned a response 1"; //RETURNS this all the time
}
};
alert('END HTTP_GET');
if (xhr.readyState == 4) return "server returned a response 2"; //want to return this when leaves this function
return "stil in progress returns before it's finished";
};
(this 3 functions are in different js)
Thanks.
what you miss here is the fact that xhr is asynchrone, so your function HTTP_GET returns before the request is done.
You could use a callback function like this :
$(document).on("pageinit","#quote_open1",function(){
console.log('pageinit quote_open1');
openPage(); });
function openPage(){
var doTheJob = function(jsonResponse){ console.log('jsonResponse : '+jsonResponse); }
HTTP_GET( url, doTheJob);
}
function HTTP_GET( url,callBackFunc){
console.log('START HTTP_GET');
var jsonResponse;
//send get request to server
xhr = new XMLHttpRequest();
xhr.open("GET",url,true); //open server connection
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4) //read server response
{
callBackFunc(xhr.responseText);
}
};
xhr.send();//this is where json string will be sent out
//
console.log('END HTTP_GET');
};

Simultaneous ajax calls

I'm trying to make 2 (or more) ajax calls simultaneously. I don't want to use jQuery, only pure JavaScript.
Most of the time, it works. data1 will output data from sample.com/ajax1 and data2 will output data from sample.com/ajax2, but sometimes (1 from 10) the second AJAX call will display result from the first one.
Why is this happening? Both AJAX requests are requesting data from the same domain, but from different URLs. Is there any way how to prevent this behavior?
Here is the script:
// First AJAX
var xmlhttp1;
// Second AJAX
var xmlhttp2;
if (window.XMLHttpRequest) {
xmlhttp1 = new XMLHttpRequest();
} else {
xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp1.onreadystatechange = function() {
if (xmlhttp1.readyState == 4 && xmlhttp1.status == 200) {
data = JSON.parse(xmlhttp1.responseText);
console.log('data1: ' + data);
}
}
xmlhttp1.open("GET", "http://sample.com/ajax1", true);
xmlhttp1.send();
if (window.XMLHttpRequest) {
xmlhttp2 = new XMLHttpRequest();
} else {
xmlhttp2 = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp2.onreadystatechange = function() {
if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {
data = JSON.parse(xmlhttp2.responseText);
console.log('data2: ' + data);
}
}
xmlhttp2.open("GET", "http://sample.com/ajax2", true);
xmlhttp2.send();
First of all, I recomment wrapping your xmlHttpRequest generation/handling in a function, so you don't duplicate code that much.
The problem you have there is that the data variable is global, so both ajax callbacks are using the same variable. You can fix it using the var keyword in both calls.
xmlhttp2.onreadystatechange = function() {
if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {
var data = JSON.parse(xmlhttp2.responseText);
console.log('data2: ' + data);
}
}
Because you're not properly encapsulating data. The way you have it written, data is a global object, so it's available to be modified by either ajax call. Since ajax calls are asynchronous, this will lead to unpredictable values for data.
The problem is probably because you forgot to define data inside your function
anyway with this function you can create multiple requests and have more control over them..
var req={};
function ajax(a){
var i=Date.now()+((Math.random()*1000)>>0);
req[i]=new XMLHttpRequest;
req[i].i=i;
req[i].open('GET',a);
req[i].onload=LOG;
req[i].send();
}
function LOG(){
console.log(this.i,this.response);
delete req[this.i];//clear
}
window.onload=function(){
ajax('1.html');
ajax('2.html');
ajax('3.html');
}
uses xhr2... you need to modify the code to make it work with older browsers.

Categories

Resources