x-www-form-urlencoded multiple keys in ajax - javascript

i have this code in ajax
var settings = {
"url": "https://sample.com",
"method": "POST",
"timeout": 0,
"headers": {
"Authorization": basicauth,
"Content-Type": "application/x-www-form-urlencoded"
},
"data": {
"key": "value1",
"key": "value2"
}
};
$.ajax(settings).done(function(response) {
console.log(response);
});
when i execute that code it only submit the value2. How can i make it submit the value1 and value2?

Having duplicate keys in an object will just have the previous values overwritten. To send multiple values with the same key with $.ajax you can pass an array as the value. By default $.ajax uses PHP style parameters so [] will be appended to your key, to avoid this you have to set the parameter traditional: true.
var settings = {
"url": "https://sample.com",
"method": "POST",
"timeout": 0,
"headers": {
"Authorization": basicauth,
"Content-Type": "application/x-www-form-urlencoded"
},
"data": {
"key": ["value1", "value2"]
},
traditional: true,
};
$.ajax(settings).done(function(response) {
console.log(response);
});

Related

How to make an AJAX call to GraphHopper Matrix API

I need to send this json with the following information, but at the time of making the request I get an error
message: "Unsupported content type application/x-www-form-urlencoded; charset=UTF-8"
status: "finished"
I don't the correct way to the request
request sent for JS and Jquery:
<script>
$("#request").click(() => {
var url = "https://graphhopper.com/api/1/matrix?key=d5ab0f9f-538a-4842-926a-9667970d4061";
var data = {
"elevation": false,
"from_points": [-33.467482, -70.624736],
"to_points": [
[-33.468756, -70.622155],
[-33.467359, -70.627332],
[-33.466348, -70.621985]
],
"from_point_hints": ["nuble"],
"to_point_hints": [
"place 1",
"place 2",
"place 3"
],
"out_arrays": [
"distances",
"times"
],
"vehicle": "car"
};
$.ajax({
url: url,
data: JSON.stringify(data),
method: 'POST',
dataType: 'json',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
});
</script>
you must first enter the longitude and then the latitude and the next error you had was to specify the head of the ajax request
the code would be:
var url = "https://graphhopper.com/api/1/matrix?key=myKey";
var data ={
"from_points": [
[
-70.6247406,
-33.4673461
]
],
"to_points": [
[
-70.913138,
-33.794796,
]
],
"from_point_hints": [
"ñuñoa"
],
"to_point_hints": [
"places 1"
],
"out_arrays": [
"times",
"distances"
],
"vehicle": "car"
};
$.ajax({
beforeSend: function(xhrObj) {
xhrObj.setRequestHeader("Content-Type", "application/json");
xhrObj.setRequestHeader("Accept", "application/json");
},
url: url,
data: JSON.stringify(data),
type: 'POST', //en este caso
dataType: 'json',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});

Request parameters not read when calling Google Cloud Printing API

I'm trying to use the Google Cloud Printing API. I previously had problems relating to the sending of my request. After some json/stringifying experimentation, I no longer get that error. Instead, my API calls are unsuccessful according to the response sent back by the Google API. Here's what I'm doing:
// Ticket used for google cloud printing
const ticket = {
"version":"1.0",
"print":{
"color":{"vendor_id":"psk:Color","type":0},
"duplex":{"type":0},
"page_orientation":{"type":0},
"copies":{"copies":1},
"dpi":{"horizontal_dpi":1200,"vertical_dpi":1200},
"media_size":{"width_microns":80000,"height_microns":58000,"is_continuous_feed":false},
"collate":{"collate":true},
"vendor_ticket_item":[
//Printer specific settings here, from the capabilities:
{"id":"psk:JobInputBin","value":"ns0000:Tray3"},
{"id":"psk:PageICMRenderingIntent","value":"psk:Photographs"},
{"id":"psk:PageMediaType","value":"ns0000:Auto"},
{"id":"psk:JobOutputBin","value":"ns0000:Auto"},
//etc.
]
}
}
request({
"method": "POST",
"content-type" : "application/json",
"url": googlePrintUrl + "submit",
"headers": {
"Authorization": "OAuth " + googleAccessToken
},
"body" : {
"printerid": "39875g133-ae7d-76hg-65af-jhe5bc682404",
"ticket": JSON.stringify(ticket),
"title": "TEST PRINT",
"content": "test msg",
"contentType": "text/plain"
},
"json": true
}, function (error, res, body){
if (error) {
console.log("There was an error with Google Cloud Print");
console.log(error);
return;
}
console.log("The server responded with:", body);
});
this request results in this response from the server:
The server responded with: { success: false,
request:
{ time: '0',
params: {},
user: 'mytest#gmail.com',
users: [ 'mytest#gmail.com' ] },
errorCode: 3,
message: 'Printer Id required for this request.' }
As you can see, the params field is empty. This is strange because when I use Postman to do the same request, this field is filled with the params I sent in the API call. Here's how I successfully did it in Postman:
Which generated the server response:
{
"success": true,
"request": {
"time": "0",
"params": {
"ticket": [
"{\"version\":\"1.0\",\"print\":{\"color\":{\"vendor_id\":\"psk:Color\",\"type\":0},\"duplex\":{\"type\":0},\"page_orientation\":{\"type\":0},\"copies\":{\"copies\":1},\"dpi\":{\"horizontal_dpi\":600,\"vertical_dpi\":600},\"media_size\":{\"width_microns\":80000,\"height_microns\":58000,\"is_continuous_feed\":false},\"collate\":{\"collate\":true},\"vendor_ticket_item\":[{\"id\":\"psk:JobInputBin\",\"value\":\"ns0000:Tray3\"},{\"id\":\"psk:PageICMRenderingIntent\",\"value\":\"psk:Photographs\"},{\"id\":\"psk:PageMediaType\",\"value\":\"ns0000:Auto\"},{\"id\":\"psk:JobOutputBin\",\"value\":\"ns0000:Auto\"}]}}"
],
"printerid": [
"39875g133-ae7d-76hg-65af-jhe5bc682404"
],
"title": [
"TEST"
],
"contentType": [
"text/plain"
],
"content": [
"**** test"
]
},
"user": "mytest#gmail.com",
"users": [
"mytest#gmail.com"
]
},
"xsrf_token": "AIp06DhAZRSLW9GlHWQLKykbpU-5fYRqcA:1531484990909",
"message": "Print job added.",
"job": {
"ticketUrl": "https://www.google.com/cloudprint/ticket?jobid\u003df11043fe-3e00-d912-11dd-c859718a5575",
"printerName": "",
"errorCode": "",
"updateTime": "1531484993830",
"title": "**** TEST",
"message": "",
"ownerId": "mytest#gmail.com",
"tags": [
"^own"
],
"uiState": {
"summary": "QUEUED",
"progress": "Delivery attempts: 1"
},
"numberOfPages": 1,
"createTime": "1531484991068",
"semanticState": {
"delivery_attempts": 1,
"state": {
"type": "QUEUED"
},
"version": "1.0"
},
"printerid": "39875g133-ae7d-76hg-65af-jhe5bc682404",
"fileUrl": "https://www.google.com/cloudprint/download?id\u003df11043fe-3e00-d912-11dd-c859718a5575",
"id": "f11043fe-3e00-d912-11dd-c859718a5575",
"rasterUrl": "https://www.google.com/cloudprint/download?id\u003df11043fe-3e00-d912-11dd-c859718a5575\u0026forcepwg\u003d1",
"contentType": "application/pdf",
"status": "QUEUED"
}
}
This is a successful printing job, and all the parameters sent by me are sent back in the response object.
So where am I going wrong in my node.js code?
Postman sends payload (printerid, content, title, etc) in formData rather than body
Underneath the "SEND" button is a button "Code" that can generate functional NodeJS (and other) snippets like
var request = require("request");
var options = { method: 'POST',
url: 'https://www.google.com/cloudprint/submit',
headers:
{ 'cache-control': 'no-cache',
Connection: 'keep-alive',
'Content-Length': '769',
'Accept-Encoding': 'gzip, deflate',
Host: 'www.google.com',
'Cache-Control': 'no-cache',
'Content-Type': 'application/json',
Authorization: 'Bearer ya29.GlxWB5_vr8QmJw3DChvVyqpRhNJ2hsuVzwNTJoYRH6r2VVGTwDE3MLNAN8pjTB3-BDWtZeIDrCDcP5DwYGywM1vgb9VMPhoi806HrMpOpKAaKzrgiliojec6IB2Cwg',
'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' },
formData:
{ printerid: 'd936d368-7ea4-6f66-84fd-6d5a7a357318',
title: 'Document Title',
content: 'Hello World',
ticket: '{"version":"1.0","print":{"vendor_ticket_item":[],"color":{"type":"STANDARD_MONOCHROME"},"copies":{"copies":1}}}',
contentType: 'text/plain' } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});

When timeout and when abort occur in $http.get?

AngularJS 1.6.6 has support for differentiation between XHR completion, error, abort, timeout, I have this code snippet which make a request to a url like below:
$http.get(url, {timeout: 1000})
.then(...)
.catch(function(error) {
console.log(error.xhrStatus) // could be abort, complete, error and timeout
});
When requesting my api takes more than 1 second the promise is rejected with xhrStatus of 'abort', I was wondering in what situation I will get 'timeout' and 'error' status texts?
Edit: It would be awesome if the answer provide the relevant server side code in Web Api
"timeout" will never occur as far as I can tell since the xhr in the $httpBackend never has a timeout property set instead angular uses it's own mechanism for aborting the xhr request if the timeout ms expires or the promise passed in resolves.
https://github.com/angular/angular.js/blob/master/src/ng/httpBackend.js#L165
"error" will occur if a request has been dispatched and the network connection has gone down
If a 500 or 200 comes back the status will be complete but angular will fire the success or error/catch handlers on the http promise depending on the status code.
Test result model (note I disconnected the network to get the result for test3.php, the test.html page loaded, then I disconnected the network before the setTimeout fired the get hence forcing the xhr.status to error)
{
"msg1": {
"data": {
"val": "test"
},
"status": 200,
"config": {
"method": "GET",
"transformRequest": [
null
],
"transformResponse": [
null
],
"jsonpCallbackParam": "callback",
"timeout": 1000,
"url": "test1.php",
"headers": {
"Accept": "application/json, text/plain, */*"
}
},
"statusText": "OK",
"xhrStatus": "complete"
},
"msg2": {
"data": null,
"status": -1,
"config": {
"method": "GET",
"transformRequest": [
null
],
"transformResponse": [
null
],
"jsonpCallbackParam": "callback",
"timeout": 1,
"url": "test2.php",
"headers": {
"Accept": "application/json, text/plain, */*"
}
},
"statusText": "",
"xhrStatus": "abort"
},
"msg3": {
"data": null,
"status": -1,
"config": {
"method": "GET",
"transformRequest": [
null
],
"transformResponse": [
null
],
"jsonpCallbackParam": "callback",
"url": "test3.php",
"headers": {
"Accept": "application/json, text/plain, */*"
}
},
"statusText": "",
"xhrStatus": "error"
},
"msg4": {
"data": "",
"status": 500,
"config": {
"method": "GET",
"transformRequest": [
null
],
"transformResponse": [
null
],
"jsonpCallbackParam": "callback",
"url": "test4.php",
"headers": {
"Accept": "application/json, text/plain, */*"
}
},
"statusText": "Internal Server Error",
"xhrStatus": "complete"
}
}
Test.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.js"></script>
<script>
angular.module('myApp', [])
.controller('MyCtrl', function($http){
var url1 = "test1.php";
var url2 = "test2.php";
var url3 = "test3.php";
var url4 = "test4.php";
var ctrl = this;
ctrl.model={msg1:null, msg2:null, msg3:null, msg4:null}
$http.get(url1, {timeout: 1000})
.then(function(resp){
ctrl.model.msg1 = resp
})
.catch(function(error) {
ctrl.model.msg1 = error;
});
$http.get(url2, {timeout: 1})
.then(function(resp){
ctrl.model.msg2 = resp
})
.catch(function(error) {
ctrl.model.msg2 = error;
});
setTimeout(function(){
$http.get(url3)
.then(function(resp){
ctrl.model.msg3 = resp
})
.catch(function(error) {
ctrl.model.msg3 = error;
});
}, 2000);
$http.get(url4)
.then(function(resp){
ctrl.model.msg4 = resp
})
.catch(function(error) {
ctrl.model.msg4 = error;
});
});
</script>
</head>
<body ng-app="myApp" ng-controller="MyCtrl as myCtrl">
<pre>{{myCtrl.model|json}}</pre>
</body>
</html>
test1.php
<?php
echo "{\"val\":\"test\"}";
test2.php
<?php
sleep(10);
test3.php
<?php
sleep(1000);
test4.php
<?php
throw new Exception("Error");

Recreating Ajax POST

I want to recreate Ajax POST which I can peak via Chrome's debugger.
I created post like this:
$.ajax({
method: "POST",
url: url,
contentType: "application/json; charset=UTF-8",
data: { "defaults": "default", "culture": "en-US", "skip": 20, "take": 20, "query": "", "filters": [], "fulltext": [], "sorting": { "field": "ModifiedOn", "asc": false } }
})
.done(function (msg) {
alert("Data Saved: " + msg);
});
I'm getting 500 error. I check and my Request Payload looks like this:
defaults=default&culture=en-US&skip=20&take=20&query=&sorting%5Bfield%5D=ModifiedOn&sorting%5Basc%5D=false
However the source post, which I want to recreate has different Request Payload:
{"defaults":"default","culture":"en-US","skip":20,"take":20,"query":"","filters":[],"fulltext":[],"sorting":{"field":"ModifiedOn","asc":false}}
I think it is causing the error.
How can I modify my request to make Request Payload look like the latter one?
data: { "defaults": "default", "culture": "en-US", "skip": 20, "take": 20, "query": "", "filters": [], "fulltext": [], "sorting": { "field": "ModifiedOn", "asc": false } }
This line is causing the Error. You need to stringify your Data like so:
data: JSON.stringify({ "defaults": "default", "culture": "en-US", "skip": 20, "take": 20, "query": "", "filters": [], "fulltext": [], "sorting": { "field": "ModifiedOn", "asc": false } })
Please read the documentation about jQuery.ajax()-function. You can check all Parameters with their Type.

How to calculate length of object being sent in POST

I've an object like
{
"Id": 1,
"Value": 10,
"UId" : "ab400"
}
How can I calculate the length of this so that I'm able to send it in ajax request.
$.ajax({
url: 'http://gdata.youtube.com/feeds/api/videos/keDZXXDxK1c/ratings',
type:"POST",
data: data,
headers: {
"Content-Type":"application/atom+xml",
"Content-Length": data.length,
I tried using stringfying the JSON but the length comes incorrect
Tried : JSON.stringify(data).length
you should use JSON.stringify() to get the complete string then apply length attribute to get length.
var data = {
"Id": 1,
"Value": 10,
"UId" : "ab400"
}
var Length = JSON.stringify(data).length;
console.log(Length);//33
console.log(data.length);//undefined, because here data is object not string.
You are calculating the length correctly, so possibly a syntax error before the ajax request.
var data = {
"Id": 1,
"Value": 10,
"UId" : "ab400"
}
var dataLength = JSON.stringify(data).length;
$.ajax({
url: 'http://gdata.youtube.com/feeds/api/videos/keDZXXDxK1c/ratings',
type:"POST",
data: data,
headers: {
"Content-Type":"application/json; charset=utf-8",
"Content-Length": dataLength
},
success: function(data){
console.log(data);
},
error: function(data) {
console.log(data);
}
});

Categories

Resources