Im trying to send an array to my Node/MongoDB server via and AJAX POST request. The body also contains other variables. Here is the client side JS code:
function setupForm(){
$("#add").submit(function(event) {
event.preventDefault();
var name = $("#name").val();
var logo = $("#logo").val();
var phone = $("#phone").val();
var email = $("#email").val();
var address = $("#address").val();
var postcode = $("#postcode").val();
var openingHours = $("#openingHours").val();
var loc = [44, 44];
$.ajax({
type: "POST",
url: "http://localhost:3000/services",
data: "name=" + name + "&logo=" + logo + "&phone=" + phone + "&email=" + email + "&address=" + address + "&postcode="+ postcode +"&openingHours=" + openingHours + "&loc=" + loc,
success: function(){alert('success');}
});
});
}
And here is the the server side code:
exports.addWine = function(req, res) {
var wine = req.body;
console.log('Adding wine: ' + JSON.stringify(wine));
db.collection('services', function(err, collection) {
collection.insert(wine, {safe:true}, function(err, result) {
if (err) {
res.send({'error':'An error has occurred'});
} else {
console.log('Success: ' + JSON.stringify(result[0]));
res.send(result[0]);
}
});
});
}
It adds it to the database but in this format. I would like it in an array:
"postcode" : "ugh",
"openingHours" : "fhgfh",
"loc" : "44,44"
As mentioned, use serializeArray(). To add your extra parameter, just append it to the array as shown below.
function setupForm(){
$("#add").submit(function(event) {
event.preventDefault();
var data = $(this).serializeArray();
// add extra parameters (don't forget brackets)
data.push({ name: 'loc[]', value: 44 });
data.push({ name: 'loc[]', value: 44 });
$.ajax({
type: "POST",
url: "http://localhost:3000/services",
data: data,
success: function() {
alert('success');
}
});
});
}
If you want to continue using your method of just building the query string, you would have to add &loc[]=44&loc[]=44 but it is better in the long run to just use one of the serialize functions.
Given the data you are using, I would advise sending the data in the POST requests' body. This will retain the datatypes (array, bools, etcs) thanks to JSON.
$.post("http://localhost:3000/services", {
name: $("#name").val(),
loc: [44, 44]
...etc
}, function(){alert('success');}
);
Backend should work fine without alterations. You might need to add body-parser to your middleware stack. The body-parser middleware will transform the body into a javascript object that you can push right into your database.
Take a look at jQuery's .serialize() and .serializeArray(). They should be able to do what you're looking for.
Related
I'm using this Javascript to send x, y values to Java from front-end (Javascript).
Sometimes this code pass the x any y values to Java and sometimes it's doesn't.After pressing the 'save' button, the function saveObjectMovingPath() will be called.
I don't know why it doesn't work sometimes! Can anyone help me to solve this issue?
<script type="text/javascript">
function saveObjectMovingPath() {
var building_Id = $("#building").val();
var floor_Id = $("#floor_level").val();
console.log('building_Id :' + building_Id + ', floor_Id : ' + floor_Id);
var json = {};
json["building_Id"] = building_Id;
json["floor_Id"] = floor_Id;
json["dataset"] = dataset;
$.ajax({
type: "post",
url: "savepath?pathConfig=" + unescape(JSON.stringify(json)),
success: function(data) {
alert("response data : " + data);
var response = JSON.parse(data);
}
});
}
</script>
This is sample data passing on URL:
"http://localhost:8080/Track/savepath?pathConfig={%22building_Id%22:%223%22,%22floor_Id%22:%2224%22,%22dataset%22:[{%22x%22:785.260498046875,%22y%22:624.4688720703125},{%22x%22:783.3544921875,%22y%22:624.4688720703125},{%22x%22:781.4485473632812,%22y%22:624.4688720703125},{%22x%22:779.5425415039062,%22y%22:624.4688720703125},{%22x%22:777.6365966796875,%22y%22:624.4688720703125},{%22x%22:775.7306518554688,%22y%22:624.4688720703125},{%22x%22:773.8246459960938,%22y%22:624.4688720703125},{%22x%22:770.9656982421875,%22y%22:624.4688720703125},{%22x%22:769.0596923828125,%22y%22:624.4688720703125},{%22x%22:767.1537475585938,%22y%22:624.4688720703125},{%22x%22:764.2947998046875,%22y%22:624.4688720703125},{%22x%22:763.341796875,%22y%22:624.4688720703125},{%22x%22:762.3887939453125,%22y%22:623.5159301757812},{%22x%22:760.4828491210938,%22y%22:623.5159301757812},{%22x%22:759.5298461914062,%22y%22:623.5159301757812},{%22x%22:757.6239013671875,%22y%22:623.5159301757812},{%22x%22:756.6708984375,%22y%22:623.5159301757812},{%22x%22:755.7178955078125,%22y%22:623.5159301757812},{%22x%22:754.7649536132812,%22y%22:623.5159301757812},{%22x%22:752.8589477539062,%22y%22:623.5159301757812},{%22x%22:751.9059448242188,%22y%22:623.5159301757812},{%22x%22:750.9530029296875,%22y%22:623.5159301757812},{%22x%22:749.0469970703125,%22y%22:623.5159301757812},{%22x%22:748.0940551757812,%22y%22:623.5159301757812},{%22x%22:747.1410522460938,%22y%22:624.4688720703125},{%22x%22:745.2350463867188,%22y%22:624.4688720703125},{%22x%22:744.2821044921875,%22y%22:625.421875},{%22x%22:743.3291015625,%22y%22:625.421875},{%22x%22:741.423095703125,%22y%22:625.421875},{%22x%22:740.4701538085938,%22y%22:626.3748779296875},{%22x%22:739.5171508789062,%22y%22:626.3748779296875},{%22x%22:738.5641479492188,%22y%22:626.3748779296875},{%22x%22:737.6112060546875,%22y%22:627.327880859375},{%22x%22:736.658203125,%22y%22:627.327880859375},{%22x%22:735.7052001953125,%22y%22:627.327880859375},{%22x%22:734.752197265625,%22y%22:627.327880859375},{%22x%22:733.7992553710938,%22y%22:628.2808227539062},{%22x%22:732.8462524414062,%22y%22:628.2808227539062}]}"
you try to send GET parameters on POST method
first you need to call the error function in your AJAX declaration and console.log it , if there is no error and the problem not resolved please check your java side (server side , maybe you try to save something need to parse ... )
second : make ajax statement look like this :
$.ajax({
type: "post",
data : {
building_Id : $("#building").val(),
floor_Id : $("#floor_level").val()
dataset: dataset;
}
url: "savepath?pathConfig=" + unescape(JSON.stringify(json)),....
....
instead of this :
var json = {};
json["building_Id"] = building_Id;
json["floor_Id"] = floor_Id;
json["dataset"] = dataset;
I'm retrieving an a list of sites, groups, and users. I'm concatenating and placing them in their respective variable, sending them in a query string to an aspx file.
var url = (Page._BASE_URL + 'Mo/Un/Unis/Unifie.aspx?' + getUserSecurityParameter() +
'&action=sending&userIds=' + encodeURI(userIds) +
'&siteName=' + encodeURI(site) +
'&groupName=' + encodeURI(groupName) +
'&siteList=' + encodeURI(siteList) +
'&team=' + encodeURI(team) +
'&users=' + encodeURI(users)+
'&site=' + encodeURI(site));
Ii'm using this code to retrieve those values on from the ajax post. I notice when I notice check the aspx source, There's so much data between the groups and sites that the users variable and data is never present.
var siteName = $.getUrlVar('siteName');
var groupName = $.getUrlVar('groupName');
var users= $.getUrlVar('users');
Is there a better way to do this so I won't have this issue? Because of missing users data it throws of a query that is written on the back end. Thanks in advance.
This is what I have now. When I try to send the data over I get an error. I can't see the what the error is unfortunately.
var requestParameters =
{
siteList: siteList,
team: team,
users: users,
siteName: site,
site: site,
group: group,
userId: userId,
securityCode: getUserSecurityParameter()
};
$.ajax({
url: Im._B + 'Mo/Uni/Unif/Ui.aspx/getValues',
type: "POST",
data: JSON.stringify(requestParameters),
contentType: "application/json; charset=UTF-8",
done: function (requestParameters, textStatus, jqXHR) {
var left = Math.floor((screen.width - 545) / 2);
windowManager.openFixed(url, 'DocumentListWindow', left, /* top: */ 10, /* width: */ 1480, /* height: */ 840);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('An error occurred trying to send the data.');
}
});
Ui.aspx.cs
[System.Web.Services.WebMethod]
public static string getValues(string requestParameters)
{
string mystuff = requestParameters;
return mystuff;
}
ERROR
"{\"Message\":\"Operation is not valid due to the current state of the object.\",\"StackTrace\":\"
Although there is technically no limit to the length of a query string, individual browsers do have limits. Follow Alex's advice and convert this to a post.
OK so I'm working on a Facebook Group Feed that loads more results, but I'm having trouble building the initial query for it all to work.
In the first if statement below, you can see where I put the parts of the query into variables and then call the function, passing those variables. This all works fine...
if (response.status === 'connected') {
// Logged into your app and Facebook.
console.log('Welcome! Fetching your information.... ');
var path = '/',
method = 'POST',
params = {
batch: [
{method : 'GET', name : 'user', relative_url : '/me?fields=id,name,picture'},
{method: 'GET', name : 'post-ids', relative_url: '/group-id/feed?fields=fields{with field expansion}',omit_response_on_success : false}
]
};
loadFeed(path, method, params);
}
The funciton below is where I'm having trouble. The first time the function is called, I need to put those three variables together into one, and call it with FB.api. You can see the function here:
function loadFeed(path, method, params) {
console.log('------------------');
console.log(path + ', ' + method + ', ' + params);
if(path != 'undefined') {
if(method != 'undefined') {
if(params != 'undefined') { var query = '{\'' + path + '\', \'' + method + '\', ' + params + '}'; }
}
else { var query = path; }
}
$('#load-more').css('display', 'hidden');
FB.api(query, function (response) {
console.log(response);
// first time page loads, response[0] is the login, and response[1] is the feed
// each time after that, response[0] is the feed
if(response.length > 1) {
var membody = JSON.parse(response[0].body),
feed = JSON.parse(response[1].body);
} else {
var feed = JSON.parse(response);
}
if(feed.paging) {
if(feed.paging.next) {
var load_more = '<div id="load-more"><center>Load more</center></div>',
method = '',
params = '';
$('#feed').append(load_more);
$('#load-more').click( function() {
loadFeed(feed.paging.next);
});
}
}
});
}
On the first call of this function, I get this error:
error: Object
code: 2500
message: "Unknown path components: /', 'POST', [object Object]}"
type: "OAuthException"
This seems to tell me that I've basically put the query together wrong, but I've tried a few different things and none of it is working. You can see in the error message that there's a missing single quote at the beginning of the query, and I've not been able to figure out how to keep the single quote there.
Does anyone have any ideas on how I can fix this problem?
Also, if you know a better way to do all this then I'd appreciate that as well!
It seems you are building your Javascript API call with HTTP API parameters.
To query JS API for user:
FB.api(
"/me", // or "/99999999999" the user's id
function(response) {
if (response && !response.error) {
/* handle the result */
}
);
Source: https://developers.facebook.com/docs/graph-api/reference/v2.2/user
To query JS API for group:
FB.api(
"/{group-id}",
function(response) {
if (response && !response.error) {
/* handle the result */
}
}
);
Source: https://developers.facebook.com/docs/graph-api/reference/v2.2/group
I have an js function that is collecting data and sending it to a php file.
I am trying to submit an array as part of the post:
function send_registration_data(){
var string = "{username : " + $('#username').val() + ", password : " + $('#pass1').val() + ", level : " + $("#userrole").val() + ", 'property[]' : [";
var c = 0;
$('input[name=property]:checked').each(function(){
if( c == 0){
string +="\"" +this.value+"\"";
c=1;
} else {
string +=",\""+this.value+"\"";
}
});
string+="]}";
$('#input').html( JSON.stringify(eval("(" + string + ")")) );
$.ajax({ url: './php/submit_registration.php',
//data: { username : $('#username').val() , password : $('#pass1').val() , email : $('#email').val() , level : $("#userrole").val() },
data: JSON.stringify(eval("(" + string + ")")) ,
type: 'post',
success: function(output) {
$('#output').html( output );
}
});
};
On submit my php file returns an the POST array as NULL. I am not sure what I am doing wrong here.
EDIT: IT is the same weather I try to convert the string to json or not.
ALso, the inputs contain just text names.
string keyword
Do not use the "string" keyword.
eval
Eval is evil - use it with caution.
strict mode
Make sure always to work in the "strict mode" by placing this line at the beginning of your code:
'use strict'
Building your response object
You do not have to glue your post object manually. Just do it this way:
var post = {
'username': $('#username').val(),
'password': $('#password').val(),
'myArray[]': ['item1', 'item2', 'item3']
};
jQuery the right way
Avoid messing up with unnecessary syntax.
$.post(url, post)
.done(function(response){
// your callback
});
Conclusion
'use strict'
var url = './php/submit_registration.php'; // try to use an absolute url
var properties = {};
$('input[name="property"]:checked').each(function() {
properties.push(this.value);
});
var data = {
'username': $('#username').val(),
'password': $('#pass1').val(),
'level': $('#userrole').val(),
'property[]': properties
};
// submitting this way
$.post(url, data)
.done(function(response) {
// continue
})
.fail(function(response) {
// handle error
});
// or this way
$.ajax({
type: 'POST',
url: url,
data: JSON.stringify(data), // you'll have to change "property[]" to "property"
contentType: "application/json",
dataType: 'json',
success: function(response) {
// continue
}
});
You need to get from php://input if you are not using multipart/form-data, so, application/json
$myData = file_get_contents('php://input');
$decoded = json_decode($myData);
If you're sending this up as json, your $_POST variable will continue to be NULL unless you do this.
am trying to update database.
For that iam doing like this
From js code
var data = {
"jobid": $('#jobid').val(),
"names": $('#names').val(),
"scripttype": $('#testscripts').val()
};
var msg="";
for(i = 1; i <=4; i++) {
data["Param" + i + "Key"] = $('#key' + i).val();
data["Param" + i + "Value"] = $('#value' + i).val();
}
$.ajax({
type: 'post',
url: "/save",
dataType: "json",
data: data
});
in node.js side
jobsCollection.update({
_id: id
}, {
$set: {
names: record.names,
script: record.scripttype,
// i dont know what should i place in this part???
// i have to set paramkey and paramValues
}
},
{
upsert: true
},
function (err, result) {
if (!err) return context.sendJson([], 404);
});
in record.names and record.scripttype getting proper values.
I don't know how to set values got from the for loop for updating
request going
Request: /save
{ jobid: '',
names: 'first',
scripttype: 'fow',
Param1Key: '1',
Param1Value: 'oneeeeee',
Param2Key: '2',
Param2Value: 'twoooooooo'
etc........
............
}
Since the property names are dynamic, you'll need to use the indexer-style property accessor of JavaScript as shown below.
Just reverse the process basically. I'm not sure where the data is located at the point you're calling update, so I called it sourceData in the example below;
// create an object with the well known-property names
var set = {
names : record.names,
script : record.scripttype
};
// now loop through the params and set each one individually
for(i = 1; i <=4; i++) {
var key = "Param" + i + "Key"; // build a key string
set[key] = sourceData[key]; // grab the data and set it
key = "Param" + i + "Value"; // and repeat
set[key] = sourceData[key];
}
then, pass it to your update:
jobsCollection.update({
_id: id
}, {
$set: set // pass the object created above
}, /* etc. */
If you don't know the count of Params, you could:
send it
use instead for .. in to loop through all the properties
For #2:
for(var key in sourceData) {
// you could filter the property names here if you'd like
// (like if only Params# were important)
set[key] = sourceData[key];
}