How to set a timeout on every xhr request - xmlhttprequest

I have this code, now what I want is to set a 3 seconds timeout on it before making the other request again.
function check(num, separator, id) {
var url = "some url"
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var xdata = xmlhttp.responseText;
if (xdata.match("OK")) {
$("#success").append(xdata);
}
else {
$("#error").append(xdata);
}
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}

Related

how to get value from api with flutter

I have fake Api
https://fakemyapi.com/api/fake?id=220e0e14-8c78-45e9-9ef0-6ca516fde5be
and I want to print some data, I used this code
var headers = {
'Cookie': '__cfduid=d99061ead63f349023a08a33868eb7ef81619925287'
};
var request = http.Request('GET', Uri.parse('https://fakemyapi.com/api/fake?id=220e0e14-8c78-45e9-9ef0-6ca516fde5be'));
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
}
else {
print(response.reasonPhrase);
}
and I get this response.
I/flutter (17790): {"first_ame":"Miguel","last_name":"Fay","photo":"https://s3.amazonaws.com/uifaces/faces/twitter/dhooyenga/128.jpg","email":"Keven.Cole#gmail.com","title":"Regional Functionality Developer","job_type":"Supervisor","telephone":["567.700.9452","1-701-720-0774 x9918","1-716-687-6317 x670"],"address":{"zip_code":"20909","street":"Myrtis Pines","city":"West Mekhifort","country":"Greece"},"friends":[{"first_name":"Carlie","last_name":"Kilback","email":"Erich_Emmerich90#gmail.com"},{"first_name":"Clarabelle","last_name":"Runolfsson","email":"Elise_Schroeder#gmail.com"}]}
so how to print the first name and zip code?
finally I got this solve by trying again and again,
var headers = {
'Cookie': '__cfduid=d99061ead63f349023a08a33868eb7ef81619925287'
};
var request = http.Request(
'GET',
Uri.parse(
'https://fakemyapi.com/api/fake?id=220e0e14-8c78-45e9-9ef0-6ca516fde5be'));
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
var item =
JsonDecoder().convert("${await response.stream.bytesToString()}");
print("item $item");
print("first_ame ${item['first_ame']}");
return item;
} else {
print(response.reasonPhrase);
}

Flutter : Multipart File request not working

