Fill gridview using javascript on selected tree node value - javascript

my requirement is to get the result in gridview based on the treeview node selection using javascript i.e. client scripting. Currently the same can be achieved using server side scripting, but i want to do this without postback and without using selectednodeindexchanged event. Pls. help me to solve this problem.

The solution is quite involved but goes something like this:
Use the Page.GetCallbackEventReference method to make an XmlHttpRequest back to the server and retrieve a json object that will be used to populated the grid.
See the System.Web.Script.Serialization namespace for pointers on how to convert your objects to JSON.
Create a JavaScript closure to encapsulate your grid update logic. Something like:
var vm = {
someField: 'test',
init: function() {
},
update: function(data) {
var grid = document.getElementById('yourGrid');
// loop through the data and set the innerHTML on the cells to whatever your data is.
}
}
setTimeout(function() {
vm.init();
}, 100);
// In the aspx/ascx
//when the callback completes convert the json to an object like this
var d = eval('(' + data + ')');
//call update on your object
vm.update(data)

Related

Javascript Associative Array cant post via php

Iam trying to post an Javascript Object via php, but i cant get the value in PHP, iam using laravel framework.
my array,
[type: "sadf", level: "sadfasdf"]
javascript code,
var data_push = Array();
$('form').on('change', 'select, textarea, input', function(t,s){
var key = $(this).attr('id');
var value = $(this).val();
data_push[key] = value;
});
$("#submit").click(function(){
$.post("{!! URL::to('test') !!}", {
_token : tempcsrf,
req_data : data_push
},
function (resp, textStatus, jqXHR) {
alert(resp);
});
});
php code,
public function workbook_save(Request $request_data)
{
$require_data = $request_data->req_data;
print_r($require_data);
}
Tried also JSON.stringfy(data_push) ,json_decode but no luck, i cant get the Javascript object in php, donno what iam doing wrong here, pls advice.
This is what your JS does:
Creates an array
Sets up an event handler to populate the array when things change in the form
Posts the (empty) array to the server
Later on, things will change in the form and data will be put in the array.
The server knows nothing about this because you already sent its contents.
You need to change your logic so you only make the POST request when you are ready to send the data.

backbone model fetch JSON element by ID

