fdaciuk / ajax Goto Github PK
View Code? Open in Web Editor NEWAjax module in Vanilla JS
Home Page: https://www.npmjs.com/package/@fdaciuk/ajax
License: Other
Ajax module in Vanilla JS
Home Page: https://www.npmjs.com/package/@fdaciuk/ajax
License: Other
What do you think about support withCredentials ?
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials
link this
$.ajax({
url:url,
dataType:'jsonp',
jsonp:'callback',
success:function(res) {
},
timeout:3000
});
The js ends with:
return ajax
})
That cases and error if I merge it with other javascripts.
Change it to:
return ajax
});
Hey. I caught this error
Unhandled rejection ReferenceError: XMLHttpRequest is not defined
in my controller i'm add your module like that:
ajax = require('@fdaciuk/ajax')
then
const aQuery = ajax({ baseUrl: 'https://some-site/api/'})
and then request
aQuery.post('/user/nop', { headers: { 'content-type': null }, data: { password: res.dataValues.password, username: res.dataValues.username } });
After I got the error I added:
XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest, xhr = new XMLHttpRequest()
and it did not help. Are there any ideas about this?
It would be interesting to have this library available over Bower.
More info about creating a package can be found here: http://bower.io/docs/creating-packages/
First things first: BADASS plugin! Saving me big time! π
A common thing when consuming REST APIs via CORS is always using the same base URL for all AJAX calls. E.g.
ajax().get('https://my-url.here/service/etc')
ajax().get('https://my-url.here/service/abc')
ajax().get('https://my-url.here/service/something')
ajax().get('https://my-url.here/service/another-something')
This gets overwhelming to type for each single new AJAX call. Maybe it would be interesting to enable user to set a base URL from where requests would start from? E.g.
ajax().registerBaseUrl('https://my-url.here/service')
ajax().get('/etc')
ajax().get('/abc')
ajax().get('/something')
ajax().get('/another-something')
then if user really needs to use another URL they could just start the request with http|https
(or another major protocol). E.g.
ajax().registerBaseUrl('https://my-url.here/service')
ajax().get('/etc') // https://my-url.here/service/etc
ajax().get('https://another-service.here/data') // https://another-service.here/data
Do you think its a good idea?
return item + '=' + encodeURIComponent ( object[ item ] );
this lib can't transport request that method is post and content-type: x-www-form-urlencoded. when pass content-type: x-www-form-urlencoded, it just stringfiy
Because I found some information about fetch and improved browser support. Should XMLHttpRequest replaced by fetch with a fallback for unsupported browsers like IE or some mobile browsers?
Found #26 with the set header example
var request = ajax({
headers: { 'content-type': null }
})
request.post(url, FormObj)
.then(function (data) {
// success
console.log(data)
})
.catch(function (err) {
// error
console.log(err)
})
Tried to add the header and send the call with one single ajax() method call.
$.ajax({
method: 'get',
url: 'https://www.google.de'
})
$.ajax({
method: 'get',
headers: {
'Access-Control-Allow-Origin': '*'
},
url: 'https://www.google.de'
})
And geht errors:
without header
XMLHttpRequest cannot load https://www.google.de/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
and with header
XMLHttpRequest cannot load https://www.google.de/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 405.
So maybe I tried it the wrong way? Could you help me with a hint about the problem?
Hi @fdaciuk, i`m try to send a object to endpoint, but the network in browser show [object object].
my code:
let url = 'http://localhost:3000/api'
let request = (param, data) = ajax({
method: "put",
url: url + param,
data: data,
});
request(`/users/1`, { driverDocument: { status: 2 } }).then()
Network
My data is in HTML format.
I tried this:
var test = ajax({
method: 'get',
url: '/ajax',
baseUrl: '<?php echo u(); ?>'
});
console.log(test);
I got an object back with abort, always, catch, then. How can I get the plain html from that object?
Hey guys,
I noticed that the browser support logos are not showing properly on README.
It looks like alrra/browser-logos switched the location of the image files to another directory, they are located inside a src
folder now.
Also, since the repo was using PNG logos we could take the opportunity to switch to SVG ones (they look better on HiDPI displays).
I could put up a PR for this if wanted.
Thanks!
Hey Fernando,
want to add BeforeSend and Complete in lib ?
It would be nice to use loading gif ;)
when I use get with params,but the param is invalid.
How to change this code to "fdaciuk/ajax" ? Help!!
$.ajax({ url: url, contentType: false, data: FormObj, processData: false, type: 'POST', cache: false, success: function(){ .... }, error: function(){ ..... } });
Converting ajax "promises" into real Promises with Promise.resolve
doesn't work. Successful case is fine. However, if there's an error (or abort), catch
in the wrapping Promise doesn't get called.
Changing the .then(onFulfilled)
method to be .then(onFulfilled, onRejected)
, would make this a proper thenable and allow any promise library to wrap it.
const req = ajax({/* ... */});
const realPromise = Promise.resolve(req);
realPromise
.then(() => console.log('worked')
.catch(() => console.log('failed'))
// 'failed' will never show if an error happens
Utilizo o ajaxForm, do jQuery em alguns projetos, posso trocar por essa lib, @fdaciuk?
Um exemplo do ajaxForm em um projeto.
$('#contact').__proto__.ajaxForm({
success: function(data) {
location.assign(data.url);
if (data.status) {
$('#contact')[0].reset();
}
},
error: function() {
alert("Mensagem nΓ£o pode ser enviada, entre em contato diretamente por e-mail");
}
});
When this is installed with NPM the dist directory seems to be ignored:
node_modules/@fdaciuk$ tree -a
.
βββ ajax
βββ .npmignore
βββ LICENSE.md
βββ README.md
βββ package.json
NPM seems to only have v0.0.6 registered. That might be the problem?
I've tried like this
var request = ajax({
method: 'options',
url: '/api/users',
data: JSON.stringify({
user: 'john'
})
});
request.then(function (response) {...});
but I got error request.then is not a function?
what's wrong?
Any plans on following Promises/A+ spec?
Because it's used by RESTful APIs I think.
http://www.restapitutorial.com/lessons/httpmethods.html
I have two modules that call .then on the promise returned from an ajax().post
call.
// module 1
proto.method = function () {
return ajax().post(...).then(function (response) {
// This will not fire if there's a `then` call in module2.method
});
};
// module 2
proto.method = function () {
module1.method().then(function (response) {
// This will fire because it was the last .then to be invoked
});
};
Only the last callback "registered" with a then
call will be invoked. As this is promise-based, I expect to be able to chain then/catch/always calls.
xhr.send(data) will ignore data while the method is GET,so i decide to serialize data and put it in the end of url
just like this:
//other my code
if (opt.type === 'GET' && opt.data2send !== null) {
if (url.indexOf('?') === -1) {
url += '?';
} else {
url += '&';
}
url += serilizeData(opt.data2send);
}
//other my code
function serializeData(data) {
if ('object' === typeof data) {
return _.map(data, function (key, value) {
return [key, '=', ('object' === typeof value ? JSON.stringify(value) : String(value))].join('');
}).join('&');
} else {
return String(data);
}
}
so , if you can add get 'data' support in this project?
thank you very much.
Hello, is this ajax library using cache?
How to make ajax refresh the cache?
Hi fdaciuk,
Could you confirm what are the browser version that fully supports your package?
Cheers
E
Hi,
When we set 'content-type': 'multipart/formdata'
and send formdata. The server will return error, due to no boundary in the 'content-type'.
I think we can when setting the 'content-type' to false, do not set content-type in header. like
if ($private.hasContentType(headers) === undefined) {
headers['Content-Type'] = 'application/x-www-form-urlencoded'
}
what do you think?
reference: http://stackoverflow.com/questions/5392344/sending-multipart-formdata-with-jquery-ajax
@luanmuniz's tip on #3
How can one import the ajax
method, or basically anything from your ajax.min.js
if the export
keyword isn't used anywhere in your code? I'm confused. it that even possible?
Any chance the non-minified source could be included in the NPM distribution? I'm including ajax from NPM via webpack. The non-minified source would allow webpack to generate usable sourcemaps for ajax.
See
.abort()
from $.ajax.
Is it possible?
Hi There,
Nice project! Have been using it in a couple of projects, works good. The docs state the following;
Passing data as object, application/json will be automatically used (since v2.3.1).
Shouldn't that be a minor (or even major) SemVer? E.g. 2.4.0
? Had my dependencies set to ^2.3.0
and after a update my whole project stopped working.
Minor issue, easy fix, but took some time to figure out what had changed (until i read your docs again).
Thanks!
A declarative, efficient, and flexible JavaScript library for building user interfaces.
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. πππ
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google β€οΈ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.