trying to invoke a backend php script which reads and writes to a mysql database and would like to define which field (aka column) I want to read or write from/to dynamically.
everything gets thru except the dynamic parameter name which I pass in as field to the javascript function.
if I hardcode field to 'mapstring' (which matches the column name in the mysql database), then it works. But writeabdata.php is written to write to any field name depending on what is passed into it.
What do I have to do to the field string parameter passed into writeabdata() so that it is passed correctly in the data portion of the .ajax call?
function writeabdata(table, id, field, mapstring) {
//alert ("table = "+table+" id = "+id+" field = \'"+field+"\' value = "+value);
$.ajax({
type: 'GET',
url: 'writeabdata.php',
data: {
'table': table,
'id': id,
field: mapstring
},
success: function (data) {
alert ("data Saved "+ data);
}
});
}
Generally when writing you'll want to use the "POST" type rather than the "GET" type. POST is for POSTING data to the data store, and GET is for RETRIEVING it. Without some more code, though, its hard to debug this, so I'm going to take a couple of shots in the dark.
First off, clean up the code a bit and unify your format - put "field" in quotes like your other items. While this may not solve your problem, the JSON standard is actually defined as using DOUBLE QUOTES only.
Second off, if we could see the PHP code, that would help - my guess is that there's something wrong with how the response is interpreted. I suggest that for debug purposes you get Fiddler running and inspect the actual request to make sure that you're sending all required fields to the server.
Once you update us with more info, I can update my answer - but I'd start by switching to POST.
Update
I think I misunderstood the question -- if you're looking to get data.field to really be data.somefield as in the name of that property could change to whatever you want, that's quite simple:
data[field] = mapstring
In other words:
function writeabdata(table, id, field, mapstring) {
//alert ("table = "+table+" id = "+id+" field = \'"+field+"\' value = "+value);
var dataObj = {
'table': table,
'id': id
};
dataObj[field] = mapstring;
$.ajax({
type: 'GET',
url: 'writeabdata.php',
data: dataObj,
success: function (data) {
alert ("data Saved "+ data);
}
});
}
Contrary to some of the comments you got, you can, as you see above, dynamically set property names using the array accessor on an object. And it works swimmingly. Build out your statically named data object properties, and then add the other ones via the array accessor.
You cannot set the field of an object literal (when you use {} directly in your code) using a variable.
For example:
var field = "b";
var myObject = {
"a": "A",
field: "B",
};
That object will look like this:
{
a: "A",
field: "B",
}
The reason this does not work is because fields are always considered to be strings. The fact that you do not need to put quotes around the field names is just language sugar, there to make it look better.
In order to create an object with a custom field you have to use the [] brackets, like this:
var field = "b";
var myObject = {
"a": "A",
};
myObject[field] = "B";
Which will then work as intended:
{
a: "A",
b: "B",
}
Here in your function you are taking 4 arguments- table, id, field, mapstring.. and then making the field:mapstring..
i.e you want the field value to be equal to mapstring than submit.. Why you want to take two arguments in a function to assign one's value to another... May be you just want field as 1 of the field of table.. So take 3 arguments- table, id, field..and assign the value of field similarly you assigned the values of table and id and see if it works...
Also replace GET with POST
Related
I want to update all the fields in a MongoDB document and I have a Javascript object that contains all these fields. I could easily type out each field to update but this seems like a lot of manual work and not reusable. I wanted to do something like below but this creates an object containing all the new field data within the document called newData.
I've tried JSON.stringify on the variable but the format isn't appropriate for update.
var newData = {
_id:ObjectId("53245234..."),
id: 88888,
firstData: "someData",
secondData: 787855,
thirdData: [ 45,17,12,234]
};
var collection = db.get('CollectionToUpdate');
//strip out dB id so as not to overwrite it, possibly not needed
if ("_id" in newData) {
delete newData["_id"];
}
//find the correct document based on program generated id and update
collection.update({id: newData.id}, {
newData
})
If you trust newData will not have any keys you don't intend (like update operators) this should work:
var collection = db.get('CollectionToUpdate');
collection.update({id: newData.id}, newData)
Note that this replaces the document. I assume that is what you meant by "update all the fields". update does not replace "_id".
Documentation for update
I'm trying to find the most efficient and generic solution for my single page app. There is 5 different tabs. Each tab is loading data in JSON object. Once user clicks on the tab JSON data is populated in the object with unique key. If user clicks on the Edit button I'm looping through JSON data and populating form fields. Here is my problem I have checkbox, radio, text and drop down menu fields on my form. Each data type requires different data type. My data in JSON object is not converted for checkbox or radio type input fields. I'm wondering what is the best way to approach this problem?
Here is example of my JSON data:
var jsonData = {
"frmTab1":{"st_fname":"mike","st_lname":"cook","st_iseligible":"yes"},
"frmTab2":{"sa_condition":"yes","sa_evaluation":"no"},
"frmTab3":{"se_respons":"yes","se_option":"3"},
... and so on
}
Here is my JQuery function that populates the form:
$('input[name="hmButton"]').on('click', function formSubmit(){
var btnVal = $(this).val();
if(btnVal == 'Edit'){
var jsonKey = $(this).attr('data-json'); //In data json is from id value
if($.isEmptyObject(jsonData[jsonKey])){
console.log('no data');
}else{
$.each(jsonData[jsonKey], function(index, element) {
//Here I need to check the input type and set checked if type is checkbox, or value if it's radio type, and same thing for drop down.
$('#frm' + index).val(element);
});
}
}
});
I was wondering if this could be done with another JSON object that will have key for each field with input type that is not equal text. If anyone can help please let me know. I'm trying to make this dynamic. This might be use in some other situation in my app. Thank you.
This...
var jsonData = {
'frmTab1': {
'st_fname': 'mike',
'st_lname': 'cook',
'st_iseligible': 'yes'
},
'frmTab2': {
'sa_condition': 'yes',
'sa_evaluation': 'no'
},
'frmTab3': {
'se_respons': 'yes',
'se_option': '3'
}
}
... is a JavaScript Object. JSON is a text-based data-interchange format, and although it's written in JavaScript Object Notation (hence JSON) try to avoid confusing JavaScript Objects with JSON data. Now that's out of the way... :)
Although JSON keys have to be defined between quotes ("...") as long as the keys in a JavaScript Object obey the usual syntax requirements the quotes for keys can be dispensed with...
var jsonData = {
frmTab1: {
st_fname: 'mike',
st_lname: 'cook',
st_iseligible: 'yes'
},
frmTab2: {
sa_condition: 'yes',
sa_evaluation: 'no'
},
frmTab3: {
se_respons: 'yes',
se_option: '3'
}
};
Your suggestion of referencing another Object which acts as an intermediary between the function which populates your page and the information in the jsonData variable is workable - perhaps something like this...
var dataMap = {
waypoint_1: jsonData.frmTab1,
waypoint_2: jsonData.frmTab2,
waypoint_3: jsonData.frmTab3
/* ... etc ... */
};
What I have called 'waypoint_n' here would reflect the properties/strings you're expecting to retrieve from your page element attributes - so that Something like...
var dKey = /* attribute value or property (String) */
var data = dataMap[ dKey ];
...would then place the required information from the jsonData Object in the data variable.
However, as you already have this information in an Object (jsonData) why not simply amend its keys to reflect the attribute values you're expecting?
You may find these links useful:
Eloquent JavaScript: The Secret Life of Objects
Eloquent JavaScript: Data Structures: Objects and Arrays
MDN: Working with JSON data
When using Parse, if I have an object called people and two columns, one called name and another called age. The user can input a name to match one that is already stored in Parse, and also input an age to be added to that specific name. How can I get it to search for the name the user has inputted, and if the name matches the user's input, add the age to that specific name?
You cannot save anything in an object unless you have access to its objectId, therefore you need to perform a search as well as a save. You need to find the object(s) associated with the name the user enters and then add age value and save it. The code becomes something like:
var query = new Parse.Query("people");
query.equalTo("name", inputName);
query.find().then( function(objects) { // query and search for object(s)
var person = objects[0]; // get the first object, there can be more than one obviously
person.set("age", inputAge); // set the age
return person.save(); // save the age value in object
}).then(function() {
// success
}, function(error) {
// error
});
I have two tables A & B, in table B I have a column of type pointer, each field points to a class in table A.
I need to know how to query table B based on the value of a particular field in the pointer column.
So for example, I have 4 objects (records) in table B, and in the pointer column I have pointer1, pointer2, pointer3 and pointer4. So if I want to carry out a query on table B and I want to extract the record with the field value of pointer3 how do I do this in javascript?
Based on your comment I would suggest storing both object IDs for each row. You could use Parse.when(recordA.save(), recordB.save()).then(...) to wait until both finished if you needed to provide feedback in the UI.
An alternative is to just store the object ID for the table B record and in the success handler you'll get back the updated record that'll include the pointer where you can then execute another save. This is slow as it will do two saves in sequence instead of kicking both off at once.
So after a long time searching and looking around and asking questions I figured it out myself in the end. I needed to pass in an object in the query.equalTo method like so:
query.find({
success: function(results) {
var detailsObject = results[0];
detailsObject.set("uuid", uuid);
detailsObject.set("proximity", prox);
detailsObject.set("campaignId", campaignId);
detailsObject.set("location", location);
detailsObject.set("sub_location", subLoc);
detailsObject.save(null, {
success: function(detailsObject) {
var content = Parse.Object.extend("Content");
var contentQuery = new Parse.Query(content);
var id = detailsObject.id;
contentQuery.equalTo("descId", detailsObject);
So "descId" is the pointer column in my content table and rather than trying to query the value in the field (object id of details object), I needed to pass the details object into the query.equalTo
I hope this is of benefit to someone else.
I have a map object containing a list of data about people. Every person's name is unique. The data fields of each person may not contain the same type of information (ie - Joey contains a date field, but Jill does not).
I am wondering if I can access a certain part of my map by using a variable name as part of the map path. Consider the following:
var data = {
'Joey': {
'id': '912',
'date': 'May 14 2012',
},
'Jill': {
'id': '231',
'login': 'JillM',
}
}
var name="Joey";
var joeyDate = data. + name + .date; //This does not work. Is there an alternative?
Use this syntax:
data[name]["date"]
This is an alternative to data.Joey, which should also work, but is static.
You can also use:
data[name].date
The difference is exactly what you're inquiring about - [] notation is better for dynamic retrieval and possibly invalid keys that wouldn't be allowed with Javascript if using dot notation. For example, if you had a key of "date-born", you can't use data[name].date-born, but you can use data[name]["date-born"].
An example of using this is:
for (name in data) {
console.log(data[name].date);
}
But of course, date must be a property (where it isn't for "Jill"), otherwise undefined will be returned.
An alternative way: mapName.get(keyName).propertyName
In your case: data.get(name).date