Mostly, rest api url' s like:
/api/student:id/notes
I create a rest api and my urls like above. But I dont know how to add parameter before notes.
$.ajax({
url : "api/v1/student/notes",
data : { "id" : uid },
type : "get",
headers : { "Authorization" : api_key },
dataType : "json",
success : function(response) {
console.log(response);
}
});
When I call like this, the url seems /api/student/notes?id=5. How can Iadd id parameter between student and notes?
Example url: http://www.sitepoint.com/best-practices-rest-api-scratch-introduction/
AFAIK, jQuery does not offer a neat API for injecting resource URI fragments like Angular's $resource. You'll have to build the URL yourself. Something like
$.ajax({
url: 'api/v1/students/' + encodeURIComponent(uid) + '/notes',
// and so on, no "data" required.
Related
Trying to override the Apify's Google Scraper actor's queries by passing the data object as given below. I am getting 400 and and 403 error message. When I remove the data playload, it works fine. It then returns the result with the default queries.
1) What is the right way to pass the playload to override the queries parameters.
2) How can I send multiple search queries like "link building", "link building service" ?
$.ajax({
url : 'https://api.apify.com/v2/actor-tasks/XXXXXXX/runs?token=XXXXXXXX&waitForFinish=120,
method : 'POST',
contentType: 'application/json',
data : { // when I add this I get 400 error.
"queries" : "Outreach link building",
},
success:function(result) {
console.log(result);
}
});
Thanks in advance.
1) You need to stringified JSON and use proper dataType:
$.ajax({
url : 'https://api.apify.com/v2/actor-tasks/XXXXXXX/runs?token=XXXXXXXX&waitForFinish=120',
method : 'POST',
contentType: 'application/json',
dataType: 'json',
data : JSON.stringify ({
"queries" : "Outreach link building"
}),
success:function(result) {
console.log(result);
}
});
You can read about that in this post.
2) If you want to send multiple queries you need to separate them using the new line:
{
"queries": "Outreach link building\nquery"
}
Currently, I'm sending the data via code in this way and it's working but how can I send the entire form in json?
Code :
$.ajax({
url : window.location.href, // the endpoint,commonly same url
type : "POST", // http method
data : { csrfmiddlewaretoken : csrftoken,
email : email,
password : password,
username : username,
dob : dob,
}, // data sent with the post request
I want to send and retrieve everything including csrfmiddlewaretoken using formdata json.
I have tried something similar to that :
var formData = new FormData($('#my_form');
formData.append('csrfmiddlewaretoken', '{{ csrf_token }}');
$.ajax({
url : window.location.href, // the endpoint,commonly same url
type : "POST", // http method
data : formData, // data sent with the post request
But, this does not work for some reason. How can I get it to work?
you need to send json serialized form data as one paramater and csrf token as another parameter because every POST request expects a csrf token in it.
csrfmiddlewaretoken = $("#add_member_Form").find("input[name='csrfmiddlewaretoken']" ).val();
formData = $('#add_member_Form').serializeArray();
formData = JSON.stringify(formData);
$.ajax({
url : url,
data : {
"csrfmiddlewaretoken" : csrfmiddlewaretoken,
"formData" : formData
},
method: "POST",
dataType : "json",
At server side in your view, you need to deserialize the data.
form_data_dict = {}
form_data_list = json.loads(form_data)
for field in form_data_list:
form_data_dict[field["name"]] = field["value"]
return form_data_dict
You could grab the form data usingserializeArray function in jQuery, then convert it into dictionary and send as post data.
The serializeArray function output would be something like,
{
'name': 'the_name',
'value': 'the_value'
}
Then, you would have to convert it to the dictionary or json format. Write a global function for that,
function objectifyForm(formArray) {
var returnArray = {};
for (var i=0;i<formArray.length;i++) {
if (formArray[i].value) {
returnArray[formArray[i].name] = formArray[i].value;
}
}
return returnArray;
}
Call it whenever you have to grab the form data,
var formData = $('#my_form').serializeArray();
formData = objectifyForm(formData);
$.ajax({
url : window.location.href, // the endpoint,commonly same url
type : "POST", // http method
data : formData,
success: blaah,
error: bleeh,
});
It would be much less effort than having to decode the dictionary every time from the server side.
I'm unsure if I'm just thinking of this the wrong way of thinking or I'm just missing something.
I have a search box that does some wildcard searches in a database. I have made this an ajax request so I don't need to reload the page and I can have a little please wait icon while the data loads.
Now as there is pagination so I could do with the url parameters being added to the url, can you do this on a ajax request, ad if so how?
here is a sample code (param1) :
data : $('#form-contactSupplementaire').serialize() + "¶m1=value",
Request full ajax :
$.ajax({
method : "POST",
url : "...",
data : $("...").serialize() + "¶m1=value",
dataType: "",
success : function (json) {
// ...
console.log(json);
}, error: function () {
console.log("Error");
}
});
I am using jquery to post Json data to server. However when I make a post request as below,
$.ajax({
type : 'POST' ,
url : uri,
data : jsonStrJson,
contentType : 'application/json',
success : successFunction
});
The http request header content type is not "application/json" even though I posting a json object.
Since it is not applcation/json, the server does not process the requset and returns 415.
Is there a way to set the header using javascript or jquery API?
Can you try this,
$.ajax({
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
type: "POST",
url: uri,
data: jsonStrJson,
dataType: "json",
success: function(json){
console.log(json);
}
});
"contentType" instead "contentTYpe" should also solve the problem. ;)
Also for setting http request header parameters you can try this approach:
$.ajax({
type : 'POST' ,
url : uri,
data : jsonStrJson,
headers : { 'Content-Type': 'application/json' }, //this line
success : successFunction
});
Aim - to get the twitter followers of a particular user using javascript
I have tried the below code as a POC-
$(document).ready(function() {
// Handler for .ready() called.
$.ajax({
url: "https://api.twitter.com/1.1/followers/ids.json?callback=?",
type: "GET",
data: { cursor: "-1",
screen_name: "twitterapi" },
cache: false,
dataType: 'json',
success: function(data) { alert('hello!'); console.log(data);},
error: function(html) { alert(html); },
beforeSend: setHeader
});
function setHeader(xhr) {
if(xhr && xhr.overrideMimeType) {
xhr.overrideMimeType("application/j-son;charset=UTF-8");
}
//var nonce = freshNonce();
//var timestamp = freshTimestamp();
//var signature = sign(nonce,timestamp);
//alert(signature);
//alert(accessToken+"-"+consumerKey);
//alert(oauth_version+"-"+oauth_signature_method);
xhr.setRequestHeader('Authorization','OAuth');
xhr.setRequestHeader('oauth_consumer_key', 'HdFdA3C3pzTBzbHvPMPw');
xhr.setRequestHeader('oauth_nonce', '4148fa6e3dca3c3d22a8315dfb4ea5bb');
xhr.setRequestHeader('oauth_signature','uDZP2scUz6FUKwFie4FtCtJfdNE%3D');
xhr.setRequestHeader('oauth_signature_method', 'HMAC-SHA1');
xhr.setRequestHeader('oauth_timestamp', '1359955650');
xhr.setRequestHeader('oauth_token', '1127121421-aPHZHQ5BCUoqfHER2UYhQYUEm0zPEMr9xJYizXl');
xhr.setRequestHeader('oauth_version', '1.0');
}
});
I calculated the signature values from the Twitter OAuth tool ..
This gives me 400 Bad Request error ....
Please let me know what the problem is...
The problem is your request's header, it should be like this:
xhr.setRequestHeader('Authorization','OAuth oauth_consumer_key="HdFdA3C3pzTBzbHvPMPw", oauth_nonce="4148fa6e3dca3c3d22a8315dfb4ea5bb", oauth_signature="uDZP2scUz6FUKwFie4FtCtJfdNE%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp= "1359955650", oauth_token, "1127121421-aPHZHQ5BCUoqfHER2UYhQYUEm0zPEMr9xJYizXl", oauth_version="1.0"');
Btw, this javascript library might help you on OAuth's stuff: oauth-1.0a
It support both client side and node.js
Cheers
The oauth_* fields are all part of the Authorization header string, so they need to be concatenated as shown at the bottom of this page - https://dev.twitter.com/docs/auth/authorizing-request
They should not be presented as separate header fields.