set synchronous:false in GM_xmlhttpRequest not works - gm-xmlhttprequest

I'm tried make an http request with synchronous as false in GM_xmlhttpRequest but does not seem to work.
how do this?
my code:
GM_xmlhttpRequest({
method: "GET",
url: "http://www.google.com/",
synchronous:false,
onload: function(xhr)
{
if(xhr.readyState == 4) {
r = xhr.responseText;
}
}
});
Thanks in advance!

GM_xmlhttpRequest is asynchronous by default.
http://wiki.greasespot.net/GM_xmlhttpRequest

Related

The request sent by jQuery or JavaScript doesn't contain the Header so I received error 405

I have the HTML file and try to send the request from that page with JavaScript or jQuery, but it doesn't send the "header" to the server and it gives me the error 405. I've read related questions and try out some of them but the error code was the same. I use Fiddler to see the final request and in that there is no header as well as the method change to the OPTION!
some of the codes I used:
$.ajax({
url: "URL",
type: "GET",
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'Bearer HASHKEY');},
success: function() { alert('Success!'); }
});
or
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "URL", true);
xhttp.setRequestHeader("Authorization", "Bearer HASHKEY");
xhttp.setRequestHeader('Content-Type', 'text/plain');
xhttp.setRequestHeader('Accept', 'application/json');
xhttp.send();
xhttp.onreadystatechange = function () {
var response = xhttp.responseText;
if (xhttp.readyState == 4 && xhttp.readyState == 200) {
var obj = JSON.parse(response);
// handle data as needed...
alert("obj" +obj);
}
};
Totally speaking I'm looking for a piece of code which can call API from the HTML which is content header: authorization.
Cheers
Try this:
$.ajax({
url: "URL",
type: "GET",
‎headers: {
‎"Authorization": "Bearer HASHKEY"
‎},
success: function() { alert('Success!'); }
});
Also, check that your server configuration supports CORS and explicitly allows the Authorization header.

How to set custom header for PouchDB ajax requests?

I'm using PouchDB 3.2.1.
I'm trying to set Authorization header for all ajax requests:
db.local = new $window.PouchDB(POUCHDB_NAME);
db.remote = new $window.PouchDB(COUCHDB_URI, {
skipSetup: true,
ajax: {
headers: {
'Authorization': 'Basic ' + $window.btoa('admin:admin')
}
}
});
// Replication
db.local.sync(db.remote, {
live : true,
retry: true
});
But it doesn't works. See the screenshot:
In the latest PouchDB this is the preferred way (click here for the docu):
var db = new PouchDB('http://example.com/dbname', {
fetch: function (url, opts) {
opts.headers.set('Authorization', 'token-here');
opts.headers.set('X-Some-Special-Header', 'foo');
return PouchDB.fetch(url, opts);
}
});
I think as described here, you also need to set:
{skipSetup: true}
In your constructor options.

Sencha Touch: Using proxy and POST request and URL generation

I have been trying to do a post request using a proxy. I have tried the direct proxy, rest and ajax proxy, and haven't been able to find a working example for a POST request.
Is it possible? Because all the examples that I have seen seen to be using only GET.
Any working examples, or pointers in this direction?
Also, I couldn't figure what is the correct way to generate URLs for a proxy at run-time, for example, calling a function to return the URL.
It appears that this might not be possible:
http://www.sencha.com/forum/showthread.php?205557-Using-Ext.data.proxy.Ajax-via-a-POST-with-jsonData
If you look at the source code for Ext.data.proxy.Rest you'll see a config object for actionMethods. They're not documented, but you should be able to pass that as a config on your proxy to override it.
For example:
proxy: {
type: 'ajax',
url: 'path/to/foo',
actionMethods: {
create : 'POST',
read : 'POST',
update : 'PUT',
destroy: 'DELETE'
},
reader: {
type: 'json',
rootProperty: 'root',
totalProperty : 'totalCount'
}
}
Easiest example of POST request could be like this:
var obj = new Object();
obj.userId = username;
obj.password = password;
var data = Ext.JSON.encode(obj);
Ext.Ajax.request({
url : 'http://myservice/auth/login?_type=json', // url : this.getUrl(),
method : "POST",
headers: {
'Content-Type': 'application/json'
},
params : data,
useDefaultXhrHeader : false,
withCredentials: true,
success : function(response) {
Ext.Msg.alert("Success", "Welcome "+respObj.user.name);
},
failure : function(response) {
var respObj = Ext.JSON.decode(response.responseText);
Ext.Msg.alert("Error", respObj.status.statusMessage);
}
});
Please note here you can customize url as per your convenience.

sencha touch2 Login examples

