Okay, this seems to be the most straight forward thing, but I really have no idea why it's doing this nor find anyone else with this problem.
Here's my issue, I'm sending a POST request like so;
$.ajax({
type: "POST",
url: '/user/sell',
data: data,
success: function(data) {
console.log('Call was successful');
}
});
In the data object is an array called items. When I log the data object it's fine, like it should be, however when I log the data object in my express function the items array changes to items[] for no reason..
NodeJS
'items[]': '15716345'
JS (Browser)
items: [15716345]
Any idea what's happening here?
Below is the entire version of the code.
Entire block (frontend)
// Validate address
if($('.block.payment .wrapper input:eq(0)').val() !== $('.block.payment .wrapper input:eq(1)').val()){
return error('Fields do not match');
}
// Get known data
var type = $('.body.inventory .methods .method.selected').data('type'),
items = [];
var data = {
type,
address: $('.block.payment .wrapper input:eq(0)').val()
}
if(type === 'steam'){
var app = $('.body.inventory .sub-methods .method.selected').data('app');
data['app'] = app;
$('.body.inventory .item[data-app="'+app+'"].selected').each(function(){
items.push($(this).data('id'));
});
}else{
$('.body.inventory .item[data-type="'+type+'"].selected').each(function(){
items.push($(this).data('id'));
});
}
data['items'] = items;
// Execute route or smt
$.ajax({
type: "POST",
url: '/user/sell',
data: data,
success: function(data) {
console.log('Call was successful');
}
});
Backend
router.post('/sell', function(req, res, next) {
try {
console.log(req.body);
res.send({
success: 1
});
} catch(e) {
if(e) console.log(e);
res.send({
success: 0,
error: e
});
}
});
Set JSON body parser middleware for requests to your expressJS application.
const bodyParser = require('body-parser');
app.use(bodyParser.json())
And in the AJAX request, make the contentType to be application/json and not the default of application/x-www-form-urlencoded; charset=UTF-8'.
$.ajax({
contentType: 'application/json',
type: "POST",
url: '/user/sell',
data: data,
success: function(data) {
console.log('Call was successful');
}
});
Assume that is your Array List, which you want to POST.
object[] Obj = new object[1];
Obj [0] = "value1"
Obj [1] = "Value2"
Obj [3] = {"CollectionValue1, CollectionValue2"}
$.ajax({
url: '../Controller/MethodName',
type: 'post',
datatype: 'json',
async: false,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ ControllerParameterName: Obj }), <!-- Obj is your Array -->
success: function (data) {
alert(data.Response);
}
});
Related
I have a text area with id "text" and I am toggling the text area to appear on the screen with a click event on some div and I have 30 such divs.
Initially , I'm assigning the textarea.value with result of ajax call to my fetch api which fetches the data from the mongo on the server side based on an unique id.
Sometimes , when I'm making the ajax call to my update api in my backend , the textarea.value I'm sending as data to this ajax call is not the same as the updated text of the text area.
//client side
// called when any of the divs is clicked
$(".radius").on("click", function(event) {
//extracting the id from the class and using this id as the id of my data for my mongo
var st=event.target.classList[1].substring(0,7);
var num=parseInt(event.target.classList[1].substring(7));
var toadd="close-button"+num;
//console.log(num+"modal")
closeButton.classList.add(toadd);
$.ajax({type: "POST",
url: "/fetch",
async: true,
data: JSON.stringify({
id: num,
}),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success:function(result) {
input.value=result.text;
},
error:function(result) {
console.log("error")
}
});
modal.classList.toggle("show-modal");
});
// called when textarea is closed
function toggleModal1(event) {
var s1=closeButton.classList[closeButton.classList.length-1];
var st=s1.substring(12);
closeButton.classList.remove(s1);
var num=parseInt(st);
// event.preventDefault();
console.log(input.value)
$.ajax({type: "POST",
url: "/update",
data: JSON.stringify({
id:num,
text:input.value,
//input is my textarea
}),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success:function(result) {
},
error:function(result) {
console.log("error")
}
});
modal.classList.toggle("show-modal");
}
//server side
app.post("/fetch",function(req,res)
{
//console.log(req.body);
// var id1=req.body.id;
const findInDB= Fruit.findOne({id:req.body.id},function (err, docs) {
console.log(docs);
res.send({text:docs.text});
});
});
app.post("/update",function(req,res)
{
Fruit.updateOne({id:req.body.id},
{text:req.body.text}, function (err, docs) {
if (err){
console.log(err)
}
else{
console.log("Updated Docs : ", docs);
}
});
I'm trying to insert data into MongoDB using Mongoose, i created a form and sending data using two ajax post to the node, but Mongoose insert two document for each ajax call, I want to send my data to data as a single document.
This my server:
app.post("/cp" , upload , function(req , res){
console.log('file uploaded succcessfully');
var title = JSON.stringify(req.body.titles);
var file = req.file;
const courses = new Courses({
// courseTitle:c_title,
// courseSubtitle:c_subtitle,
// courseAuthor : c_creator,
// coursePrice : c_price,
courseVideo :file ,
courseTitles :title ,
// courseSpecs : c_specs,
courseValidation : 0
});
courses.save();
});
Mongoose insert a document with title and without file and a document with file and without title,
Ajax:
if(e.submitter.id == "submitpostCp"){
var data = {};
data.titles = titlesLis;
data.specs = specsLis;
data.submit = "submitAll";
var fileup = new FormData($('#form')[0]);
$.when(
$.ajax({
type: 'post',
url: '/cp',
data: JSON.stringify(data),
contentType: 'application/json',
xhrFields: {
withCredentials: false
},
headers: {
},
success: function (data) {
console.log('Success');
console.log(data);
},
error: function () {
console.log('We are sorry but our servers are having an issue right now');
}
})
).then(function() {
$.ajax({
url:'/cp',
type: 'POST',
contentType: false,
processData: false,
cache: false,
data: fileup,
success: function(res){
// alert(res);
},
error: function(){
alert('Error: In sending the request!');
}
})
});
}
In this case you should use findOneAndUpdate method with options {upsert: true}: https://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate
I would like to post Json to a web service on the same server. But I don't know how to post Json using JQuery. I have tried with this code:
$.ajax({
type: 'POST',
url: '/form/',
data: {"name":"jonas"},
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
But using this JQuery code the data is not received as Json on the server. This is the expected data at the server: {"name":"jonas"} but using JQuery the server receive name=jonas. Or in other words, it's "urlencoded" data and not Json.
Is there any way to post the data in Json format instead of urlencoded data using JQuery? Or do I have to use a manual ajax request?
You're passing an object, not a JSON string. When you pass an object, jQuery uses $.param to serialize the object into name-value pairs.
If you pass the data as a string, it won't be serialized:
$.ajax({
type: 'POST',
url: '/form/',
data: '{"name":"jonas"}', // or JSON.stringify ({name: 'jonas'}),
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
Base on lonesomeday's answer, I create a jpost that wraps certain parameters.
$.extend({
jpost: function(url, body) {
return $.ajax({
type: 'POST',
url: url,
data: JSON.stringify(body),
contentType: "application/json",
dataType: 'json'
});
}
});
Usage:
$.jpost('/form/', { name: 'Jonh' }).then(res => {
console.log(res);
});
you can post data using ajax as :
$.ajax({
url: "url",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ name: 'value1', email: 'value2' }),
success: function (result) {
// when call is sucessfull
},
error: function (err) {
// check the err for error details
}
}); // ajax call closing
I tried Ninh Pham's solution but it didn't work for me until I tweaked it - see below. Remove contentType and don't encode your json data
$.fn.postJSON = function(url, data) {
return $.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json'
});
The top answer worked fine but I suggest saving your JSON data into a variable before posting it is a little bit cleaner when sending a long form or dealing with large data in general.
var Data = {
"name":"jonsa",
"e-mail":"qwerty#gmail.com",
"phone":1223456789
};
$.ajax({
type: 'POST',
url: '/form/',
data: Data,
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
Using Promise and checking if the body object is a valid JSON. If not a Promise reject will be returned.
var DoPost = function(url, body) {
try {
body = JSON.stringify(body);
} catch (error) {
return reject(error);
}
return new Promise((resolve, reject) => {
$.ajax({
type: 'POST',
url: url,
data: body,
contentType: "application/json",
dataType: 'json'
})
.done(function(data) {
return resolve(data);
})
.fail(function(error) {
console.error(error);
return reject(error);
})
.always(function() {
// called after done or fail
});
});
}
Below is the relevant code (JS+jQuery on the client side):
function getuser(username, password) {
var user = new Object();
user.constructor();
user.username = username;
user.password = password;
//....
$("#a1").click(function () {
var u = getuser($("#username").val(), $("#password").val());
if (u == false) {
alert("error");
} else {
//....
}
});
}
The question is how to send var u to a session on the server side?
You can use ajax to accomplish this. Something like:
$.ajax({
url: "/Controller/Action/",
data: {
u: u
},
cache: false,
type: "POST",
dataType: "html",
success: function (data) {
//handle response from server
}
});
Then have a controller action to receive the data:
[HttpPost]
public ActionResult Action(string u)
{
try
{
//do work
}
catch (Exception ex)
{
//handle exceptions
}
}
Note that /controller/action will be specific to where youre posting the data to in your project
See the documentation
For example:
If you just want to do a simple post the following may suit your needs:
var user = getUser(username, password);
$.post(yourserverurl, user, function(response){console.log("iam a response from the server")});
As the documentation says:
This is a shorthand to the equivalent Ajax function:
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
So In your example:
$.ajax({
type: "POST",
url: "/mycontroller/myaction",
data: {user: getUser(username, password)},
success: function(responseFromServer){//handleResponseHere},
error: function(xhr){//handleyourerrorsHere}
dataType: yourdatatype
});
I am trying to make a comment form which adds a comment in array of blog schema
but when I am using ajax it is giving undefined below the places where I have console log and when I am using simple post request it is working fine.
I am using mongoose, nodejs , express, jquery ajax
my script is as follows
var frm = $('#commentForm');
frm.submit(function (e) {
e.preventDefault();
console.log('clicked');
$.ajax({
type: 'POST',
url: "/blog/addComment",
contentType: "application/json; charset=utf-8",
dataType: 'json'
})
.done(function(data) {
addNewComment(data);
})
.fail(function() {
console.log("Ajax failed to fetch data");
});
});
function addNewComment(data){
console.log(data);
}
my routes is as follows
//add comments
router.post('/addComment',function(req,res,next){
console.log(req.body.comment+" "+ req.body.userId+" "+req.body.postId);
var newComment = {
'text': req.body.comment,
'author': req.body.userId
}
Post.addComment(req.body.postId, newComment, function(err,comment){
if(err) throw err;
console.log(comment);
res.send(comment);
});
});
and my mongoose schema is
//add comments
module.exports.addComment = function( postId, newComment, callback){
var query = { '_id': postId};
console.log('postid: '+postId+" newcomment: "+newComment.text+ " "+newComment.author);
Post.findOneAndUpdate( query, { $push:{'comments': newComment} }, {new:true} , callback);
}
That's because data is not defined in ajax call ,
use following provide the frm is the actallu form or use
use data : form name.serialize()
var frm = $('#commentForm');
frm.submit(function (e) {
e.preventDefault();
console.log('clicked');
$.ajax({
data : $(this).serialize(),
type: 'POST',
url: "/blog/addComment",
contentType: "application/json; charset=utf-8",
dataType: 'json'
})
.done(function(data) {
addNewComment(data);
})
.fail(function() {
console.log("Ajax failed to fetch data");
});
});