I've mostly worked with jQuery before and I'm new to YUI. I wish to set a custom header for each Ajax request using either IO or DataSource in YUI 3. I want the header to be inserted automatically for each request. In jQuery I could accomplish this with $.ajaxPrefilter like so:
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
var value = 'blah';
if (value) {
jqXHR.setRequestHeader("My-Custom-Header", value);
}
});
I found these pages in the online documentation for YUI 3 but I just don't "get it". How can I accomplish this?
http://developer.yahoo.com/yui/3/examples/io/io-get.html
http://developer.yahoo.com/yui/3/api/io.html
Check out the "header" method in the io module: API docs
I haven't tested it, but you should be able to do something like this:
YUI().use('io', function(Y) {
Y.io.header('X-My-Header', 'My Custom Value');
Y.io(/*...*/); // Should have the X-My-Header HTTP header
});
Note that this will only apply to the current YUI instance. So if you have another YUI().use(/.../) statement, you'll need to set the header again.
If you need it to provide headers across instances, you should define your own module that wraps the Y.io functionality. Check out this gist to get a sense of what that entails.
I honestly don't think it is good idea to do it "JQuery style". Either way you need to provide configuration object, so few more characters doesn't make much difference.
But the worst part is that when someone else will see your code he will not have idea where the additional headers come from and he will probably waste hours of his life.
If you still want to have default headers somewhere, do it Javascript way like so:
Y.myDefaultIOCfg={"My-Custom-Header":value}
...
var cfg=Y.merge(Y.myDefaultIOCfg, {
method: 'GET',
data: 'foo=bar'
})
request = Y.io(uri, cfg)
This way you explicitly say that you are using some object as a pattern for the config object and additional header definition can be found there.
I don't know YUI syntax very well, but try this:
YUI().use("io-base", function(Y) {
var cfg, request;
cfg = {
methos: 'GET',
data: 'foo=bar',
headers: {
'My-Custom-Header': value
}
}
request = Y.io(uri, cfg);
});
Related
I'm kind of new to using ajax but I've been largely successful. Most of my ajax calls look very similar to this:
function saveQueryProf(){
var currentDate = new Date();
var date=currentDate.getDate()+'/'+(currentDate.getMonth()+1)+'/'+currentDate.getFullYear();
$.ajax({
type: "POST",
url: "API.php",
data: { method: "createQueryProfile",
prof_name: $('#nameTxt').val(),
prof_SQL: $('#sqlTxt').val(),
date: date
},
datatype: "json"
}).done(function(returnresult) {
})
}
Using the $.ajax({ method. However, any time I see someone using "ajax" on youtube or other sites, their code looks more like this:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
I realize that these are doing different things, but what is the difference in these 2? And when I'm looking for answers online how could I find an answer that is more along the lines of the first style?
The first example, using $.ajax(), is specific to jQuery. It's a lot simpler than the built-in Javascript API, XMLHttpRequest. XMLHttpRequest doesn't require any external libraries to use, though it's more difficult. $.ajax() relies on XMLHttpRequest.
Your code requires the jQuery library to work (that's where $ and $.ajax come from). Their code is using XMLHttpRequest directly, which is built in to JavaScript, so it doesn't need any libraries. If you want your AJAX code to depend on jQuery, then just include it as a search term.
I saw that the question was already answered, but I think that more information can be added.
In your first example you are using jQuery ($.ajax call). You will need to add this library to your website in order to make it work. The easiest way is to add a tag with jQuery CND to your website.
The second example is using vanilla JavaScript, the XMLHttpRequest. It has more complex syntax (a strange mixture of upper and lowercase characters), but you don't need to add anything to the site. It will do the work, and once you are used to the syntax it might be all you need.
Third option that I have used for AJAX request is the fetch() method. Like XMLHttpRequest it is build in in the JavaScript language. fetch() has very simple syntax and allows easy use of promises. You might need promises if you will be making requests that will not return data immediately. Here's more information on fetch:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Fourth option that I've used for AJAX is Axios library. If you are including jQuery only for AJAX requests Axios is probably better choice. More read on Axios: https://github.com/axios/axios
If you want to dig a bit more on the differences and pros/cons between fetch() and XMLHttpRequest take a look on this thread:
Fetch API vs XMLHttpRequest
Shortly Ajax is an extension method which defined in JQuery for factory class XmlHttpRequest.
I am working with the Polymer 2 library. Whenever I try to make multiple requests using iron-request, the code only ever seems to make a POST request on the first initiation. Any subsequent requests seem to be ignored, even when data that is set to be sent to the server is different from the initial request.
I've written a small example in this Plunker: https://plnkr.co/edit/cozVKUdQ2q2SV46rcCTL?p=preview
I created a iron-request and a button element to initiate the request like so:
<paper-button on-click="save" class="green">Send</paper-button>
...
<iron-request id="xhr"></iron-request>
The save function is setup to take text from a textarea and send that off to a server.
save() {
var response = this.$.xhr.send({
url: "https://httpbin.org/post",
headers: {
'content-type': 'application/x-www-form-urlencoded'
},
body: {
content: this.inputdata
},
method: "POST"
});
var poly = this;
this.$.xhr.completes.then(function(data) {
console.log("finished");
poly.$.responsetext.innerHTML = data.response;
})
The code in question is in the "element1.html" file. If you try sending different text payloads, only the first request will be send. (You can see in the response box that the form "content" field stays the same.)
Any idea what is going on? I'm thinking that I would have to create new iron-request elements everytime I need to make a new request... but that doesn't sound like a very elegant solution.
As you suspected, iron-request has been built to send a single HTTP request. I had a quick look at the its implementation. The send method will actually just return null and not do anything, if the request has a status that is larger 0 than, which will be the case if you have used it before.
While you could create a new iron-request element for each request, it is not elegant (as you said yourself). Instead, you could work with iron-ajax. You can find some instructions on its documentation page.
Your <iron-request> can be rewritten as this.
<iron-ajax id="xhr" url="https://httpbin.org/post" content-type="application/x-www-form-urlencoded" method="POST" body="[[inputdata]]" on-response="onXhrSuccess"></iron-ajax>
Your save function,
save() {
this.$.xhr.generateRequest();
}
onXhrSuccess(event, request) {
console.log("finished");
poly.$.responsetext.innerHTML = event.detail.response;
}
I have the following segment js code, but I can't understand $.tzPOST.
$.tzPOST('login',$(this).serialize(),function(r){
working = false;
if(r.error){
chat.displayError(r.error);
}
else chat.login(r.name,r.gravatar);
});
What does $.tzPOST mean?
Thanks you so much !
I think you're referring to this tutorial about a live webchat.
Rboe guessed right that tzPOST is a custom function that was added to $ (jQuery) object. The tutorial provides the source for both tzPOST and tzGET functions on the same page (use CTRL+F there to find it quickly), here they are:
// Custom GET & POST wrappers:
$.tzPOST = function(action,data,callback){
$.post('php/ajax.php?action='+action,data,callback,'json');
}
$.tzGET = function(action,data,callback){
$.get('php/ajax.php?action='+action,data,callback,'json');
}
It just makes POST and GET requests code shorter and therefore easier to read and maintain. For example, if you change the name or location of your ajax.php file you'd just need to change the path in these 2 functions instead of changing it in every AJAX request. With the standard way your function would look like this:
$.post('php/ajax.php?action=login', $(this).serialize(), function(r) {
working = false;
if(r.error){
chat.displayError(r.error);
}else {
chat.login(r.name,r.gravatar);
}
}, 'json');
So the difference is small.
I wanted to pass multipart/formdata through a $resource in angular in order to post an image.
I followed the magic answer founded here AngularJS: Upload files using $resource (solution)
But this solution apply for all requests in my modules. And I want it to apply only for one $resource or two. If possible I want to keep JSON for the others requests. In fact I'm using nested properties and I would like to keep it.
Is here any way to do it ?
Thanks
As per $request documentation, the transformRequest() can be applied per method; you will have to redefine the method though. Some sample code would be:
var MyResource = $resource("url", {
myPost: {
method: "POST",
transformRequest: function(data) {
// code from http://stackoverflow.com/questions/21115771/angularjs-upload-files-using-resource-solution
}
}
);
This is the barebone setup, you will probably need some adjustments. It would be used as (again the simplest case):
MyResource.myPost(formData); // formData contains properties and the image(s)
Why does this not work? anybody:
In my code I have:
$.getJSON("http://isp123.co.uk/cw/NorthWales/Test.txt?jsoncallback=?",
function(data){
//This never gets executed
alert('here');
});
The text file can be viewed here:
http://isp123.co.uk/cw/NorthWales/Test.txt
This is not a JSONP response:
({"name" : "hello world"});
If you had a proper JSONP response, then your code should work.
The question mark in the "callback=?" part of the URL is changed by jQuery before making the request, your JSONP server needs to be able to dynamically create the JSONP "function" in response to the unique jQuery request. If you can't dynamically create your JSONP, perhaps you could use YQL/Yahoo pipes to turn it into JSONP?
This pipe should do the trick, to see if it works, use this URL instead in your getJSON function: http://pipes.yahoo.com/pipes/pipe.run?u=http%3A%2F%2Fisp123.co.uk%2Fcw%2FNorthWales%2FTest.txt&_id=332d9216d8910ba39e6c2577fd321a6a&_render=json&_callback=?
I just tried this and it worked:
$.getJSON("http://pipes.yahoo.com/pipes/pipe.run?u=http%3A%2F%2Fisp123.co.uk%2Fcw%2FNorthWales%2FTest.txt&_id=332d9216d8910ba39e6c2577fd321a6a&_render=json&_callback=?", function(data){
//This always gets executed!!!
alert('here');
});
I don't know if you know enough about JSONP but this is not JSONP
?({"name" : "hello world"});
It really should be something like this http://isp123.co.uk/cw/NorthWales/Test.txt?jsoncallback=foo
foo({"name" : "hello world"});
From the jQuery.getJson manual page:
Important: As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently. Avoid frequent hand-editing of JSON data for this reason. JSON is a data-interchange format with syntax rules that are stricter than those of JavaScript's object literal notation. For example, all strings represented in JSON, whether they are properties or values, must be enclosed in double-quotes. For details on the JSON format, see http://json.org/.
Your JSON is invalid according to http://jsonlint.com/
Here Clearly mentioned
As of jQuery 1.5, setting the jsonp
option to false prevents jQuery from
adding the "?callback" string to the
URL or attempting to use "=?" for
transformation. In this case, you
should also explicitly set the
jsonpCallback setting
and read jsonpCallback section
jsonpCallback,
Specify the callback function name for
a JSONP request. This value will be
used instead of the random name
automatically generated by jQuery. It
is preferable to let jQuery generate a
unique name as it'll make it easier to
manage the requests and provide
callbacks and error handling. You may
want to specify the callback when you
want to enable better browser caching
of GET requests. As of jQuery 1.5, you
can also use a function for this
setting, in which case the value of
jsonpCallback is set to the return
value of that function
Probably worth using jQuery.ajax() - http://api.jquery.com/jQuery.ajax/
You can pass in the dataType as "jsonp" and then jQuery takes care of all the callback business, but more importantly you can specify a function to run when there's an error, which may help you:
$.ajax({
dataType: "jsonp",
success: function(d) {console.log(d);},
error: function() { console.log("error") } //do your debugging in here
//add other parameters such as URL, etc
});
The error function you define can be passed 3 variables, read up on it on the ajax() page on the jQuery docs (linked at the beginning of my post) to find out more about that and how to use them.
Your problem lies with how your server is outputting the information. In the link you've supplied, the assumption is that any name placed in the ?jsonpcallback should result in wrapping the JSONP code in a function with that same name. It, however, is not the case.
So the next option is this: use a static function name in your server file and wrap the code. (e.g. use foo(<jsonp>) and stick with it) Then, you have to explicitly tell jQuery that we are going to use a specific function name (leave jQuery with the assumption it's supplying (and thus receiving) that name back, when in-fact you're just supplying it server side and filling in the blanks).
Once you have your file setup, use something like the following:
$.ajax({
// setup the request
url: 'http://isp123.co.uk/cw/NorthWales/Test.txt',
crossDomain: true,
dataType: 'jsonp',
jsonp: false,
jsonpCallback: 'foo', // "supply" the jsonp function (pseudo-defined)
// function to call when completed
complete: function(data){
alert(data);
}
// just in case, catch the error
error: function(j,t,e){
alert('AJAX Error');
}
});
So now when jQuery makes the call and it thinks it's supplying the callback, it's really just getting the server-defined callback in return. So, for the above to work, your text file should look something like this:
foo({name:"Hello, World!"});
Also, if you can, change your header to application/javascript, though this is some-what optional.