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

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');
};

Related

How to call a php function in javascript [duplicate]

This question already has answers here:
How can I call PHP functions by JavaScript?
(13 answers)
Closed 3 years ago.
i have a function in php .i want to call it inside javascript function .How to do that?
My php function is
<?php
function image_save(){
$img = $_POST['image'];
$folderPath = "C:/xampp/htdocs/";
$image_parts = explode(";base64,", $img);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = base64_decode($image_parts[1]);
$fileName = '1'. '.jpeg';
$file = $folderPath . $fileName;
file_put_contents($file, $image_base64);
print_r($fileName);
$command = escapeshellcmd("python C:/xampp/htdocs/generate_graph.py");
$output = shell_exec($command);
}
?>
You can call an API from js running on your broswser, not directly a PHP function.
If you want to call a PHP function from Javascript, you need to send an XMLHttpRequest to a server on which this function is running. Javascript is running in the browser, at your client computer. And PHP is running on your server, in some datacenter somewhere. Therefore, it's impossible to call a PHP function from your Javascript directly.
The XmlHttpRequest send an http request ( POST | GET | ... ) to a server and wait for it's output. In your case, you would call a php file on a server and wait for it's response.
From Javascript.info
// 1. Create a new XMLHttpRequest object
let xhr = new XMLHttpRequest();
// 2. Configure it: GET-request for the URL
xhr.open('GET', '/yourPhPfileLocationUrl/');
// 3. Send the request over the network
xhr.send();
// 4. This will be called after the response is received
xhr.onload = function() {
if (xhr.status != 200) { // analyze HTTP status of the response
alert(`Error ${xhr.status}: ${xhr.statusText}`); // e.g. 404: Not Found
} else { // show the result
alert(`Done, got ${xhr.response.length} bytes`); // responseText is the server
}
};
xhr.onprogress = function(event) {
if (event.lengthComputable) {
alert(`Received ${event.loaded} of ${event.total} bytes`);
} else {
alert(`Received ${event.loaded} bytes`); // no Content-Length
}
};
xhr.onerror = function() {
alert("Request failed");
};
There is also numerous libraries out there to do way simpler XMLHttpRequest.
You could also submit a form, it might be easier.
<form action="/yourPHPFunctionUrl">
<!-- some inputs -->
<button type="submit">Send me ! </button>
</form>

render_template not rendering the template specified on a POST request [duplicate]

This question already has answers here:
How to replace the entire html webpage with ajax response?
(6 answers)
How to replace innerHTML of a div using jQuery?
(14 answers)
Closed 3 years ago.
In index.html, I'm getting a value stored in localStorage:
<script>
function checkChannel() {
if (localStorage.getItem('channel')) {
const channel = localStorage.getItem('channel');
const request = new XMLHttpRequest();
request.open('POST', '/convert');
// Add data to send with request
const data = new FormData();
data.append('channel', channel);
// Send request
request.send(data);
}
}
</script>
</head>
<body onload="checkChannel()">
.
.
.
This works fine. It is routed to the code below in application.py. The debugger hits the first line in convert() below, so I know it's getting there.
#app.route("/convert", methods=["POST"])
def convert():
channel = request.form.get("channel")
channel_messages = channels_dict[channel]
return render_template("channel.html", channel=channel, channel_messages=channel_messages)
However, channel.html is not being rendered. Instead, it stays on the same page. What am I doing wrong here? I can give more details if needed.
You need to define a request.onload() function. This function will be called after the response is received. so your JS code will be similar to this:
function checkChannel() {
if (localStorage.getItem('channel')) {
const channel = localStorage.getItem('channel');
const request = new XMLHttpRequest();
request.open('POST', '/convert');
// Add data to send with request
const data = new FormData();
data.append('channel', channel);
// Send request
request.send(data);
// 4. This will be called after the response is received
request.onload = function() {
if (request.status != 200) {
// analyze HTTP status of the response
alert(`Error ${request.status}: ${request.statusText}`);
// e.g. 404: Not Found
} else { // show the result
$('body').html(request.response)
}
};
}
}
Please note that you can replace $('body').html('some content') by $('div').html('some content') or $('#some-id').html('some content') based on channel.html file content.
Please find this example.

Symfony 3 - Sending AJAX request as XmlHttpRequest() (javascript) does not pick up request as XmlHttpRequest in backend

