Post jQuery JSON Object to NodeJs Restify - ajax

I want to know why it is so hard to post a simple JSON string in a /:parameter to restify. I have followed many examples but have not found anything concrete.
I have the following code in the front end.
$("#btnDoTest").click(function() {
var jData = {
hello: "world"
};
var request = $.ajax({
url: "http://localhost:8081/j/",
async: false,
type: "POST",
data: JSON.stringify(jData),
contentType: "application/javascript",
dataType: "json"
});
request.success(function(result) {
console.log(result);
});
request.fail(function(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
});
I am succesful in sending simple text if I concatenate the param after the j/. But what I want to send is an object like this {hello:"world"} and reconstruct it back in nodeJS and work with it.
--Edit:
This is my nodejs file
/* the below function is from restifylib/response.js */
var restify = require("restify");
/* create the restify server */
var server = restify.createServer({
});
server.use(restify.bodyParser({ mapParams: true }));
server.use(
function crossOrigin(req,res,next){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
return next();
}
);
server.post('/j/', function (req, res, next) {
//res.send(201,"REceived body: "+JSON.stringify(req.params));
res.send(201,"REceived body: "+JSON.stringify(req.params));
return next();
});
var port = 8081;
server.listen(port);
console.log("Server listening on port " +port)
Any help would be appreciated thanks.
0x

I finally got it working.
--Front end code
$("#btnDoTest").click(function() {
var request = $.ajax({
url: "http://localhost:3000/j",
async: false,
type: "POST",
data: {
blob: {wob:"1",job:"2", ar:[1,2,{a:'b'}]}
},
contentType: "application/x-www-form-urlencoded", //This is what made the difference.
dataType: "json",
});
request.success(function(result) {
console.log(result);
});
request.fail(function(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
});
NodeJs services
/* the below function is from restifylib/response.js */
var restify = require("restify");
/* create the restify server */
var server = restify.createServer({
});
server.use(restify.bodyParser());
server.use(restify.CORS());
server.post('/j/', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
// req.params == data on jquery ajax request.
res.send(200, JSON.stringify(req.params));
console.log(req.params.blob.ar[2].a)
res.end();
return next();
});
var port = 3000;
server.listen(port);
console.log("Server listening on port " + port)

Don't stringify it. Try this, note the two changes, I removed the JSON.stringify and switched to application/json, as its JSON and not JavaScript.
var request = $.ajax({
url: "http://localhost:8081/j/",
async: false,
type: "POST",
data: jData,
contentType: "application/json",
dataType: "json"
});
application/javascript should only be used when doing JSONP.

my answer first!
jquery:
$.ajax({
url: url,
method: 'post',
data: JSON.stringify({key:value}),
contentType: "application/json"
});
node http:
server.post('/1', function(req, res) {
var body = req.body;
var dataValue = body.dataKey;
});
why?
data of $.ajax is just for what to send to server end, its datatype has not be defined, so when use JSON.stringify({key:value}), the data will be sent as a string like '{key:"xxx"}', and node recieve a string, not a json object even the string structure looks like a json. but after we add contentType: "application/json" in $.ajax, when node recieve the data, it will be a real json object type data.

Related

laravel - ajax formdata wont show in controller

I have tried many different combination for AJAX Setup in order to send the formData to controller. Somehow I cannot get the form input inside my controller despite trying to return it will all type of ways. May I know what did I miss that causing me not be able to get the input in controller?
$("#formCropUpdate").on("submit", function (event) {
event.preventDefault();
var formId = $('#formId').val();
var url = '/Form/' + formId;
var form = this;
formData = new FormData(form);
console.log(Array.from(formData));
$.ajax({
url: url,
type: "PATCH",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
cache: false,
dataType: false,
contentType: false,
processData: false,
data:formData,
success: function (response) {
console.log(response);
return false;
},
});
});
public function update(Request $request){
$UserId = Auth::user()->id;
$Company = Company::where('id', Auth::user()->company_id)->first();
return $request->all();
}
use
<meta name="csrf-token" content="{{ csrf_token() }}">
in head
and jQuery code
$('#form_submit').submit(function (e) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
e.preventDefault();
var base = window.location.origin;
let formData = new FormData(this);
let my_url = base + "/article-store";
$.ajax({
type: 'post',
url: my_url,
data: formData,
cache: false,
contentType: false,
processData: false,
success: (data) => {
},
error: function (data) {
}
});
});
After quite a bit of digging, since what I am doing is using the PATCH request, it's still not working as of now with FormData. To solve it, we need to spoof the method by appending the PATCH method to formData and our AJAX settings to be changed to POST. Then you'll receive all the request inside your controller.
Reference:
https://laracasts.com/discuss/channels/laravel/ajax-formdata-and-put-fails
https://laracasts.com/discuss/channels/javascript/axiosajax-http-patch-requests-with-file-not-working
$("#formCropUpdate").on("submit", function (event) {
event.preventDefault();
var formId = $('#formId').val();
var url = '/Form/' + formId;
var form = this;
formData = new FormData(form);
formData.append('_method', 'PATCH');
console.log(Array.from(formData));
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: url,
data:formData,
cache: false,
contentType: false,
processData: false,
success: function (response) {
console.log(response);
return false;
},
});
});

