I'm sending via AJAX to my server nodejs, with this JS on client side:
function login(){
var array=[];
var jsonData={};
jsonData.user=$('#user').val();
jsonData.pass=$('#pass').val();
array.push(jsonData);
console.log(JSON.stringify(array));
$.ajax({
method:'POST',
url: 'auth',
dataType: 'application/json',
data: JSON.stringify(array)
}).done(function(msg){
alert( "Data Saved: " + msg );
});
}
As can you see, before send ajax, the browser output console is:
[{"user":"User001","pass":"SecretPassword"}]
On server side, I have this code:
router.post('/', function(req, res, next){
console.log(req.body);
// { '[{"user":"User001","pass":"SecretPassword"}]': '' }
console.log(JSON.parse(req.body));
// {"[{\"user\":\"User001\",\"pass\":\"SecretPassword\"}]":""}
res.sendStatus(202);
}
But, if I test this web service with Postman, my server receives Json data correctly:
Screen capture
Please, does anyone help me??, I trying solve this about 2 days :(
Don't stringify data, it's supposed to be an object, so you can send jsonData directly:
function login(){
var array=[];
var jsonData={};
jsonData.user=$('#user').val();
jsonData.pass=$('#pass').val();
array.push(jsonData);
console.log(JSON.stringify(array));
$.ajax({
method:'POST',
url: 'auth',
dataType: 'application/json',
data: jsonData // << here
}).done(function(msg){
alert( "Data Saved: " + msg );
});
}
var invoiceJson = {name: "abc"};
$.ajax({
url: url,
type: "POST",
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(invoicejson),
success: (data) => {
try {
console.log( data);
} catch (err) {
console.log( err);
}
}
})
Related
I've been having a problem all day sending json data via ajax to Express.
My ajax looks like this:
$('#saveClause').click(function () {
var username = document.getElementById('postUserName').innerHTML;
var clauseTitle = document.getElementById('modalTitle').innerHTML;
var clauseDescription = document.getElementById('modalDescription').innerHTML;
var clauseText = document.getElementById('modalText').innerHTML;
$.ajax({
url: "/classes/updateAssignment",
type: "post",
dataType: "json",
data: {
username: username,
title: clauseTitle,
description: clauseDescription,
text: clauseText
},
cache: false,
contentType: "application/json",
complete: function () {
console.log("complete");
},
success: function () {
console.log("success");
},
error: function () {
console.log("Process Error");
}
});
});
and my Express Classes routes looks like this:
router.post('/updateAssignment', function (req, res) {
console.log(req.body.username)
console.log(req.body.title);
console.log(req.body.description);
console.log(req.body.text);
res.type('json');
res.send({
some: JSON.stringify({
response: 'json'
})
});
});
I issued a postman post request to the url with this JSON object:
{
"username":"testing",
"title":"123",
"description":"j456",
"text":"seven"
}
and Express logged all the details in the console just fine, so it must be a problem with my ajax request as it's giving me an unexpected token u error but I don't know what's causing it. Any ideas?
Try removing the contentType: "application/json",
If you used postman with no headers, most likely this is causing the parser to fail.
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
});
});
}
I am using ajax to get JSON from an API, however I am having a problem, retrieving the data. The code for ajax function is fine as I am using it elsewhere. I believe that the issue is with the .done(function().
$.ajax({
url: "http://127.0.0.1:4001/Barratt/getData.php",
//dataType: 'json',
//method: 'GET',
//contentType: 'application/json'
data: {url: developmentURL},
method: 'POST'
})
.done(function(data) {
//var developments = [];
$.each(data, function() {
$.each(this, function(i, obj) {
console.log(i, obj.Name + ' = ' + obj.ItemKey);
//developments.push();
});
});
})
.fail(function() {
alert('Failed to fetch data')
});
This is the code I am using, which just logs loads of 0 "undefined=undefined". However I have the .done(function() working in a jsfiddle, with the JSON hard coded. So I'm not sure where the problem lies.
Here is the fiddle
The data is of string type. Parse the string into JSON before looping:
data = JSON.parse(data);
$.each(data, function() {
If you want to avoid using JSON.parse you can Set the dataType to just 'json' and you will automatically recieve a parsed json response:
$.ajax({
url: "http://127.0.0.1:4001/Barratt/getData.php",
dataType: 'json', //Uncomment this line
//method: 'GET',
//contentType: 'application/json'
data: {
url: developmentURL
},
method: 'POST'
})
Or you can also make use of jquery $.getJSON api.
I assume the data that you retrive is an array of Json according to your code.
You forgot add key and value in the $.each callback function to loop into each Json value.
$.ajax({
url: "http://127.0.0.1:4001/Barratt/getData.php",
//dataType: 'json',
//method: 'GET',
//contentType: 'application/json'
data: {url: developmentURL},
method: 'POST'
})
.done(function(data) {
//var developments = [];
$.each(data, function(key,value) {
$.each(value, function(subKey, subValue) {
console.log(subKey, subValue.Name + ' = ' + subValue.ItemKey);
//developments.push();
});
});
})
.fail(function() {
alert('Failed to fetch data')
});
I'm trying to post JSON data along with 2 ids through a Jquery AJAX post. But I am not able to do it.
Following is my code:
try {
var surveyID= localStorage.getItem("surveyId");
var userDetails = jQuery.parseJSON(localStorage.getItem("userdetails"));
var providerKey = userDetails["ProviderUserKey"];
var dataValue = { "str": StringJson};
var url = APP_URL+"EditSurvey?";
var param = "SurveyId="+surveyID+"&JSONData="+JSON.stringify(dataValue)+"&UserId="+providerKey;
$.ajax({
type: "POST",
contentType: "application/json",
url: url,
data: param,
async:true,
success: function (data) {
alert('sucess');
//}
},
error: function (err) {
alert("Err : " + err.error);
},
});
} catch (error) {
alert(error);
}
I get the following error when I debug this in Safari:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
and in simulator I get the following error:
Where am I getting wrong? How do I solve this? I have to 3 parameters for post
surveyID
JSON data
userID
Edited:
The webservice is now changed and all 3 params- i.e. 2 ids and one whole json data is passed to the webservice. Still jquery ajax post is not working. See my code below:
var surveyID= localStorage.getItem("surveyId");
var userDetails = jQuery.parseJSON(localStorage.getItem("userdetails"));
var providerKey = userDetails["ProviderUserKey"];
var dataValue = {"surveyID":surveyID, "userID":providerKey, "str": StringJson};
alert(dataValue);
var url = APP_URL+"EditSurvey";
var param = dataValue;
$.ajax({
type: 'POST',
contentType: "application/json",
url: url,
data: dataValue,
success: function (data) {
alert('sucess');
//}
},
error: function (err) {
alert("Err : " + err.text);
},
});
edited to include stringJson:
var StringJson = JSON.stringify(MainJSON);
alert(StringJson);
Check if the final json which is being passed is in the exact format as expected by the server.
Try giving:
contentType: 'application/json',
Accept: 'application/json'
See if it helps.
try this one
formData = {
// all your parameters here
param1: param1,
JSONData: formToJSON(),
UserId: providerKey
}
$.ajax({
type: 'POST',
contentType: 'application/json',
url: url,
dataType: "json",
data: formData,
success: function(data) {
//success handling
},
error: function(data) {
alert("Err : " + err.error);
}
});
function formToJSON() {
return JSON.stringify({
dataValue: dataValue
});
}
In ajax return, i am getting json as
[{"colourname":"red,yellow"}]
i want to fetch "red,yellow" string from json ,
ajax call se ,
$.ajax({
type: "POST",
url: "loadData.php",
data: {
productid: 'getId'
}
}).done(function (msg) {
alert('get ' + msg);
});
I tried ,
msg[0].colourname
msg["colourname"]
Nothing worked how can i access values?
The response returned by $.ajax in done is a raw string, not a JavaScript object. Set dataType: 'json' in the ajax configuration and jQuery will parse the JSON msg as a JavaScript object.
$.ajax({
type : "POST",
url : "loadData.php",
data : {
productid : 'getId'
},
dataType: 'json',
}).done(function(msg) {
alert('get '+msg);
});
Setting the dataType explicitly is not required if you send the server response with Content-Type: application/json
BTW, you should use an array for colourNames: {"colournames":["red","yellow"] }
try this
$.ajax({
type: "POST",
url: "loadData.php",
dataType: 'json'
data: {
productid: 'getId'
}
}).done(function (msg) {
alert('get ' + msg);
});
});