I have an ExceptionListener implemented in Symfony3 (also works in Symfony2). The ExceptionListener identifies whether the request was normal HTTP or AJAX (XmlHttpRequest) and generates a response accordingly. When using jQuery .post() or .ajax(), the ExceptionListener returns $request->isXmlHttpRequest() as TRUE, but when using javascript var xhr = new XmlHTTPRequest(), the ExceptionListener returns $request->isXmlHttpRequest() as FALSE. I am using the latter in a small amount of instances where files need to be uploaded via AJAX (which cannot be done using .post() or .ajax().
I am looking for a solution (either frontend or backend) to resolve my ExceptionListener incorrectly picking this up as a normal HTTP request.
Frontend Code:
function saveUser()
{
var form = document.getElementById('userForm');
var formData = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open('POST', '{{url('saveUser')}}', true);
xhr.onreadystatechange = function (node)
{
if (xhr.readyState === 4)
{
if (xhr.status === 200)
{
var data = JSON.parse(xhr.responseText);
if (typeof(data.error) != 'undefined')
{
$('#processing').modal('hide');
$('#errorMsg').html(data.error);
$('#pageError').modal('show');
}
else
{
$('#successMsg').html('User Successfully Saved');
$('#processing').modal('hide');
$('#pageSuccess').modal('show');
$('#userModal').modal('hide');
updateTable();
}
}
else
{
console.log("Error", xhr.statusText);
}
}
};
$('#processing').modal('show');
xhr.send(formData);
return false;
}
ExceptionListener.php (partial)
# If AJAX request, do not show error page.
if ($request->isXmlHttpRequest()) # THIS RETURNS FALSE ON JS XmlHTTPRequest()
{
$response = new Response(json_encode(array('error' => 'An internal server error has occured. Our development team has been notified and will investigate this issue as a matter of priority.')));
}
else
{
$response = new Response($templating->render('Exceptions/error500.html.twig', array()));
}
When using vanilla ajax you need to pass the following header to your ajax request
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

Normal redirect or preload

So on the net I've come across a several ways to preload / redirect a webpage.
Now's the question is this the proper way to handle a redirect with preload (Load the next page async while still showing the current page)
$.get("page.php", function (data) {
document.open();
document.write(data);
document.close();
window.history.pushState("Title", "Title", "/page.php");
$.cache = {};
}, "html");
Or should I better stay with a regular redirect?
window.location = "page.php";
The next page contains a fullscreen video and a soundtrack (audio)
Thanks.
You can use Ajax to load next page asynchronous.
Here is an example of a simple Ajax request using the GET method, written in JavaScript.
AJAX stands for Asynchronous JavaScript and XML, and for the XMLHttpRequest object to behave as AJAX, the async parameter of the open() method has to be set to true: xhr.open('get', 'send-ajax-data.php', true);
get-ajax-data.js:
// This is the client-side script.
// Initialize the Ajax request.
var xhr = new XMLHttpRequest();
xhr.open('get', 'send-ajax-data.php', true); // `true` makes the request asynchronous
// Track the state changes of the request.
xhr.onreadystatechange = function () {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200; // status 200 is a successful return.
if (xhr.readyState === DONE) {
if (xhr.status === OK) {
alert(xhr.responseText); // 'This is the returned text.'
} else {
alert('Error: ' + xhr.status); // An error occurred during the request.
}
}
};
// Send the request to send-ajax-data.php
xhr.send(null);
And at the end you can use below codes to reload or redirect page data:
document.getElementById("myDiv").innerHTML = xhr.responseText;

JSONP Callback is Undefined

I'm a NOOB and I see that other users have encountered a similar problem, but after many hours of frustration, I cannot get a JSONP callback function to work.
I'm trying to extract the "woeid" information from Yahoo geo.places so I can use it to specify the location to obtain weather data. I receive input (such as a zip code) from the "location" id in a form and submit it to Yahoo.
The code is returning an XMLHttpRequest object, which I can read by looking at xhr.responseText in the console, but I can't extract the JSON object that is being passed to the callback function by the server.
I know I must be making a simple error, however I can't figure out what it is. I'm trying to do this through Javascript prior to learning how to retrieve the data using the $.ajax method in jQuery.
Can you tell me where the error is? Here is my code:
// an XMLTHttpRequest
var xhr = null;
/*
* void
* getWoeid()
* gets WOEID from Yahoo geo.places to use in request
* for weather data
*
*/
function getWoeid() {
// instantiate XMLHttpRequest object
try {
xhr = new XMLHttpRequest();
}
catch (e) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
// handle old browsers
if (xhr == null) {
alert("Ajax not supported by your browser!");
return;
}
// construct URL
var userinput = document.getElementById("location").value;
var data = encodeURIComponent("select * from" +
" geo.places where text =" + userinput);
var url = "http://query.yahooapis.com/v1/public/yql?q=" + data + "&format=json& callback=callback";
// get data
xhr.onreadystatechange = handler;
xhr.open("GET", url, true);
xhr.send(null);
}
// callback function
function callback(response) {
woeid = response;
}
/*
* void
* handler()
*
* Handles the Ajax response
*/
function handler() {
// only handle loaded requests
if (xhr.readyState == 4) {
// display response if possible
if (xhr.status == 200) {
var location = woeid;
}
else
alert("Error with Ajax call");
}
}
You can't use an XHR object to request a JSONP result, because of the same origin policy. Also, even if you would make a request locally, using an XHR object to make the request would mean that the callback function would not be called, you would just get the code for calling it in the response.
To get make a JSONP request, you use a script tag:
var script = document.createElement('script');
script.src = url;
document.head.appendChild(script);

Categories

Resources