I am using the easybitcoin.php script here:
(It makes json-rpc calls to bitcoind)
I've made a seperate php file, that retrieves the data from the easybitcoin.php file such as balance, accounts..etc. And spits it out on a page.
When making a json-RPC call, such as:
retrieve_once('easybitcoin.php');
print_r($<username>->getbalance($_SESSION['username']) );
You need to refresh the page to get your updated balance, how would you make it dynamic where the user does not have to refresh the page.
Thanks for any help.
Make an AJAX GET request:
var client = new XMLHttpRequest();
client.onreadystatechange = handler;
client.open("GET", "yourPhpFile.php");
client.send();
Create the handler:
function processData(data) {
// taking care of data
}
function handler() {
if(this.readyState == this.DONE) {
if(this.status == 200 &&
this.responseXML != null) {
// success!
processData(this.responseXML);
return;
}
// something went wrong
processData(null);
}
}
In the processData function do whatever you want with the data you receive from the server.
In the yourPhpFile.php you should include the easybitcoin.php file and make the necessary calls.
Now you can encapsulate your AJAX request in setInterval(), this way it will periodically get updates.
Related
I know I can take post data from WordPress / PHP and pass it into JS by using AJAX. But is it possible to do this the other way round? i.e. create a JS event listener on a form and the pass the values back to the server to be executed using a PHP function.
Yes, definietly. You pretty much answerd the question yourself.Here is some code to get you started.
document.querySelector(".whateverFormSubmit").click(function(e){
e.preventDefault();
let formInfo = document.querySelector("input1");
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.querySelector("response").innerHTML = this.responseText;
}
};
xhttp.open("POST", "ajax.php", true);
xhttp.send('formInfo=' + formInfo);
})
Pay attention to preventDefault(), if you don't use it your form will be posted through HTTP body, thus rendering your AJAX useless.
And there you go, you posted information from frontend to backend without refreshing the page. Of course you can mess around with sending a JSON, but I kept it simple.
I'm a client-side newbie learning the ropes, and need to clarify Ajax concepts.
e.preventDefault(); is a typical method of preventing form submission (page refresh) in JS.
One use case where the above is handy is Ajax-based form submission. Sample code is:
function overwrite_default_submit(e) {
// block the default behavior
e.preventDefault();
// create and populate the form with data
var form_data = new FormData();
form_data.append("reply", text_field.value);
// send the form via AJAX
var xhr = new XMLHttpRequest();
xhr.open('POST', e.target.action);
xhr.setRequestHeader("X-CSRFToken", get_cookie('csrftoken'));
xhr.send(form_data);
}
I have two questions:
1) Imagine the POST request is being sent to a function that ends with a redirect to a different URL. For example, I use Django to develop web applications; a typical Django view may end up with return redirect("home") where home is the home page of the said app. In such a scenario, how does preventDefault() prevent the redirect statement in server-side code from executing? I'm trying to understand the exact mechanics behind it.
2) What if one wanted page refresh (or redirect) to proceed normally after an Ajax POST request? What tweaks need to be made? Would love to see an illustrative example to clarify my concepts.
I'm well-versed in Django (Python) so in case you need to show server-side code, Django would be a good example.
Note: prefer to stick to pure JS for this, since I'm learning JS these days. JQuery's on my radar, but only after I've mastered the fundamentals of JS.
The preventDefault() cancels the event, Default action that event of element will not occur. This will simply halt further execution of javascript code after that statement.
For i.e.
- Clicking on a submit button, prevent it from submitting a form.
- Clicking on a link, prevent the link from following the given
URL
To redirect to the next page or to add notification or may be to add html through javascript, but here is to redirect only.
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) //Here we need to check OK response and last state of ajax call.
{
window.location.href = 'REDIRECT_URL'
window.location.reload() // To refresh page.
}
};
=== I've added that in your function ===
function overwrite_default_submit(e)
{
// block the default behavior
e.preventDefault();
// create and populate the form with data
var form_data = new FormData();
form_data.append("reply", text_field.value);
// send the form via AJAX
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) //Here we need to check OK response and last state of ajax call.
{
window.location.href = 'REDIRECT_URL'
window.location.reload() // To refresh page.
}
};
xhr.open('POST', e.target.action);
xhr.setRequestHeader("X-CSRFToken", get_cookie('csrftoken'));
//xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(form_data);
}
Now in case of Django you need also need to add view / call proper action that should return either json or xml.
from django.http import JsonResponse
def some_view(request):
return JsonResponse({"key": "value"})
To know how ajax work you can check here https://www.w3schools.com/xml/ajax_intro.asp
1) Ajax request should not receive redirect response. Usually it supposed to be a valid json-string. Django has a JsonResponse for this purpose. If you want your django view to process ajax data you should check it on your backend side, for example:
if request.is_ajax():
return JsonResponse({'data': data})
2) You can do redirect with your javascript code, for instance:
window.location.href = 'https://stackoverflow.com'
I have this following js code to send an audio file to servlet. I need to send two more additional parameters to the servlet. Following is my current code
form = new FormData(),
request = new XMLHttpRequest();
form.append("file",blob, filename);
request.open(
"POST",
"AudioToText",
true
);
request.send(form);
CAn anyone help me with js code how to add additional two parameters like id/pass in this request and how to fetch them in the servlet. Thanks in advance.
The second param in request.open() suppose to point to the file that will process the data in absolute an absolute link, there's also another property of the XMLHttpRequest type called onreadystatechanged which expects a callback that will check to see whether or not the request was successful
Example Code - ignore the lines with self, this those are just variables pointing to methods/properties and are not dependent to perform a request:
// if an Object to connect to server was created begin transfer
if (this.xhr) {
var processData = function () {
// if everything is ok carry on
if (self.xhr.readyState === 4 && self.xhr.status === 200) {
if(self.responseType === "text"){
self.Success(self.xhr.responseText);
}else{
self.Success(self.xhr.responseXML);
}
}
// if something fails along the way else execute failure method
else if (self.xhr.status !== 200 && self.xhr.readyState === 4) {
// something went wrong
}
};
// open connection
this.xhr.open(this.method, this.host, true);
// set up the connection to a method to process the data
//noinspection JSPrimitiveTypeWrapperUsage
this.xhr.onreadystatechange = processData;
// send the data
this.xhr.send(this.postData);
I am trying to solve this problem of mine: I am making two ajax calls on window.load, and it seems like second AJAX response rewrite first one before I function can proceed it or I am making something wrong... anyway I am not able to solve it without making calls synchronous and i don't really want to do that for obvious reasons.
So Here is my code (Javascript) To Create new XMLHttpRequest:
function createRequest(){
if(window.XMLHttpRequest)
return new XMLHttpRequest;
else
return new ActiveXObject("Microsoft.XMLHTTP");
}
My send request function (to sending them)
function sendRequest( url, callback){
request = createRequest();
if(typeof callback === 'function'){
request.onreadystatechange = callback();
}
request.open("GET", url, true);
request.send();
}
and finally my callback
function handleData(){
return function(){
if (request.readyState == 4 && request.status == 200) {
serverResponse = JSON.parse(request.responseText);
switch(Object.keys(serverResponse)[0]){
case "a": function1(serverResponse.a,"a"); break;
case "b": function2(serverResponse.b,"b"); break;
}
}
}
I am creating my calls like this:
window.onload = function () {
sendRequest('url' , handleData);
sendRequest('url2', handleData);
}
NOTICE: As you can see, this is simplified version of my code.
In a switch I am calling function1 and 2 these functions are really handling JSON response from server. I am making calls on two different urls on a same domain with different json response.
Also when I make only one call it works well(Both of them)... Problem only occurs when I am trying to make 2 in a row - And when i make two calls only second one is processed right. Thats why i am thinking that second overwrite first.
I tried to make two functions to handleData so there was handleData1() and handleData2() instead of single handleData() with switch so i call them like this:
window.onload = function () {
sendRequest('url' , handleData1);
sendRequest('url2', handleData2);
}
but i run into problem where second ajax response(always the second call) but again only second one succeed. And then i put console.log(request) in both of em, and i get only JSON for second function trying to be processed with second function.(nothing about first one) Sometimes is second function called more times like 4.
Btw handleData2 does not depend on data from handleData1.
If any more questions please do ask :) Thanks
request = createRequest();
creates a global variable. Every call to the function will override that variable, which is what you are experiencing.
Create a local variable and pass the value to the callback:
var request = createRequest();
if(typeof callback === 'function'){
request.onreadystatechange = callback(request);
}
// ...
function handleData(request) {
// ...
}
I am able to connect to the webservice. That service has a number of operations that can be executed and return a result. One is called helloWorld. I would like to perform that operation. Right now I specify the web service file, but i need to further specify the method in the file to be executed. Here is what I have:
function soapReq() {
var ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
// Get the data from the server's response
console.log(ajaxRequest.responseText);
}
}
ajaxRequest.open('POST', 'http://theWebServiceNameThatICannotGiveOut', true);
ajaxRequest.send(null);
}
Can I add the operation to be performed onto the end of the url or something?
You should find something on the server, or find the page that has the hello world operation. Then you can make a request to that page (see example below), and you don't need it to be a POST request, just use GET.
Example:
// something like this:
ajaxRequest.open('GET', 'http://site.xxx/helloWorld.php', true);
// or this
ajaxRequest.open('GET', 'http://site.xxx/helloWorld.php?somevar=somevalue', true);
// or also this
ajaxRequest.open('GET', 'http://site.xxx/somepage.php?op=helloWorld', true);
But I can't help you more than this if you can't provide the site you're trying to make the request to. You should ask someone that works on it or search on the site itself.