I will design a a sample. My project will take all json data and insert to my web sql database.Firstly I used ajax for take my data and tried parse it. When I parsed , I dont access my json fields.
var oModel = new sap.ui.model.json.JSONModel();
var aData = jQuery
.ajax({
url : "http://../DataSource?format=json&key....",
dataType : "json",
success : function(data, textStatus, jqXHR) {
var JsonData = data;
oModel.setData(JsonData);
},
error : function(jqXHR, textStatus, errorThrown) {
}
});
obj = JSON.parse(oModel);
var myTextField = obj.Name;// This is not working
console.log(myTextField);
Also ı tried this.
var model = new sap.ui.model.json.JSONModel();
model.loadData("http://.../DataSource?format=json&key=...");
obj = JSON.parse(model);
var myTextField = obj.Name;
console.log(myTextField);
This my database. I want insert all name and surname field.
function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS emre');
tx.executeSql('CREATE TABLE IF NOT EXISTS emre (id unique, data)');
tx.executeSql('INSERT INTO emre (id, data) VALUES (?,?)', [ name ,
surname ]);
}
You seem to try parsing the model, but that is not a JSON structure but a UI5 object which happen to contain the JSON structure.
But why would you parse the JSON in the first olace?? If your AJAX call finishes successfully, and stores the retrieved data in your model, you can simply access it from the model using
model.getProperty("/path/to/your/property");
Have a look at the model API in the docs, there it is all well explained
EDIT to get to the data after it is loaded, use the attachRequestCompleted event handler:
var model = new sap.ui.model.json.JSONModel();
model.attachRequestCompleted( function(){
console.log(model.getProperty("Name"));
});
model.loadData("http:.../DataSource?format=json&key=...);
Related
I am running parse server in NodeJS environment with express.
Generally, Parse automatically figures out which data has changed so only “dirty” fields will be sent to the Parse Cloud. So, I don’t need to worry about squashing data that I didn’t intend to update.
But why this following code is saving new data every time instead of updating the existing document data with name "Some Name".
// Parse code
Parse.initialize(keys.parseAppID);
Parse.serverURL = keys.parseServerURL;
var GameScore = Parse.Object.extend("GameScore");
var gameScore = new GameScore();
let data = {
playerName: "Some Name",
score: 2918,
cheatMode: true
};
gameScore.save(data, {
success: (gameScore) => {
// let q = new Parse.Query("GameScore");
// q.get(gameScore.id)
console.log("ID: " + gameScore.id)
},
error: function (gameScore, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and message.
alert('Failed to create new object, with error code: ' + error.message);
}
});
// End of Parse code
The problem is that you're executing the query to find which object you want to update, but then you're not using the results when you go to save data.
query.first({ // This will result in just one object returned
success: (result) => {
// Check to make sure a result exists
if (result) {
result.save(data, {
// Rest of code
Note: You're treating playerName as a unique key. If multiple users can have the same playerName attribute, then there will be bugs. You can use id instead which is guaranteed to be unique. If you use id instead, you can utilize Parse.Query.get
Edit:
Since you want to update an existing object, you must specify its id.
var GameScore = Parse.Object.extend("GameScore");
var gameScore = new GameScore();
gameScore.id = "ID"; // This id should be the id of the object you want to update
I just read that the mtype option in the jqGrid will determine how we will do the ajax call. GET will retrieve data and POST will send data.
When i load my jqGrid, i want to pass an extra parameter to my controller, in my js file:
url: 'Controller/Action1',
mtype: 'POST',
datatype: 'json',
postData: { ParentId: selectedParentId },
In my controller I have this:
public JsonResult Action1(ParentId)
{
// Retrieve child properties from db using ParentId
// Return json result
}
How will my jqGrid load the returned json data if my mtype is POST?
In my action, could i still get the other options of my jqGrid as a parameter like sort order, page size selected? Could i use something like this.Request.Param["sidx"] in my action?
In your controller you would take all the parameters the jqGrid would pass you:
public ActionResult GetGridData(string sidx, string sord, int page, int rows, bool _search, string filters, string ParentId)
{
....
int totalRecords = wholeList.Count();
var pagedQuery = wholeList.OrderBy(sidx + " " + sord).Skip((page - 1) * rows).Take(rows).ToList();
var jsonData = new
{
total = (totalRecords + rows - 1) / rows,
page = page,
records = totalRecords,
rows = (
from tempItem in pagedQuery
select new
{
cell = new string[] {
tempItem.ToString(),
...
}
}).ToArray()
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
You can use the extra parameter to change what you feed back to the jqGrid, and you will also see you are passing in and using the parameters to handle paging.
mtype option defines the type of the HTTP request:
if it's set to GET (by default): the request parameters are appended in the http query in the Addressbar like this .../Controller/Action1?ParentId=selectedParentId
if it's set to POST, the request parameters are hidden when sending http query
In fact, the two methods send the same parameters with diffrent ways. So there is any diffrent on loading returned JSON data with GET or POST method
Or course you can get the other options of your jqGrid as a parameter like sort order
Sorry for my bad english
When I create a new item in the server-side using a Kendo UI data source, how do I update the ID of the client-side data item with the ID of the new record inserted in the database in the server-side?
Doing more research I have found this extremely useful information which, indeed, should be in the docs, but it is "hidden" in a not-so-easy-to-find forum search message:
http://www.kendoui.com/forums/ui/grid/refresh-grid-after-datasource-sync.aspx#2124402
I am not sure if this is the best approach, but it resolved my problem!
This solution simply uses the data source read method to update the model instances with data from server.
The precious info is where it is done: in the "complete" event of the transport.create object!
Here is the code:
transport: {
read: {
url: "http://myurl.json"
},
create: {
url: "http://mycreate.json",
type: "POST",
complete: function(e) {
$("#grid").data("kendoGrid").dataSource.read();
}
},
To avoid the additional server call introduced by the read method, if you have your create method return an object the Data Source will automaticly insert it for you.
Knowing that all you need to do is set the id field from the database and return the model.
e.g. psudo code for ASP MVC action for create.
public JsonResult CreateNewRow(RowModel rowModel)
{
// rowModel.id will be defaulted to 0
// save row to server and get new id back
var newId = SaveRowToServer(rowModel);
// set new id to model
rowModel.id = newId;
return Json(rowModel);
}
I've had the same problem and think I may have found the answer. If in the schema you define the object that holds the results, you must return the result of the created link in that same object. Example:
schema: {
data: "Results",
total: "ResultsCount", ....
}
Example MVC method:
public JsonResult CreateNewRow(RowModel rowModel)
{
// rowModel.id will be defaulted to 0
// save row to server and get new id back
var newId = SaveRowToServer(rowModel);
// set new id to model
rowModel.id = newId;
return Json(new {Results = new[] {rowModel}});
}
Just to add to Jack's answer (I don't have the reputation to comment), if your Create and Update actions return data with the same schema as defined in the kendo DataSource, the DataSource will automatically update the Id field as well as any other fields that may have been modified by the action call. You don't have to do anything other that form your results correctly. I use this feature to calculate a bunch of stuff on the server side and present the client with the results w/o requiring a complete reload of the data.
I would like to overwrite the value of the "password" field before submiting a form on Jquery using AjaxSubmit function.
I know I can just update the value on the input field but, I don't want the user to see this transformation. In other words, I just want to send a custom value to the password field and keep the current value on the screen...
How could I do that?
My current code:
var loginoptions = {
success: mySuccessFuction,
dataType: 'json'
}
$('#My_login_form').submit(function(e) {
e.preventDefault();
var pass=$("#My_login_form_password").val();
if (pass.length>0){
loginoptions.data={
password: ($.sha1($("#My_login_form_csrf").val()+$.sha1(pass)))
}
$("#My_login_form").ajaxSubmit(loginoptions);
delete loginoptions.data;
});
The problem with this code is that it is sending a "password" POST variable with the form field value and, a duplicated one with the value I set on "loginoptions.data".
Building off of Cristiano's answer, I was able to get this to work. If you use :beforeSubmit(), the changed value doesn't post, but if you use the :beforeSerialize(), it posts the changed value.
$('#ff').ajaxForm({
beforeSerialize:function(jqForm, options){
var serializedForm = decodeURIComponent(jqForm.serialize());
options.data = serializedForm.deserializeToObject();
options.data.tPassword = MD5($("#tPassword").val())
},
success:function(data){
// do stuff
}
});
If you want to do it anyhow then I think you can use callback function beforeSubmit: function(contentArray, $form, options){}
beforeSubmit: function(contentArray, $form, options){
for(var i=0; i<contentArray.length; i++){
if(contentArray[i].name == "password") {
contentArray[i].value = ($.sha1($("#My_login_form_csrf").val()+$.sha1(pass)))
}
}
}
It seems that ajaxSubmit uses the serialize() function of jquery on the form and then, adds the extra data serialized too. So, if I have a field named "password" with the value "1234" and then try to change that to "abcd", using "loginoptions.data.password", it will serialize everything and put the "options.data" like this:
"password=1234&field_2=value_2&password=abcd"
After many tries, I gave up on using ajaxSubmit function and decided to use ajax function to submit the form:
var the_form=$('form#My_login_form');
loginoptions.url=the_form.attr("action");
loginoptions.type=the_form.attr("method");
var serializedForm=decodeURIComponent(the_form.serialize());
loginoptions.data=serializedForm.deserializeToObject();
var pass=$("#My_login_form_password").val();
if (pass.length>0){
loginoptions.data.password= ($.sha1($("#My_login_form_csrf").val()+$.sha1(pass)));
}
$.ajax(loginoptions);
Here is the deserializeToObject() function:
function deserializeToObject (){
var result = {};
this.replace(
new RegExp("([^?=&]+)(=([^&]*))?", "g"),
function($0, $1, $2, $3) { result[$1] = $3; }
)
return result;
}
String.prototype.deserializeToObject = deserializeToObject;
I am trying to access an object with form data sent to my controller. However, when I try to access objects I get values of null or 0. I used two methods, the first by serializing and the second by storing names and values in one object. (the code below sends/posts serialized)
Here is my JS...
$("#createUser").click(function() {
//store input values
var inputs = $('#newUserForm :input');
var input = $('#newUserForm :input').serializeArray();
console.log(input);
//if I want just the values in one object
var values = {};
$(inputs).each(function() {
values[this.name] = $(this).val();
});
console.log(values);
if(LiveValidation.massValidate( validObj )){
$.post('./adminPanel/createUser', function(input){
alert('Load was performed.');
//test confirmation box
$("#msgbox").html("Grrrrreat");
//drop down confirmation
$("#msgbox").slideDown();
});
} else {
//test fail box
$("#failbox").html("Fail");
$("#failbox").slideDown();
}
});
In the controller side I try to access data the following way...
$this->input->post("firstName")
where firstName is the name of the field.
Below is an image of the objects passed.
Top being serialized array and the bottom a single object with all the names and values of form...
If you're using jQuery, you can use jQuery's built in serialize/query string functions to get the data from a form: http://api.jquery.com/serialize/
In your case:
var data = $('#newUserForm').serialize(); // is a string like "firstName=jon"