I want to upload image by multipart File request. With using this code When I pass two image files then it's working fine. But when I want to pass one image file and another is null then it's not working.
where is the problem? How can I solve this ?
Here is my code -
Future<Map<String, dynamic>> updateprofile(
UpdateProfileInfo updateProfileInfo,
File imageFile,
File signatureFile) async {
String url = "$baseAPIUrl/update-profile-info";
String _token = await SavedData().loadToken();
String authorization = "Bearer $_token";
final headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
"Authorization": authorization
};
var request = http.MultipartRequest("POST", Uri.parse(url));
request.headers.addAll(headers);
request.fields.addAll(updateProfileInfo.toJson());
request.files
.add(await http.MultipartFile.fromPath('image', imageFile.path));
request.files.add(
await http.MultipartFile.fromPath('signature', signatureFile.path));
print(" Update Profile Json ${updateProfileInfo.toJson()}");
print("Request Fields ${request.fields}");
http.StreamedResponse response = await request.send();
String respStr = await response.stream.bytesToString();
dynamic respJson;
try {
respJson = jsonDecode(respStr);
} on FormatException catch (e) {
print(e.toString());
}
print('API ${response.statusCode}\n $respJson');
bool isSuccess = response.statusCode == 200;
var data = json.decode(respStr);
return {
'isSuccess': isSuccess,
"message": isSuccess ? data["success"]["message"] : null,
"name": isSuccess ? data["success"]["name"] : null,
"classgroup": isSuccess ? data["success"]["classgroup"] : null,
"image": isSuccess ? data["success"]["image"] : null,
"error": isSuccess ? null : data['error']['message'],
};
}
Here is postman Screenshot
1.
2. POSTMAN Generated code for Dart - http
when one of your file is null, you should avoid adding it to the request body.
if(imageFile != null){
request.files
.add(await http.MultipartFile.fromPath('image', imageFile.path));
}
if(signatureFile != null){
request.files.add(
await http.MultipartFile.fromPath('signature', signatureFile.path));
}
its because signatureFile.path is going to cause an error here
using dio package should work
Future<bool> updateImage(var pickedFile) async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();` <br/>
var token = sharedPreferences.getString("token");
Dio dio = Dio();
final File file = File(pickedFile.path);
String fileName = file.path.split('/').last;
dio.options.headers["authorization"] = token;
FormData formData = FormData.fromMap({
"image": await MultipartFile.fromFile(file.path),
});
try {
var response = await dio.post(API.kBASE_URL, data: formData);
if (response.statusCode == 200) {
return true;
} else {
return false;
}
} catch (r) {
return false;
}
}

Is there a way to fix Cannot read property 'post' of undefined?

I'm running a page in vue with a form, it submits and returns data to and from an API, I'm getting a 'post' of undefined error in the console and I can't seem to figure out what's going on.
<script>
methods: {
StartClient: function () { // Initiate XMLHttpRequest as aHttpRequest for GET
this.get = function(Url, Callback){
var aHttpRequest = new XMLHttpRequest();
aHttpRequest.onreadystatechange = function() {
if (aHttpRequest.readyState == 4 && aHttpRequest.status == 200)
Callback(aHttpRequest.responseText);
}
// use aHttpRequest with response headers, to allow GET
aHttpRequest.open("GET", Url, true);
aHttpRequest.setRequestHeader("X-Api-Key", "eVnbxBPfn01kuoJIdfgi46TiYNv8AIip1r3WbjsX");
aHttpRequest.send(null);
}
this.post = function(Url, message, Callback) { // initiate XMLHttpRequest as aHttpRequest for POST
var aHttpRequest = new XMLHttpRequest();
aHttpRequest.onreadystatechange = function() {
if (aHttpRequest.readyState == 4 && aHttpRequest.status == 200)
Callback(aHttpRequest.responseText);
}
// use aHttpRequest with response headers, to allow POST
aHttpRequest.open("POST", Url, true);
aHttpRequest.setRequestHeader("X-Api-Key", "eVnbxBPfn01kuoJIdfgi46TiYNv8AIip1r3WbjsX");
aHttpRequest.send(message);
}
},
submitData: function () { // Start a traceroute, followed by the 'Begin' button
document.getElementById('inputBox').disabled = true;
var targetInputButton = document.getElementById("inputBox").value;
var message = '{"targetInputButton":"' + targetInputButton + '"}';
this.StartClient().post('https://le75bkfcmg.execute-api.eu-west-2.amazonaws.com/dev/start-trace', message, function(response) {
document.getElementById('jobId').innerHTML = response;
});
},
sendBackData: function () { // Receive traceroute data, followed by the 'Generate data' button
var jobId = document.getElementById("jobId").innerHTML;
var message = '{"jobId":"' + jobId + '"}';
this.StartClient().post('https://le75bkfcmg.execute-api.eu-west-2.amazonaws.com/dev/check-trace', message, function(response) {
document.getElementById('report').innerHTML = response;
});
}
}
}
</script>

Loading local JSON file with Safari Extension

Trying to load JSON file with Safari Extension.
var xhr = new XMLHttpRequest();
xhr.open("GET", safari.extension.baseURI +'js/data.json', true);
It gives an error "Cross origin requests are only supported for HTTP."
For example it is possible with Chrome Extenison
var xhr = new XMLHttpRequest();
xhr.open("GET", chrome.extension.getURL('/js/data.json'), true);
There you need to specify it in manifest
"web_accessible_resources": ["/js/data.json"]
Is there a similar way in Safari?
EDIT
Found a solution
It is possible through Global page
global.html
function handleMessage(event) {
if (event.name === "requestParagraphs") {
var xhr = new XMLHttpRequest();
xhr.open("GET", safari.extension.baseURI + 'js/data.json', true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
var articlesJSON = JSON.parse(xhr.responseText);
event.target.page.dispatchMessage('paragraphs', articlesJSON);
}
};
xhr.send();
}
}
safari.application.addEventListener("message", handleMessage, false);
injected.js
function handleMessage(msgEvent) {
var messageName = msgEvent.name;
var messageData = msgEvent.message;
if (messageName === "paragraphs") {
// ...
}
}
safari.self.addEventListener("message", handleMessage, false); // Listen response
safari.self.tab.dispatchMessage('requestParagraphs'); // Call global page

Chrome, recognize open tab

I'm creating an extenstion for google chrome that will perform checking if a stream on twitch.tv is online and will notify the user evey X minutes, I got that covered. What I'm looking for is a JScirpt code that will recognize if user is already on the streamers channel and will stop notifying him.
var username="$user";
setInterval(check,300000);
function check()
{
request("https://api.twitch.tv/kraken/streams/" + username, function() {
var json = JSON.parse(this.response);
if (json.stream == null)
{
chrome.browserAction.setIcon({ path: "offline.png" });
}
else
{
notify();
}
});
return 1;
}
function notify(){
var opt = {type: "basic",title: username + " is streaming!",message: "Click to join!",iconUrl: "start.png"};
chrome.notifications.create("", opt, function(notificationId)
{
setTimeout(function()
{
chrome.notifications.clear(notificationId, function(wasCleared) { console.log(wasCleared); });
}, 3000);
});
chrome.browserAction.setIcon({path:"online.png" });
}
chrome.browserAction.onClicked.addListener(function () {
chrome.tabs.create({ url: "http://www.twitch.tv/"+username });
});
function request(url, func, post)
{
var xhr = new XMLHttpRequest();
xhr.onload = func;
xhr.open(post == undefined ? 'GET' : 'POST', url, true);
xhr.send(post || '');
return 1;
}
check();
Use window.location.href to get the complete URL.
Use window.location.pathname to get URL leaving the host.
You can read more here.