File upload using jquery/ajax for REST API

I was trying to upload file to a remote server using REST api by ajax/jquery with the following script, but it returns 400 error with a Bad request. I have tested the end point with curl, which is giving correct response and file is being uploaded.
$(document).ready(function () {
$("#btnSubmit").click(function (event) {
//stop submit the form, we will post it manually.
event.preventDefault();
fire_ajax_submit();
});
});
function fire_ajax_submit() {
// Get form
var form = $('#fileUploadForm')[0];
alert(form.files[0]);
var data = new FormData(form);
data.append("CustomField", "This is some extra data, testing");
$("#btnSubmit").prop("disabled", true);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "http://10.13.20.166:5332/fileUploadtoFolder",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
$("#result").text(data);
console.log("SUCCESS : ", data);
$("#btnSubmit").prop("disabled", false);
},
error: function (e) {
$("#result").text(e.responseText);
console.log("ERROR : ", e);
$("#btnSubmit").prop("disabled", false);
}
});
}
Change your code 👇
var data = new FormData(form);
Use this code 👇
// Create an FormData object
var data = new FormData(document.getElementById("fileUploadForm"));
Try again

Angular Datatables use source object

With Angular Datatables I want to pre-load a JSON object with Ajax so that I can re-use the object elsewhere without doing another ajax request.
But how do I load this object into the datatable?
.controller('ResponsiveDatatableCtrl', function ($scope, $rootScope, DTOptionsBuilder, DTColumnBuilder, apiserv, $filter, $state, $http) {
$scope.dataLoading2 = true;
var vm = this;
var data = "?db="+ $rootScope.globals.currentUser.agents[$rootScope.globals.currentDB].db_name;
var url = apiserv+"api.files.php"+data;
var headers = {'Content-Type': 'application/x-www-form-urlencoded'};
$http({
method: 'POST',
url: url,
headers: headers,
})
.success(function (response) {
$rootScope.globals.files = response;
$scope.dataLoading2 = false;
//console.log($rootScope.globals.files);
});
vm.dtOptions = DTOptionsBuilder.fromFnPromise($rootScope.globals.files)
.withPaginationType('full_numbers')
.withBootstrap()
.withOption('responsive', true);
})
Ok I have attempted the following and it seems to call my code under success but then the table doesn't update?
vm.dtOptions = DTOptionsBuilder.newOptions().withOption('ajax', {
url: url,
type: 'POST',
headers: headers,
data: function(data, dtInstance) {
},
success: function(response) {
$rootScope.globals.files = response;
}
})
.withPaginationType('full_numbers')
.withBootstrap()
.withOption('responsive', true);

$.ajax() to $.getJSON()

I would like to ask if there is a method to parse data from $.ajax() to $.getJSON() please?
This is the $.ajax() example:
var apiUrl = 'https://api.com/url_here';
var apiKey = 1234567890;
var apiSecret = 0987654321;
var data = {};
$.ajax({
url: apiUrl,
headers: {
"Authorization": "Basic " + btoa(apiKey+ ":" + apiSecret)
},
data: data,
dataType: 'json',
type: 'GET',
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data);
}
});
And this is what I have in my $.getJSON(), where I have a struggle in calling the headers for authentication:
$.getJSON(apiUrl, function(json){
console.log(JSON.stringify(json));
});
Thanks a lot! xxx

I don't receive data from formdata in my sails.js server

I have this ajax request:
this.sendApiRequestWithFile = function (method) {
var formData = new FormData();
formData.append("name", "my name");
data_ajax = {
url: "http://localhost:1337/" + method,
method: "PUT",
data: formData,
headers: {
'Cache-Control': 'no-cache',
'Content-Type': 'multipart/form-data; boundary=----',
}
}
return $http(data_ajax).success(function(data, status, headers, config) {
return data;
}).error(function(data, status, headers, config) {
return data;
});
}
And my server is in sails.js so I catch parameters like this: req.body and it doesn't work. I try req.params.all() and doesn't work too.
I hope the following code should work. If you try to access the uploaded file from server, use req.file("file_name")
var fd = new FormData()
fd.append("name", "name value")
$.ajax({
url: "/url",
type: "POST",
data: fd,
processData: false,
contentType: false,
success: function(response) {
console.log("Success : " + response);
},
error: function(jqXHR, textStatus, errorMessage) {
console.log(errorMessage); // Optional
}
});
});

Resources