So I am trying to shorten an URL with the new V4 Bitly API, but I am getting an JSON error.
My code:
$(function() {
$(".createBitly").on("click", function(e) {
e.preventDefault();
var url = $(this).attr("href");
var accessToken = "xxx";
var params = {
"long_url" : encodeURIComponent(url)
};
$.ajax({
url: "https://api-ssl.bitly.com/v4/bitlinks",
cache: false,
dataType: "json",
method: "POST",
contentType: "application/json",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + accessToken);
},
data: params
}).done(function(data) {
console.log(data);
}).fail(function(data) {
console.error(data);
});
});
});
Results: a 422 http error;
"{"message":"UNPROCESSABLE_ENTITY","resource":"bitlinks","description":"The JSON value provided is invalid."}"
But running it with CURL does work though: How to shorten URL using PHP Bitly v4?
What am I doing wrong? Is it not possible with jQuery only?
TIA.
I had made this edit from your code above and its working well.
1) JSON.stringify before sending request (convert your request to JSON format).
2) No need for encodeURIComponent().
$(function() {
$(".createBitly").on("click", function(e) {
e.preventDefault();
var url = $(this).attr("href");
var accessToken = "token";
var params = {
"long_url" : url
};
$.ajax({
url: "https://api-ssl.bitly.com/v4/shorten",
cache: false,
dataType: "json",
method: "POST",
contentType: "application/json",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + accessToken);
},
data: JSON.stringify(params)
}).done(function(data) {
console.log(data);
}).fail(function(data) {
console.log(data);
});
});
});
Related
function regCall(token){
$.ajax({
type: 'GET',
url: 'http://localhost:3000',
dataType: 'HTML',
headers: {
'x-auth': token
}
});
}
This is my ajax GET request I want to display the given url in html.
The below is the whole snippet with my login logic.
$(document).ready(()=>{
$('#login').submit((e)=>{
$.ajax({
type: 'POST',
url:'http://localhost:3000/login/users',
data: {
email: $('#email').val(),
password: $('#password').val()
},
success: function(data, status, req){
// alert(req.getResponseHeader('x-auth'));
localStorage.setItem('t',req.getResponseHeader('x-auth'));
var token = localStorage.getItem('t');
regCall(token);
// window.location.href = '/';
},
error: function (req, status, error) {
// alert(req.getResponseHeader('x-auth'));
localStorage.setItem('t',req.getResponseHeader('x-auth'));
alert('Invalid email and password');
window.location.href = '/login';
}
});
e.preventDefault();
});
})
This is the whole code of snippet.
extract response data from SUCCESS function:
function regCall(token){
$.ajax({
type: 'GET',
url: 'http://localhost:3000',
dataType: 'HTML',
headers: {
'x-auth': token
},
success: function(data){
//targetElement should be replaced by the ID of target element
$("#targetElement").html(data);
}
});
}
By using the success callback function you can display the response content on the HTML place
**First method:**
function regCall(token){
$.ajax({
type: 'GET',
url: 'http://localhost:3000',
dataType: 'HTML',
headers: {
'x-auth': token
},
success: function(responseData){
$("#div or class Id").html(responseData);
}
});
}
**Second method:**
function regCall(token){
$.ajax({
type: 'GET',
url: 'http://localhost:3000',
dataType: 'HTML',
headers: {
'x-auth': token
}
}).done(function(responseData){
$("#div or class Id").html(responseData);
});
}
**NOTE:**
Make sure you are having the jQuery script
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I have read a lot of posts, old, new and the wikipedia documentation.
I have this request that works itself and in the sanbox:
https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=einstein&format=json
https://www.mediawiki.org/wiki/Special:ApiSandbox#action=query&format=json&list=search&srsearch=einstein
but when I try to use it in a javascript script, I can not get the data:
I tried both ajax and Json:
here is the code I used:
a 'GET' request with ajax :
code markup sucks
function build_wiki_search_url(pattern) {
var base_url = "https://en.wikipedia.org/w/api.php";
var request_url = "?action=query&format=json&list=search&srsearch=";
var url = base_url + request_url + pattern;
return url;
}
$(document).ready(function() {
$("#doit").click(function() {
console.log("Submit button clicked");
var pattern = $("#search").val();
var url = build_wiki_search_url(pattern);
console.log(url);
$.ajax( {
type: "GET",
url: url,
dataType: 'jsonp',
success: function(data) {
console.log(data);
},
error: function(errorMessage) {
console.log("damnn");
}
});
console.log("end");
});
})
a 'POST' request with ajax following the wikipedia documentation
var base_url = "https://en.wikipedia.org/w/api.php";
$.ajax( {
contentType: "application/json; charset=utf-8",
url: base_url,
data: {
action: 'query',
list: 'search',
format: 'json',
srsearch: 'einstein',
origin: '*',
},
dataType: 'json',
type: 'POST',
success: function(data) {
console.log("ok");
// do something with data
},
error: function(errorMessage) {
console.log("damnn");
}
} );
and a getJSON try:
//getJSON atempt.
console.log(url + '&callback=?');
$.getJSON(url + '&callback=?', function(json) {
console.log("ok");
});
Here is the output in my console:
Submit button clicked
https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&srsearch=einstein
script.js
end
The problem comes in fact from the html:
<form >
<input type="text" id="search"> <button id="doit"> Search!!</button>
</form>
Since the button is in a form, this button normal behavior is to generate a submit action. So the idea is to disable this normal behavior with:
$("#doit").click(function(e) {
e.preventDefault();
The full working code :
function build_wiki_search_url(pattern) {
var base_url = "https://en.wikipedia.org/w/api.php";
var format = "&format=json";
var request_url = "?action=query&format=json&list=search&srsearch=";
var url = base_url + request_url + pattern;
return url;
}
$(document).ready(function() {
$("#doit").click(function(e) {
e.preventDefault();
console.log("Submit button clicked");
var pattern = $("#search").val();
var url = build_wiki_search_url(pattern);
$.ajax( {
type: "GET",
url: url,
dataType: 'jsonp',
success: function(data) {
console.log(data.query.searchinfo.totalhits);
},
error: function(errorMessage) {
console.log("damnn");
}
});
});
})
I'm able to post a message but when I add either the attachment or pending_attachment, I get an error saying:
TypeError: 'stepUp' called on an object that does not implement interface HTMLInputElement.
function post() {
yam.getLoginStatus( function(response) {
if (response.authResponse) {
yam.request(
{ url: "https://api.yammer.com/api/v1/messages.json" //note: the endpoint is api.yammer...
, method: "POST"
, data: {
"body" : document.getElementById("post_body").value,
"group_id" : document.getElementById("group_id").value
,"attachment1" : document.getElementById("attachment")
}
, success: function (msg) {
alert("Post was Successful!: " + msg.messages[0].id); //id of new message
}
, error: function (msg) { alert("Post was Unsuccessful..." + msg); }
}
);
} else {
yam.login( function (response) {
//nothing
});
}
});
}
yammer's javascript SDK doesn't work with attachment. (at least no working example has been seen on the internet) To upload an attachment, you can either upload the file to your server and then use og_url to post a link to that file on your server, or cook up your own ajax form upload. here is an example:
var data = new FormData();
data.append('body', document.getElementById("post_body").value);
data.append('group_id', document.getElementById("group_id").value);
data.append('attachment1', document.getElementById("attachment"), 'filename_of_your_choice');
$.ajax({
url: "https://api.yammer.com/api/v1/messages.json",
data: data,
beforeSend: function (xhr) {
// set authorization header
xhr.setRequestHeader("Authorization", "Bearer YOUR_AUTHORIZATION_TOKEN");
},
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function (data) {
console.log("ajax post success.");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("There was an error with the request.");
}
});
Notice that the authorization token is obtained in the response to a successful login. It is not your app ID. Also, I doubt document.getElementById("attachment") will work. You need to convert that object into an byte array blob.
It works for me:
function postAttach() {
var msg = $('#attach_body').val();
var m_data = new FormData();
m_data.append('body', msg);
m_data.append('group_id', 6194208);
m_data.append('attachment1', $('input[name=attachment1]')[0].files[0]);
yam.platform.request({
url: "messages.json",
contentType: "multipart/form-data",
data: m_data,
processData: false,
contentType: false,
type: 'POST',
dataType: 'json',
success: function (user) {
alert("The request was successful.");
},
error: function (user) {console.log(user);
alert("There was an error with the request.");
}
});
}
<div name="postYammer">
<input type="text" name="body" value="" id="attach_body" />
<input type="file" name="attachment1" id="attach_img"/>
<button onclick="postAttach()" type="button">Post</button>
</div>
//Example Nodejs in async function
// nota : you can get token from https://developer.yammer.com/docs/app-registration
const qs = require("qs");
const got = require("got");
const formData = require("form-data");
const fs = require("fs");
var json = {
is_rich_text: true,
topic1: 'tag1',
topic2: 'tag2',
body: 'body body',
group_id: 'group_id',
}
let querystring = qs.stringify(json);
var formData = new formData();
var aHeader = formData.getHeaders();
aHeader['Authorization'] = "Bearer token";
formData.append('attachment1', fs.createReadStream(path));
const response = await got.post('https://www.yammer.com/api/v1/messages.json?' + qs, {
headers: aHeader,
body: formData
});
I'm trying to post JSON data along with 2 ids through a Jquery AJAX post. But I am not able to do it.
Following is my code:
try {
var surveyID= localStorage.getItem("surveyId");
var userDetails = jQuery.parseJSON(localStorage.getItem("userdetails"));
var providerKey = userDetails["ProviderUserKey"];
var dataValue = { "str": StringJson};
var url = APP_URL+"EditSurvey?";
var param = "SurveyId="+surveyID+"&JSONData="+JSON.stringify(dataValue)+"&UserId="+providerKey;
$.ajax({
type: "POST",
contentType: "application/json",
url: url,
data: param,
async:true,
success: function (data) {
alert('sucess');
//}
},
error: function (err) {
alert("Err : " + err.error);
},
});
} catch (error) {
alert(error);
}
I get the following error when I debug this in Safari:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
and in simulator I get the following error:
Where am I getting wrong? How do I solve this? I have to 3 parameters for post
surveyID
JSON data
userID
Edited:
The webservice is now changed and all 3 params- i.e. 2 ids and one whole json data is passed to the webservice. Still jquery ajax post is not working. See my code below:
var surveyID= localStorage.getItem("surveyId");
var userDetails = jQuery.parseJSON(localStorage.getItem("userdetails"));
var providerKey = userDetails["ProviderUserKey"];
var dataValue = {"surveyID":surveyID, "userID":providerKey, "str": StringJson};
alert(dataValue);
var url = APP_URL+"EditSurvey";
var param = dataValue;
$.ajax({
type: 'POST',
contentType: "application/json",
url: url,
data: dataValue,
success: function (data) {
alert('sucess');
//}
},
error: function (err) {
alert("Err : " + err.text);
},
});
edited to include stringJson:
var StringJson = JSON.stringify(MainJSON);
alert(StringJson);
Check if the final json which is being passed is in the exact format as expected by the server.
Try giving:
contentType: 'application/json',
Accept: 'application/json'
See if it helps.
try this one
formData = {
// all your parameters here
param1: param1,
JSONData: formToJSON(),
UserId: providerKey
}
$.ajax({
type: 'POST',
contentType: 'application/json',
url: url,
dataType: "json",
data: formData,
success: function(data) {
//success handling
},
error: function(data) {
alert("Err : " + err.error);
}
});
function formToJSON() {
return JSON.stringify({
dataValue: dataValue
});
}
I have written the following javascript to create a tasklist in google:
postData = {'title':'Netsuite List'};
access_token = 'xxxx';
url = 'https://www.googleapis.com/tasks/v1/users/#me/lists';
headers['Content-type'] = 'application/json';
headers['Authorization'] = 'Bearer ' + access_token;
headers['Content-length'] = 25;
response = $$.requestURL(url, postData, headers, 'POST');
The response says:
{ "error":
{ "errors": [ { "domain": "global", "reason": "parseError", "message": "This API does not support parsing form-encoded input." } ], "code": 400, "message": "This API does not support parsing form-encoded input." }
}
What could be the possible error ?
not working
contentType: 'application/json; charset=UTF-8',
try with this
var headers = { };
headers["Content-Type"] ="application/json ; charset=UTF-8";
//remove to parsing form-encoded input error
data:JSON.stringify( model),
//this use for remove to parse error
Example:
$.ajax({
type: 'Post',
url: postUrl,
headers: headers,
dataType: 'json',//not required in some case
data:JSON.stringify( model),
success: function (data, sts) {
alert('success');
},
error: function (err, sts) {
var msg;
}
});
You sent data like:
title=Netsuite%20List
But Google API waits for JSON:
{ "title": "Netsuite List" }
Try to provide JSON.stringify() output to the requestURL method:
postData = JSON.stringify({'title':'Netsuite List'}); // <-- Added JSON.stringify
access_token = 'xxxx';
url = 'https://www.googleapis.com/tasks/v1/users/#me/lists';
headers['Content-type'] = 'application/json';
headers['Authorization'] = 'Bearer ' + access_token;
headers['Content-length'] = 25;
response = $$.requestURL(url, postData, headers, 'POST');
Also, it's better to get around documentation or source of $$ object you use and check how it can support sending JSON data.
jQuery.ajax({
url: "https://www.googleapis.com/tasks/v1/users/#me/lists",
method: "POST",
data: JSON.stringify({ /* your object */ }),
dataType: "json",
beforeSend: (xhr) => {
xhr.setRequestHeader("Content-Type", "application/json");
},
//...
or :
jQuery.ajax({
url: "https://www.googleapis.com/tasks/v1/users/#me/lists",
method: "POST",
data: JSON.stringify({ /* your object */ }),
dataType: "json",
contentType: "application/json",
//...