I am using backbone for the first time and I am really struggling to get it to function correctly with a JSON data file.
I have a model Like so:
window.Test = Backbone.Model.extend({
defaults: {
id: null,
name: null,
},
url: function() {
return 'json/test.json/this.id';
},
initialize: function(){
}
});
When a test item is clicked I then try to bring up the details of the pacific model that was clicked by doing
testDetails: function (id) {
var test = new Test();
test.id = id;
test.fetch({ success: function(data) { alert(JSON.stringify(data))}});
},
However this does not work, I am unable to correctly say "get the JSON element with the passed ID"
Can anyone please show me how to correctly structure the models URL to pull the element with the ID.
Thanks
The problem here is that you're treating your JSON data file like a call to a server. That won't work and it's the reason you're getting a 404. If you're accessing a file locally, you have to load the file first. You can do this with jQuery using the .getJSON() method, or if the file's static, just load it into memory with a script block (though you'll probably need to assign a var in the file). Most likely, you'll use jQuery. An example of this can be found here:
Using Jquery to get JSON objects from local file.
If this is an array of JSON, you can load the array into a collection, and use the "at" method to access the particular element by id. If it's entirely JSON, you'll have to create a custom parser.
your url is incorrect for one. you are returning the literal string 'this.id'. you probably want to do something more along the lines of
url: function () {
return 'json/test.json/' + this.id;
}
I would start by fixing your url function:
url: function() {
return 'json/test.json/' + this.get('id');
}
The way you have it now, every fetch request, regardless of the model's id, is going to /json/test.json/test.id

How to pass data from one HTML page to another HTML page using JQuery?

I have two HTML pages that work in a parent-child relationship in this way:
The first one has a button which does two things: First it requests data from the database via an AJAX call. Second it directs the user to the next page with the requested data, which will be handled by JavaScript to populate the second page.
I can already obtain the data via an ajax call and put it in a JSON array:
$.ajax({
type: "POST",
url: get_data_from_database_url,
async:false,
data: params,
success: function(json)
{
json_send_my_data(json);
}
});
function json_send_my_data(json)
{
//pass the json object to the other page and load it
}
I assume that on the second page, a "document ready" JavaScript function can easily handle the capture of the passed JSON object with all the data. The best way to test that it works is for me to use alert("My data: " + json.my_data.first_name); within the document ready function to see if the JSON object has been properly passed.
I simply don't know a trusted true way to do this. I have read the forums and I know the basics of using window.location.url to load the second page, but passing the data is another story altogether.
session cookie may solve your problem.
On the second page you can print directly within the cookies with Server-Script tag or site document.cookie
And in the following section converting Cookies in Json again
How about?
Warning: This will only work for single-page-templates, where each pseudo-page has it's own HTML document.
You can pass data between pages by using the $.mobile.changePage() function manually instead of letting jQuery Mobile call it for your links:
$(document).delegate('.ui-page', 'pageinit', function () {
$(this).find('a').bind('click', function () {
$.mobile.changePage(this.href, {
reloadPage : true,
type : 'post',
data : { myKey : 'myVal' }
});
return false;
});
});
Here is the documentation for this: http://jquerymobile.com/demos/1.1.1/docs/api/methods.html
You can simply store your data in a variable for the next page as well. This is possible because jQuery Mobile pages exist in the same DOM since they are brought into the DOM via AJAX. Here is an answer I posted about this not too long ago: jQuery Moblie: passing parameters and dynamically load the content of a page
Disclaimer: This is terrible, but here goes:
First, you will need this function (I coded this a while back). Details here: http://refactor.blog.com/2012/07/13/porting-javas-getparametermap-functionality-to-pure-javascript/
It converts request parameters to a json representation.
function getParameterMap () {
if (window.location.href.indexOf('?') === (-1)) {
return {};
}
var qparts = window.location.href.split('?')[1].split('&'),
qmap = {};
qparts.map(function (part) {
var kvPair = part.split('='),
key = decodeURIComponent(kvPair[0]),
value = kvPair[1];
//handle params that lack a value: e.g. &delayed=
qmap[key] = (!value) ? '' : decodeURIComponent(value);
});
return qmap;
}
Next, inside your success handler function:
success: function(json) {
//please really convert the server response to a json
//I don't see you instructing jQuery to do that yet!
//handleAs: 'json'
var qstring = '?';
for(key in json) {
qstring += '&' + key + '=' + json[key];
qstring = qstring.substr(1); //removing the first redundant &
}
var urlTarget = 'abc.html';
var urlTargetWithParams = urlTarget + qstring;
//will go to abc.html?key1=value1&key2=value2&key2=value2...
window.location.href = urlTargetWithParams;
}
On the next page, call getParameterMap.
var jsonRebuilt = getParameterMap();
//use jsonRebuilt
Hope this helps (some extra statements are there to make things very obvious). (And remember, this is most likely a wrong way of doing it, as people have pointed out).
Here is my post about communicating between two html pages, it is pure javascript and it uses cookies:
Javascript communication between browser tabs/windows
you could reuse the code there to send messages from one page to another.
The code uses polling to get the data, you could set the polling time for your needs.
You have two options I think.
1) Use cookies - But they have size limitations.
2) Use HTML5 web storage.
The next most secure, reliable and feasible way is to use server side code.

Backbone: Getting data from server into JQGrid

