Converting cURL to Ajax and getting back Error 400 - javascript

I am trying to store specific urls into jsonbox. However, I have been getting Error 400.
The curl command from the documentation is as below:
curl -X POST 'https://jsonbox.io/demobox_6d9e326c183fde7b' \
-H 'content-type: application/json' \
-d '{"name": "Jon Snow", "age": 25}'
Below is my edited code, putting in the link for jsonbox and URL as the data.
function send_request(url) {
this.url = url;
$.ajax({
url: 'https://jsonbox.io/box_89ad34d6d995aeb9ebb4',
type: 'post',
data: JSON.stringify(this.url),
dataType: 'json',
contentType: 'application/json',
success: function (data) {
alert(JSON.stringify(data));
},
error: function(){
alert("Cannot get data");
}
})
}
What am I missing or doing wrong here?

The issue seems to be the payload. Not sure why are you sending the url with your POST request. Check this working snippet:
$(document).ready(function() {
var payload = {
"name": "Maria",
"age": 78
}
$.ajax({
url: 'https://jsonbox.io/demobox_6d9e326c183fde7b',
type: 'POST',
data: JSON.stringify(payload),
dataType: 'json',
contentType: 'application/json',
success: function (data) {
console.log(data);
},
error: function(){
console.log("Cannot get data");
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Related

How can I send a curl request from javascript?

I would like to send this
curl https://fcm.googleapis.com/fcm/send \
-H "Content-Type: application/json" \
-H "Authorization: key=<MY API KEY>" \
-d '{ "notification": {"title": "Hello world", "body": "you got a new message", "icon": "icon/path","click_action" : "page/path"},"to" : "<DEVICE TOKEN>"}'
from a js file to wherever I want. Considering the ideas you are giving me bellow, now I'm trying with this:
$.ajax({
url: "https://fcm.googleapis.com/fcm/send",
type: 'POST',
dataType: 'json',
headers: {
'Access-Control-Allow-Origin' : '*',
'Authorization': '<APY KEY>',
'contentType': 'application/json',
},
data: {
'title': 'Hello world!',
'body': 'you got a new message',
'icon': 'icon/path',
'click_action' : 'page/path',
'to' : '<DEVICE TOKEN>',
},
success: function (result) {
alert(JSON.stringify(data));
},
error: function (error) {
alert("Cannot get data");
}
});
but I'm getting this error: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present
Curl doesn't exist in JavaScript, instead you can use XMLHttpRequest. To make it even more easy, you can use jQuery to send an AJAX request.
Here is some example code:
$.ajax({
type: "POST",
url: "http://yourdomain.com/example.php",
data: {
api_key: "xxxxxxxx"
},
success: function(data) {
console.log(data);
//do something when request is successfull
},
dataType: "json"
});

How to add extra fields in request JSON sent to DialogFlow former Api.ai

I am trying to append extra information to the jsonrequest that is sent from my application to DialogFlow. I am aware of the possibility to send data calling an intent by triggering its event from Sending Parameters in a Query Request, and I am using that method already for other functionality.
Basically, I am trying to add a value with the userID, and I need to retrieve that value in DialogFlow. I am keepeing track of the session in php, so I am using phpto get ID value. I have tried to do the following in the ajaxrequest:
$.ajax({
type: "POST",
url: baseUrl + "query?v=20150910",
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
"Authorization": "Bearer " + accessToken
},
//This folllowing line is the modified part:
data: JSON.stringify({
query: text,
lang: "en",
sessionId: "somerandomthing",
userId: "100"
}),
success: function(data) {
},
error: function() {
setResponse("Internal Server Error");
}
});
And this one as well:
$.ajax({
type: "POST",
url: baseUrl + "query?v=20150910",
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
"Authorization": "Bearer " + accessToken
},
//This folllowing line is the modified part:
data: JSON.stringify({
query: text,
lang: "en",
sessionId: "somerandomthing",
userId: "100",
parameters: {
userId: "100"
}
}),
success: function(data) {
},
error: function() {
setResponse("Internal Server Error");
}
});
I need that value in the request to process some data in the back-end based on it. If anyone knows how to do it, or has suggestions for a better approach that would be much appreciated.
There are discussion posts related to this in the DialogFlow Forums, but there is still no resolution. The feature might not be available, or it is not documented Link 1, Link 2, Link 3.
I solved this issue with the help of #Svetlana from Dialogflow. The original post is Here, and here is an example from a JavaScript application with back-end in Node.js:
You would format your request like:
$.ajax({
type: "POST",
url: baseUrl + "query?v=20150910",
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
"Authorization": "Bearer " + accessToken
},
data: JSON.stringify({originalRequest: {data: {exampleMessage: 'Test'}}, query: text, lang: 'en', sessionId: 'somerandomthing'}),
success: function (data) {
},
error: function () {
setResponse("Internal Server Error");
}
});
and you would access the value in the webhook with:
var exampleMessage = req.body.originalRequest.data.exampleMessage;
or
var exampleMessage = req.body.originalRequest.data['exampleMessage'];
Hope this helps.

cURL to jQuery AJAX conversion

I've racked my brain over this and I cant seem to figure out the solution so ask humbly for your assistance please. I'm using the restlet client on chrome which uses a cURL command to GET json from a server. I need to convert this curl command over to AJAX, and I'll provide as much code as I'm allowed to. Could you please help me by converting this over to jQuery's Ajax?
cURL Command:
curl -i -L -X GET \
-H "Authorization:Basic base64username:base64password" \
'https://internalserverurl'
Here's what I have for my jQuery AJAX Method:
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = Base64.encode(tok);
return "Basic " + hash;
}
function getData() {
$.ajax({
url: "https://internalurl",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa("username:password"));
},
type: 'GET',
dataType: 'json',
contentType: 'application/json',
processData: false,
success: function (data) {
alert(JSON.stringify(data));
console.log(data);
},
error: function (data) {
var strBuilder = [];
for(key in data){
if (data.hasOwnProperty(key)) {
strBuilder.push(key + ":" + data[key] + "<br><br>");
}
}
alert(strBuilder.join(""));
$('#errordiv').html(strBuilder);
}
});
}
Thank you all for your assistance.
I said it in the comments, but you can use the $.ajax function and set your headers in the beforeSend block.
$.ajax({
url: 'https://internalserverurl',
type: 'GET',
dataType: 'json',
success: function() { alert('hello!'); },
error: function() { alert('boo!'); },
beforeSend: setHeader
});
});
function setHeader(xhr) {
xhr.setRequestHeader('Authorization':'Basic base64username:base64password');
}

