JQuery $.post() and curl - javascript

This is what the GroupMe API (https://dev.groupme.com/docs/v3#messages_create) asks for:
$ curl -X POST -H "Content-Type: application/json" -d '{"source_guid": "frgfre", "text":"alala"}' https://api.groupme.com/v3/groups/ID/messages?token=YOUR_ACCESS_TOKEN
Please assume ID is a valid group id and the token is also valid and works. How exactly would I convert that to a $.post() request and run it from the console of a browser? Here is what I have that is not working in IE when Cross Domain is enabled and it is a trusted site:
var t = {"source_guid": "frgfre", "text":"alala"};
$.post("https://api.groupme.com/v3/groups/ID/messages?token=YOUR_ACCESS_TOKEN", t);
//I have also tried t.toString() as well but it didn't work
If that can't be converted (or what I have right now is correct), where would I run the first bit of code?

$.post posts the data in application/x-www-form-urlencoded format. If the API requires it to be JSON, you need to use $.ajax to override the default.
$.ajax({
url: "https://api.groupme.com/v3/groups/ID/messages?token=YOUR_ACCESS_TOKEN",
data: JSON.stringify(t),
contentType: 'application/json',
processData: false
});

Related

How to to convert my curl method to work in my javascript script?

Beginner in javascript,
I'm looking for ways to convert my curl method to work in my javascript script.
Here is my curl method:
curl -X GET "http://model.dbpedia-spotlight.org/en/annotate?text=beyonce" -H "accept: text/html"
My test with ajax (doesn't work):
$.ajax({
method: "GET",
url: "http://model.dbpedia-spotlight.org/en/annotate?text=beyonce"
})
The AJAX call is missing the accept header.
Once you add this in, it seems to work. Please see the example below:
$.ajax({
method: "GET",
url: "http://model.dbpedia-spotlight.org/en/annotate?text=beyonce",
data: { confidence: "0.60" },
headers: {"accept" : "text/html"}
}).done((res) => $("#res").append(res));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="res"></div>
I'd recommend using the fetch API over this jquery ajax method you're using. It's quite supported
fetch("http://model.dbpedia-spotlight.org/en/annotate?text=beyonce").then(response => response.text())
If you consider using it, I'd also recommend learning how to deal with Promises in case you don't know!

Image or file corrupted when success upload

Hi im trying to upload file or image in my dropbox using dropzone. and when it successfully upload in my dropbox it just corrupted it cant be preview.. I was wondering if there's a problem with my codes in getting a file
This is my processing method inside of my init: function()
this.on("processing", function(file) {
var url = 'https://content.dropboxapi.com/2/files/upload';
var file = dropzone.files[0];
var filename = file.name;
$.ajax({
url: url,
type: 'post',
processData: false,
contentType: 'application/octet-stream',
headers: {
"Authorization": "ACCESS TOKEN",
"Dropbox-API-Arg": '{"path": "/'+filename+'","mode": "add"}'
},
success: function (data){
alert('Success Upload');
/*this.options.url = url;*/
console.log(data);
}
})
});
Mmm may be you are not uploading the file with the proper headers. If you can please use curl first instead of using javascript so you can check faster if your file is being uploaded or not.
https://www.dropbox.com/developers/documentation/http/documentation#files-upload
I don't know if you have already checked the API documentation, first test it using curl and then form the packet using javascript.
curl -X POST https://content.dropboxapi.com/2/files/upload \
--header "Authorization: Bearer TOKEN
" \
--header "Dropbox-API-Arg: {\"path\": \"/Homework/math/Matrices.txt\",\"mode\": \"add\",\"autorename\":
true,\"mute\": false}" \
--header "Content-Type: application/octet-stream" \
--data-binary #local_file.txt
I hope this can help you...
Have you checked your internet connection? I ask because I had a similar problem, and even though my network was "fast", turns out my network is a burst type of network and the image was only uploading 2 of the 5 mb file size before the burst traffic timed out.
Crazy I know, but if you think that not might be the issue. Have you debugged this script yet? Are you getting your alert on screen and in your console debugger?

converting curl query in jquery ajax request

I have a curl command for getting json data and I want to send this request from javascript program. Please anybody can tell how to convert this curl command into jquery ajax request.
Command:
curl -H "Snapdeal-Affiliate-Id:<your affiliate ID>" -H "Snapdeal-Token-Id:<your affiliate Token>" "<URL for the chosen category>" -H "Accept:application/json"
cURL -H parameters add extra headers to the request.
jQuery.ajax have an option headers, this is a Plain JavaScript Object with the pair name/value for each header.
Then, your cURL request will translate in something like this:
$.ajax(url, {
url: "<URL for the chosen category>"
headers: {
"Snapdeal-Affiliate-Id":"<your affiliate ID>",
"Snapdeal-Token-Id":"<your affiliate Token>"
},
accepts: "application/json"
}).done(function (data) {
// code to handle succesful response
}).fail(function (data) {
// code to handle error response
});

what is wrong with my jQuery POST request?

I am trying to authenticate with a remote service through jQuery. First, I verify that I can do this outside of the browser:
curl -X POST -H "Content-Type: application/json" -H "Accept: appliction/json" -d '{"username":"...","password":"..."}' http://example.com/auth
This successfully returns a token.
Now I try it with jQuery:
$.ajax({
url: "http://example.com/auth",
type: "POST",
dataType: "json",
contentType: "json",
data: {username:"...",password:"..."},
error: function(data){alert(JSON.stringify(data))},
success: function(data){alert(JSON.stringify(data))}
});
I get a server error (500). Clearly I am doing something wrong. This is my first time trying to do a POST in jQuery, so I don't know how to identify what the problem is. What am I doing wrong here?
P.S. I can successfully do a GET request through jQuery, if I already have a token:
$.ajax({
url: "http://example.com/stuff?token=f42652adcbfe3ed9d59fae62b5267b8d",
type: "GET",
dataType: "json",
error: function(data){alert(JSON.stringify(data))},
success: function(data){alert(JSON.stringify(data))}
});
The only thing I notice is a difference in the data representations. Look at the data in the original request:
-d '{"username":"...","password":"..."}'
And the data in the AJAX request:
data: {username:"...",password:"..."}
The former wraps the keys in strings, whereas the latter doesn't. The whole thing should be a string too. Try:
data: '{"username":"...","password":"..."}'
This would be more consistent with JSON formatted data in general, I believe. Without wrapping the keys in strings, it may be a JavaScript object but it's not JSON data.
Update: oops missed a comment saying stringify didn't work. I'll leave this for posterity
Sometimes you need to stringify the data when sending Json, otherwise jquery may serialize the object as a param string rather than as a whole object. It depends on how your server binds the request query to the object. though. Can you debug the server request or is that out of your hands?
Try doing (provided you are on a semi modern browser) :
data: JSON.stringify({ your: data})
Thank you everybody for your help. Each little piece of advice helped lead me to the solution. I said it in a comment already, but here is the solution:
The dataType is correctly listed as "json", but the contentType should be listed as "application/json".
The content must be wrapped in JSON.stringify.
Do you post to the same domain as the js was loaded from? If not you need to use jsonp and make sure the server explicitly accepts your request, I believe.
500 Internal Server Error
The server encountered an unexpected condition which prevented it from fulfilling the request.
Json response from the url may be the reason, you can comment the stringfy function and alert the response. You can use try/catch method in response and check the error.
1) Open Network in Tools (f12)
2) Select "Network"
3) Select error row
4) Open "Body" on rights side
5) In title you can see error description eq.
<title>The parameters dictionary contains a null entry for parameter 'Id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Delete(Int32)' in 'BosCatalog.Controllers.ProductsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.<br>Parameter name: parameters</title>

How to Debug ajax REST calls (in general)

I have an cURL call that works and I have converted it to an ajax call. The ajax call is failing. How do I get something to return from the call? There should be a dictionary [cURL call returns a dictionary].
How do I know what is failing in my call? I don't know how to proceed in debugging it.
Thanks
curl -v -X PUT -H "Content-Type: application/json" -H "Accept: application/json" -X PUT --user user:pass https://my.address.for/this/url -d "{\"name\": \"Marcus0.3\",\"start\": 500000,\"end\": 1361640526000}"
$.ajax({
type: 'put',
url: 'https://my.address.for/this/url',
dataType: 'json',
async: false,
username: 'user',
password: 'pass',
data: {
"name": "Marcus0.3",
"start": 500000,
"end": 1361640526000
},
success: function(){alert('DONE!');},
error: function(){alert('fail');},
}).responseText;
I keep getting 'fail' responses
If you type F12 it will open up chrome dev tools, then click on the network tab.
You will see all requests, including ajax requests as they happen. You can click on the line item "name" field for full info about the request and response, similar to cURL verbose mode
You can use Firefox with firebug to get the exact error message.Else do like this
error:function(error){alert(error)}

Categories

Resources