I have a Web Application that currently uses JQGrid but I'm trying to introduce Backbone.js to improve code organization. What I'm trying to do is get data from the server using a Collection, and then add the JSON information to my defined JQGrid but I can't get it to work. My JQGrid is defined like this:
var tareasHumanasTable = $("#grillaTH").jqGrid({
datatype: 'local',
height: 'auto',
colNames:[ colNames...],
colModel:[ colModel...]
}
And my Model and Collection are defined like this:
window.TareaHumana = Backbone.Model.extend();
window.TareaHumanaCollection = Backbone.Collection.extend({
model: TareaHumana,
url: "bandejaTareas/buscarTH"
});
I have a button that when clicked starts server communication. Now is doing this:
$(function(){
$("#botonBuscar").bind('click',function(){
var tareaHumanaList = new TareaHumanaCollection();
tareaHumanaList.fetch({data: $("#formBandejaTareas").serializeObject()});
//alert("tareaHumanaList.toJSON(): " + tareaHumanaList.toJSON());
tareaHumanaList.each(function(tareaHumana, i){
//alert("tareaHumana.toJSON(): " + tareaHumana.toJSON());
tareasHumanasTable.jqGrid('addRowData', (i + 1), tareaHumana.toJSON());
});
That code doesn't work at all. With Firebug I verified that the server sends the data in the correct format but the code isn't working. The weirdest thing is that when I uncomment the "alert(...)" lines everything starts to work.
The key is that fetch is asynchronous. So if you immediately call each after fetch it's probably your collection won't be populated. You should use success callback. For example take a look at this answer.
Try to use datatype:jsonstring and create a format function on the collection to provide corect data format to jqgrid.

How do I display values of an JSON object?

Here is what I got so far. Please read the comment in the code. It contains my questions.
var customer; //global variable
function getCustomerOption(ddId){
$.getJSON("http://localhost:8080/WebApps/DDListJASON?dd="+ddId, function(opts) {
$('>option', dd).remove(); // Remove all the previous option of the drop down
if(opts){
customer = jQuery.parseJSON(opts); //Attempt to parse the JSON Object.
}
});
}
function getFacilityOption(){
//How do I display the value of "customer" here. If I use alert(customer), I got null
}
Here is what my json object should look like: {"3":"Stanley Furniture","2":"Shaw","1":"First Quality"}. What I ultimately want is that, if I pass in key 3, I want to get Stanley Furniture back, and if I pass in Stanley Furniture, I got a 3 back. Since 3 is the customerId and Stanley Furniture is customerName in my database.
If the servlet already returns JSON (as the URL seem to suggest), you don't need to parse it in jQuery's $.getJSON() function, but just handle it as JSON. Get rid of that jQuery.parseJSON(). It would make things potentially more worse. The getFacilityOption() function should be used as callback function of $.getJSON() or you need to write its logic in the function(opts) (which is actually the current callback function).
A JSON string of
{"3":"Stanley Furniture","2":"Shaw","1":"First Quality"}
...would return "Stanley Furniture" when accessed as follows
var json = {"3":"Stanley Furniture","2":"Shaw","1":"First Quality"};
alert(json['3']);
// or
var key = '3';
alert(json[key]);
To learn more about JSON, I strongly recommend to go through this article. To learn more about $.getJSON, check its documentation.
getJSON will fire an asynchronous XHR request. Since it's asynchronous there is no telling when it will complete, and that's why you pass a callback to getJSON -- so that jQuery can let you know when it's done. So, the variable customer is only assigned once the request has completed, and not a moment before.
parseJSON returns a JavaScript object:
var parsed = jQuery.parseJSON('{"foo":"bar"}');
alert(parsed.foo); // => alerts "bar"
.. but, as BalusC has said, you don't need to parse anything since jQuery does that for you and then passes the resulting JS object to your callback function.
var customer; //global variable
function getCustomerOption(ddId){
$.getJSON("http://localhost:8080/WebApps/DDListJASON?dd="+ddId, function(opts) {
$('>option', dd).remove(); // Remove all the previous option of the drop down
if(opts){
customer = opts; //Attempt to parse the JSON Object.
}
});
}
function getFacilityOption(){
for(key in costumer)
{
alert(key + ':' + costumer[key]);
}
}

Categories

Resources