Trouble Converting cURL request to Javascript

I don't know what's wrong. I've spent almost an hour reading and re-reading, checking my spelling etc. I was hoping maybe someone can point out what I'm doing wrong.
This is the cURL statement that returns successfully in the terminal:
curl https://api.gumroad.com/v2/products \
-d "access_token=123456abcdef" \
-X GET
The following are some of my attempts that did not work. And yes, I'm certain jQuery has been loaded:
$.ajax({
url: "https://api.gumroad.com/v2/products",
data: "access_token=123456abcdef",
success: function(result){
console.log(result);
}});
And this one:
$.ajax({
url: "https://api.gumroad.com/v2/products",
data: "access_token=123456abcdef",
processData: false,
type: "get",
success: function(result){
console.log(result);
}});
And another one:
$.ajax({
url: url,
beforeSend: function(xhr) {
xhr.setRequestHeader("access_token", "123456abcdef")
}, success: function(data){
alert(data);
//process the JSON data etc
}
})
Looks like you are sending a string instead of a data object, try this:
$.ajax({
url: "https://api.gumroad.com/v2/products",
data: {access_token: "123456abcdef"},
processData: false,
type: "get",
success: function(result) {
console.log(result);
}
});

Setting request header in ajax

I have trouble with a piece of ajax code. This is the error message I get from mod security:
/ajaxController.php?mod=catalog&op=ajaxSeenProducts HTTP/1.1
Access denied with code 400 (phase 2). Operator EQ matched 0 at
REQUEST_HEADERS. [file "/usr/local/apache/conf/modsec2.user.conf"]
[line "12"] [id "960012"] [msg "POST request must have a
Content-Length header"] [severity "WARNING"] [tag
"PROTOCOL_VIOLATION/EVASION"]
There is a module in the web shop I am working on, which shows the last viewed products, and the jquery code I have is this:
$('#seen_products_box').ready(function() {
$.ajax({
type: "POST",
url: "{HOME}ajaxController.php?mod=catalog&op=ajaxSeenProducts",
success: function(seenProducts) {
$('#seen_products_box').empty();
$('#seen_products_box').append(seenProducts);
}
});
});
While searching for the solution, I have found in various places that I need to set the
Content-length
parameter, but all I have found is in this format:
xmlHttp.setRequestHeader("Content-length", params.length);
Is there any way to set the request header in the code format I have provided above? I have already tried something like:
headers: {
"Content-Length": params.length
}
but with no result. Any help would be appreciated.
use code like:
var url = '{HOME}ajaxController.php?';
var data = "mod=catalog&op=ajaxSeenProducts";
$.ajax({
url: url,
data: data,
dataType: "html",
type:'post',
success:function(seenProducts){
$('#seen_products_box').empty();
$('#seen_products_box').append(seenProducts);
},
error:function(response){
}
});
you can use the beforeSend function to set the headers
$('#seen_products_box').ready(function() {
$.ajax({
type: "POST",
beforeSend: function (request)
{
request.setRequestHeader("Authority", authorizationToken);
},
url: "{HOME}ajaxController.php?mod=catalog&op=ajaxSeenProducts",
success: function(seenProducts) {
$('#seen_products_box').empty();
$('#seen_products_box').append(seenProducts);
}
});
});
or other way you can do it like
$('#seen_products_box').ready(function() {
$.ajax({
type: "POST",
headers: {"X-Test-Header": "test-value"},
url: "{HOME}ajaxController.php?mod=catalog&op=ajaxSeenProducts",
success: function(seenProducts) {
$('#seen_products_box').empty();
$('#seen_products_box').append(seenProducts);
}
});
});

Categories

Resources