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.
Related
I am working on a scenario, where i need to cancel third party library request based on some condition and then unblock if condition evaluates to false. Let us assume that third party URL is being loaded with following URL:
https://cdn-thirdparty.com/...
Now, once it is loaded, it captures user clicks on the application and sends data as another URL:
https://cdn-info-thirdpart.com/...
Now, say i want to block all the requests to URL which contains thirdparty in it.. How do i achieve this in Vanilla Javascript...
P.S: I do not have access to remove the library from code, instead i have to do some engineering that requests are getting blocked based on some conditions(we can assume any) and then getting unblocked on falsy condition.
The code i tried to intercept all XMLHttpRequest is as below and i do get URL, method of call but i need to block it now and then unblock.
let oldXHROpen = window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
// do something with the method, url and etc.
this.addEventListener('load', function() {
// do something with the response text
console.log('load: ' + url, method);
});
return oldXHROpen.apply(this, arguments);
}
Source of above code: https://medium.com/#gilfink/quick-tip-creating-an-xmlhttprequest-interceptor-1da23cf90b76
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.
I'm pretty new to javascript and am working on an embedded system which decodes video over IP.
I have written a small app for setting up and changing channels using javascript and included a key handler for remote controls and an event handler so I can take some action or present a message if video stops or the network goes down, but now I also want to set up an automatic HTTP POST that gets sent when I change channel to include some data about the device and the url currently being played.
This is a small embedded hardware device running busybox, so I can't use Ajax or add any other normal web technologies, I just need to use Javascript to send a HTTP POST triggered by events I am monitoring, so my first goal is to be able to press a button and send that POST message then work out when to trigger it later.
Anyone familiar with doing such things that can give me a quick overview of how to send a post to a known listening device/location and include data in it?
Many thanks
This is easy if your Javascript engine supports XMLHttpRequest (XHR), which is ubiquitous on the web. Google it or see this page for details. I've provided a code snippet below. Read it carefully, particularly the comments on "async" being true and closures in response handlers. Also, this code is super lightweight as far as Javascript goes and I would expect it would work fine on just about any contemporary hardware footprint.
var url = "http://www.google.com/";
var method = "POST";
var postData = "Some data";
// You REALLY want shouldBeAsync = true.
// Otherwise, it'll block ALL execution waiting for server response.
var shouldBeAsync = true;
var request = new XMLHttpRequest();
// Before we send anything, we first have to say what we will do when the
// server responds. This seems backwards (say how we'll respond before we send
// the request? huh?), but that's how Javascript works.
// This function attached to the XMLHttpRequest "onload" property specifies how
// the HTTP response will be handled.
request.onload = function () {
// Because of javascript's fabulous closure concept, the XMLHttpRequest "request"
// object declared above is available in this function even though this function
// executes long after the request is sent and long after this function is
// instantiated. This fact is CRUCIAL to the workings of XHR in ordinary
// applications.
// You can get all kinds of information about the HTTP response.
var status = request.status; // HTTP response status, e.g., 200 for "200 OK"
var data = request.responseText; // Returned data, e.g., an HTML document.
}
request.open(method, url, shouldBeAsync);
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
// Or... request.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
// Or... whatever
// Actually sends the request to the server.
request.send(postData);
I've got an issue similar to this question here:
Javascript and AJAX, only works when using alert()
I have an AJAX call to update a field in the database when finalizing a form. However, the call doesn't seem to be reaching the controller. When I put an alert in, it works. I've currently got it set to synchronous because of the issue, but even then, without the alert, it only reaches the controller about 1 in every 5 or six times. This is the AJAX bit:
function finalize() {
if (!confirm("Are you sure?"))
return;
$("#finalizebutton").attr('disabled', 'disabled');
var request = new XMLHttpRequest();
var url = "/Operation/Finalize/";
request.open("GET", url, false);
request.send();
$("#otherformstuff").attr('disabled', 'disabled'); //a few disable calls
}
On the control side I have approximately:
public ActionResult Finalize()
{
db.setfinalized(true); //breakpoint here that only gets hit about 1 in 5 tests
return Content("Finalized");
}
Even when there is an alert shoved in there it sometimes doesn't work.
Oddly enough, I put an alert for request.responseText and it gave me the response from the control without the control ever actually processing it...
Any thoughts on this are appreciated.
Because you tell it to be synchronous.
Your problem is with this line:
request.open("GET", url, false);
The open method takes 3 arguments. Method, url, and the third is a boolean that tells it whether or not the request should be asynchronous.
Just change the false to true, and the request will be async.
request.open("GET", url, true);
But you could also just replace that entire block of XHR code with this one line..
$.get('/Operation/Finalize/');
We've all seen some examples in AJAX tutorials where some data is sent. They all (more or less) look like:
var http = createRequestObject(); // shared between printResult() and doAjax()
function createRequestObject() { /* if FF/Safari/Chrome/IE ... */ ... }
function printResult()
{
if (http.readyState == 4) { ... }
}
function doAjax() {
var request = 'SomeURL';
http.open('post', request);
http.onreadystatechange = printResult;
data = ...; // fill in the data
http.send(data);
}
// trigger doAjax() from HTML code, by pressing some button
Here is the scenario I don't understand completely: what if the button is being pressed several times very fast? Should doAjax() somehow re-initialize the http object? And if if the object is re-initialized, what happens with the requests that are being already on air?
PS: to moderator: this question is probably more community-wiki related. As stated here (https://meta.stackexchange.com/questions/67581/community-wiki-checkbox-missing-in-action) - if I've got it right - please mark this question appropriately.
Since AJAX has asynchronus nature, with each button click you would raise async event that would GET/POST some data FROM/TO server. You provide one callback, so it would be triggered as many times as server finishes processing data.
It is normal behaviour by default, you should not reinitialize of http object. If you want to present multiple send operation you have to do that manually (e.g. disabling button as first call being made).
I also suggest to use jQuery $.ajax because it incapsulate many of these details.
Sure that numerous libraries exist nowadays that perform a decent job and should be used in production environment. However, my question was about the under-the-hood details. So here I've found the lamda-calculus-like way to have dedicated request objects per request. Those object will obviously be passed to the callback function which is called when response arrives etc:
function printResult(http) {
if (http.readyState == 4) { ... }
...
}
function doAjax() {
var http = createRequestObject();
var request = 'SomeURL';
http.open('get', request);
http.onreadystatechange = function() { printResult(http); };
http.send(null);
return false;
}
Successfully tested under Chrome and IE9.
I've used a per-page request queue to deal with this scenario (to suppress duplicate requests and to ensure the sequential order of requests), but there may be a more standardized solution.
Since this is not provided by default, you would need to implement it in JavaScript within your page (or a linked script). Instead of starting an Ajax request, clicking a button would add a request to a queue. If the queue is empty, execute the Ajax request, with a callback that removes the queued entry and executes the next (if any).
See also: How to implement an ajax request queue using jQuery