I am new to titanium and and want to call a web service from my titanium app.
The webService returns the json response.
As I am aware of calling the webService using XMLRPC but very confused regarding json.
Until now, I know that we have to create the HTTPClient.
var request = Titanium.Network.createHTTPClient();
request.open("POST", "http://test.com/services/json");
request.onload = function() {
var content = JSON.parse(this.responseText);//in the content i have the response data
};
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //did not understand this line
request.send();
Now the problem is if my url(endpoints) have many WebServices, so where i will give the method name i.e WS name which is to be called.
From the API documentation of Titanium mobile the function open i.e. request.open accepts 3 parameters:
method name (http method name)
url of request
async (boolean property) by default true.
In the above code what is "POST" doing there?? and if my WS name is system.connect then where i will be mentioning that in code?
And what if the WS needs parameter, so how can we send the parameter to the webService form the above code.
I know that request.send() can be used to send parameter but how ??
To invoke a webservice you should:
// create request
var xhr = Titanium.Network.createHTTPClient();
//set timeout
xhr.setTimeout(10000);
//Here you set the webservice address and method
xhr.open('POST', address + method);
//set enconding
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
//send request with parameters
xhr.send(JSON.stringify(args));
// function to deal with errors
xhr.onerror = function() {
};
// function to deal with response
xhr.onload = function() {
var obj = JSON.parse(this.responseText);
};
address is your webservice url.
method is the method you desire to invoke.
address+method is a URL, in your example: "http://test.com/services/json" the method invoked would be named json.
args: is a json object where it's variable names should have the exact same name as the webservice parameters. You can create a the parameters object like this:
var args = {};
args.parameter1 = 'blabla';
args.parameter2 = 'blaaaa';
Related
I'm trying to send json data from my web app to my python flask api, my server is receiving the POST rqeuest & is receiving data, the issue is that it's not receiving json data rather the string b''
This is the javascript code I got to send the json data to my api
function onSubmit() {
document.getElementById("orderbutton").disabled=true;
setTimeout('document.getElementById("orderbutton").disabled=false;',3000);
var request = new XMLHttpRequest();
var url = "http://127.0.0.1:5000/api/order";
request.open('POST', url, true)
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.onload = function() {
var response = JSON.parse(request.responseText)
console.log(response)
}
request.send(JSON.stringify({"id": document.getElementById("order").value.trim()}))
}
edit: it's not an issue with document.getElementById("order").value.trim() because when I console.log it, I get the input I put in my <input> field
Try editing your send() line to
request.send(JSON.stringify({id: document.getElementById("order").value.trim()}));
Change is from "id" to id
use .decode('utf-8'), Let me know the result.
I am working on a site, which uses a 3rd party library to launch a pop up to collect users email addresses.
After the user submits the email address, the 3rd party API is called, following the format https://<API-URL>/collectemail?email=test%40test.com
I want to run a function when that API is called and pass it the email param. How can I listen for that event and then trigger my function?
The best way would be to fork the library and modify it so that, when the API is called, the library code itself calls the code on your site with the email parameter.
If that's not possible, your only other option is to monkeypatch XMLHttpRequest so as to intercept requests, such as with:
// Your code, make sure this runs first:
const origXHR = window.XMLHttpRequest;
window.XMLHttpRequest = function() {
const xhr = new origXHR();
xhr.open = (method, url) => {
origXHR.prototype.open.call(xhr, method, url);
console.log('Connection just opened to:', url);
}
return xhr;
};
// Library code:
const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://example.com/?email=test%40test.com');
xhr.send();
Heres my email sending function:
function send() {
var key = "dJdJekCVAFIqvUJ13DEczZjgIh_4MyeIGEHz2GBYKFe";
var message_name = "defender_send_message";
var data = {};
data.value1 = document.getElementById('textBox').value;
data.value2 = localStorage.getItem("AdminsEmail");
var url = "https://maker.ifttt.com/trigger/" + message_name + "/with/key/" + key;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
console.log("Message Sent");
}
}
}
xmlhttp.open('POST', url, true);
xmlhttp.responseType = 'json';
xmlhttp.send(new FormData(data));
}
I wanted to create an email sending function with only pure js, not jquery or anything. I get the following errors when i click send:
(ignore the first error i fixed that already)
I had a jquery function that worked (but i had to get rid of it):
var message = localStorage.getItem("Message");
console.log(message + localStorage.getItem("AdminsEmail"));
var key = "dJdJekCVAFIqvUJ13DEczZjgIh_4MyeIGEHz2GBYKFe"; // << YOUR KEY HERE
var message_name = "defender_send_message"; // << YOUR MESSAGE NAME HERE
var url = "https://maker.ifttt.com/trigger/" + message_name + "/with/key/" + key;
$.ajax({
url: url,
data: {value1: message,
value2: localStorage.getItem("AdminsEmail")},
dataType: "jsonp",
complete: function(jqXHR, textStatus) {
console.log("Message Sent");
}
});
why would this work and my other function not?
EDIT 2 : Since it seems the endpoint doesn't actually return JSON, I think your original jQuery code wasn't correct either. You need to do more research into this iftt.com platform and how to use it. From what I can tell, it's meant to be used in a mobile app, not in the browser- it would be a normal POST XHR then, and CORS doesn't apply to mobile apps. They have this page for testing the endpoint- notice that it gives you an example using curl, a command-line tool, where again CORS doesn't apply. So I think you need to rethink things, this service is not designed to be used from a browser, like you are trying to do.
EDIT: since it turns out you are actually trying to use JSONP and not a plain XHR, all you need to do is implement that without jQuery- create a script tag with the server's URL and add a URL parameter to define your callback function to handle the data. This answer should give you the solution.
In your case the code might look like this :
http://www.codeply.com/go/bp/VRCwId81Vr
function foo(data)
{
// do stuff with JSON
console.log(data)
}
var script = document.createElement('script');
script.src = "https://maker.ifttt.com/trigger/defender_send_message/with/key/"+
"dJdJekCVAFIqvUJ13DEczZjgIh_4MyeIGEHz2GBYKFe?callback=foo";
document.getElementsByTagName('head')[0].appendChild(script);
Note that this doesn't work for me(but with your code, you would get Message sent printed to the console, so maybe you thought it was working?)- the response isn't JSON. Most likely the endpoint isn't actually meant to be used for JSONP?
My answer below only applies if you are trying to do a regular XHR in a browser without JSONP.
This happens because of the Cross Origin Resource Sharing policy of your browser. Your code is hosted at localhost, and it is trying to access a resource hosted at maker.ifttt.com through an XmlHttpRequest. In order to allow this to happen, the server at maker.ifttt.com would need to be configured to allow access from the localhost origin. Presumably you can not make that change as you don't control that server.
In your case, the best solution would be to make the request to maker.ifttt.com through your own server- CORS doesn't apply for server-to-server requests. Send the XmlHttpRequest to your server, take the data regarding the email from the request URL parameters, and then make the request to maker.ifttt.com using that data.
We can create XMLHttpRequest object and then can use it later for another request like :-
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function(){ } // something
xhr.send(null);
There will be a search box and when we enter something in it, it sends an ajax request, but if the user entered more so we will cancel that previous ajax request and create new.
If we want to send another ajax request by same object, we can create an xhr object for that search box to be sure that there will be only one ajax request at a time so if we need to send another request, will will do like :-
xhr.abort()
xhr.open()
xhr.send(null);
I'm using jQuery for portability across browsers, and I want something similar to the above, meaning an XHR (or wrapped XHR) object, that can be used again and again and can also cancel previous request.
How we can do that in jQuery ?
Try using a function to return $.get() , .abort()
var current;
var request = function(url) {current = $.get(url); return current};
request(url); current.abort();
request(url).then(function(data) {
// do stuff
}, function err(jqxhr, textStatus, errorThrown) {
// do stuff with error
});
I've got the following synchronous request...
var xhr = new XMLHttpRequest();
xhr.open("GET",uri,false);
xhr.send(null);
I've read http://www.w3.org/TR/XMLHttpRequest/#the-open-method and it appears that this doesn't allow for extra parameters. Basically I'd like to send other data such as postdata and useragent how would I do this using AJAX?
var strResult;
var xhr = new XMLHttpRequest();
xhr.open("POST",uri,false);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send("id=1&user="+txtUser.value+"&password="+txtPassword.value);
strResult=xhr.responseText;
i'm not 100% sure, but i think you can pass .send() extra parameters.