I need a cross-domain user login request instance, please help me, thank you!!
My code
Ext.data.JsonP.request({
url: 'http://25.30.2.3:8080/newvbo/applyaction!longin',
params: {
username:'13881901678',
password:'111111',
},
success: function(response, opts) {
alert('1');
},
failure: function(response, opts) {
alert('2');
}
});
My question is, I not receive the server returns the value, I wrong?
You can Try this
Ext.Ajax.request({
method:'GET',
contentType:'application/json; charset=utf-8',
dataType:'json',
url:'http://........Login',
disableCaching: false,
withCredentials: true,
useDefaultXhrHeader: false,
callbackKey: 'callback',
params: {
EmailId:Ext.getCmp('usernametwoway').getValue(),
Password:Ext.getCmp('loginpasswordtwoway').getValue(),
},
success:function(response)
{
console.log(response);
var res = response.responseText;
var jsonarr = Ext.decode(response.responseText);
console.log(jsonarr);
var myres = jsonarr[0].Result;
console.log(myres);
switch(myres)
{
case '1':
console.log("Registration response is successfully");
Ext.Viewport.setActiveItem({xtype:'passengerdetailstwoway'});
break;
case '0':
console.log("Failed");
Ext.Msg.alert("Error","Login Failed",Ext.emptyFn);
break;
Based on the responce you can Specify the Switch case..
Hi #jesse you can try for cross-domain something like this,
Ext.Ajax.request({
url: 'your_url_path',
timeout: 90000,
params: {
withCredentials: true,
useDefaultXhrHeader: false,
username:'13881901678',
password:'111111',
},
success: function(response, o) {
if(response != '') {
alert('1')
}
},
failure: function(response, o) {
alert('2')
}
})
For cross-domain you need put withCredentials: true and useDefaultXhrHeader: false.
I hope help you.
I would like to suggest you a different approach because sending login credentials as GET parameter to remote server over http is not a good idea, instead you should use POST method over HTTPS. Now you would think JSONP doesn't support POST so how can I do this, but if you are going to install your app on Phone or iPad it would do remote call from browser without using JsonP, which means you can use normal AJAX proxy to do whatever you want. Check this out:
How to use json proxy to access remote services during development
Which means this should work:
var obj = new Object();
obj.userId = username;
obj.password = password;
var data = Ext.JSON.encode(obj);
Ext.Ajax.request({
url : 'https://login_url',
method : "POST",
headers: {
'Content-Type': 'application/json'
},
params : data,
useDefaultXhrHeader : false,
withCredentials: true,
success : function(response) {
},
failure : function(response) {
}
});

how to get the server response.responseText after store load extjs 4

I'm having one problem with getting the response.responseText from the server response in extjs 4.
Below is my code to load the store:
store.load({
params: {
'projectid': this.projectid
},
callback: function (records, operation, success, response) {
console.log(records);
console.log(response.responseText);
}
});
Actually, when I made the request with the below function, I properly get the reponse.responseText.
Ext.Ajax.request({
url: 'login/GetLoginCheck.action',
method: 'GET',
params: {
'username': values['username'],
'password': values['password']
},
scope: this,
success: function(response) {
Ext.Msg.alert(response.responseText);
var redirect = response.responseText;
window.location.href = "" + redirect + ".jsp";
},
failure: function(response) {
Ext.Msg.alert('INVALID USERNAME OR PASSWORD');
}
});
So please suggest me how can I get the response.responseText from the store.load() having a callback function.
callback has 3 parameters...
try this :
store.load({
params: {
'projectid': this.projectid
},
callback: function (records, operation, success) {
console.log(operation.response.responseText);
}
});
I have faced a similar problem using Model.load(...), but in my case, operation.response was not defined. So, I have found another way to get it :
Model.load(1, {
success: function () {
// I haven't tested inside this callback yet
},
failure: function (record, operation) {
var response = operation.request.proxy.reader.rawData;
alert(response.message);
}
});
You may also try this..
Ext.create('Ext.data.Store',{
fields[],
proxy:{url:'store_url.json', reader:{type:'json',root:'data'}},
autoLoad:true,
listeners:{
load:function(store, record, success, opts){
var response_text = store.proxy.reader.rawData;
console.log(response_text);
}
}
})
In extjs 3.4 you can use this:
this.historyInvoiceHeaderGrid.store.load({
params:{start:0, limit:20},
callback: function (records, operation, success) {
console.log(this.reader.jsonData);
}});
This property store.reader.jsonData will return full response.
Maybe for someone it would be usefull in extjs 3.
You must set messageProperty in proxy reader in your 'Ext.data.Store'.
reader: {
type: 'json',
root: 'myDataList',
totalProperty: 'myTotalRecord',
successProperty: 'mySuccess',
messageProperty : 'myMsg'
}
when mySuccess returns false then invoked callback: function.
store.load({
params: {start: 0, limit: 15},
callback: function (records, operation, success) {
if (!success) {
try {
Ext.Msg.alert('Sorry !', operation.getError());
// operation.getError() returns myMsg value
}catch (e){
Ext.Msg.alert('Exception !', e);
}
}
}
});
Here is a json return from Java Servlet.
Map<String, Object> myDataMap = new HashMap<>(3);
try {
// Something
myDataMap.put("mySuccess", true);
myDataMap.put("myMsg", "Whats up khomeni !");
} catch (Exception e) {
myDataMap.put("mySuccess", false);
myDataMap.put("myMsg", "Whats wrong with me.");
}
String json = new Gson().toJson(myDataMap);
In Extjs 4.x it is working like this
myStore.load({
url: 'myurl',
method: 'GET',
callback: function(records, operation, success) {
var jsonStr = Ext.JSON.decode(operation.response.responseText);
alert(jsonStr.message);
}
});
In Extjs 5 you have to do like this
myStore.load({
url: 'myurl',
method: 'GET',
callback: function(records, operation, success) {
var message=forecastMethodStore.getProxy().getReader().rawData.message;
}
});
But the key point here is you should set the message in JSON response from java side.
Sample: {"Root":[], "message":"duplicates"}"
Hope this will help someone.