AJAX modifying the DOM & calling a function - javascript

I am on Linux -both browser side & server side- with a recent Firefox 38 or 42 if that matters; this question gives more context, and the github GPLv3 project containing my code. It is not a usual Web application (it would have usually one, and perhaps a dozen, of simultaneous Web users). I am writing or generating both server & browser side code
Let's suppose I have some HTML5 code like
<div id="mydyndiv_id"></div>
I am making an AJAX request with JQuery. On success it should insert some (AJAX generated) HTML element, e.g. <b>bold</b> (in reality it is a much bigger HTML fragment with nested <span>-s whose content is dynamically generated from the POST argument of the AJAX request), into that div and call some other Javascript function doit, e.g. doit(42) only once just after the AJAX request (e.g. that function would clear some other <textarea> in my page, and the 42 argument is provided by the AJAX response). I can change code both on server side (e.g. alter the AJAX processing) and on browser side.
What is the most idiomatic way to achieve that?
making a JSON AJAX which contains both the inserted HTML & the function argument, so the AJAX response could be {"text":"<b>bold</b>", "data": 42}" of Content-type: "application/json" and the Javascript code would be
$.ajax
({url: "/someajax",
method: "POST",
data: {"somearg": "foo"},
datatype: "json",
success: function(jsa) {
$("#mydyndiv_id").html(jsa.text);
doit(jsa.data);
}});
this is rather heavy, the server should double-encode HTML&JSON the HTML fragment: it needs first to construct the <b>bold</b> fragment -with HTML encoding, and then to construct the JSON object and send it.
making an HTML AJAX which has some <script> element. The AJAX response would be of Content-type: text/html and would contain <b>bold</b><script>doit(42)</script>, and the Javascript code would be
$.ajax
({url: "/someajax",
method: "POST",
data: {"somearg": "foo"},
datatype: "html",
success: function(ht) {
$("#mydyndiv_id").html(ht);
}});
this might be wrong, since the doit(42) function could be perhaps called more than once and is kept in the DOM and I don't want that
making a Javascript AJAX; the AJAX response would be of Content-type: application-javascript and would contain:
$("#mydyndiv_id").html("<b>bold</b>");
doit(42);
with the AJAX invocation in Javascript being
$.ajax
({url: "/someajax",
method: "POST",
data: {"somearg": "foo"},
datatype: "script",
success: function(jscode) { /* empty body */ }
})
This is brittle w.r.t. errors in doit(42) (see this question; the only debugging technique I found is lots of console.log and that is painful) and also requires double encoding on server side.
Of course, any other technique is welcome!
PS. If you are curious, the code is commit a6f1dd7514e5 of the MELT monitor (alpha stage) and you would try the http://localhost.localdomain:8086/nanoedit.html URL in your browser; this software (which is also a specialized HTTP server!) would have only very few simultaneous Web users (usually one, perhaps a dozen); in that sense it is not a usual web application. In my dreams it could become a workbench for a small team of (C & C++) software developers, and the GUI of that workbench would be their browser.

These different approaches have pros and cons, but generally the first two options are more advisable, let's see:
JSON AJAX
First of all, working with templating on your server is the right approach. If you use this method you will be able to pass more flexible data from your server to your client as you can e.g. use {"text":"<b>bold</b>", "data": 42, "more_data": 43}".
You are not bound to use just the data at the moment you initially create the service but expand passed data easily.
HTML AJAX
This method is simple and if you would like to have a service for every single piece of data you need to pass, rather than a service for multiple pieces, this is the preferable choice. In difference to the JSON AJAX method, you will not be able to expand here and if needed, you'll naturally have to create a new service for passing new data.
Javascript AJAX
Altough it is possible, tis method is rather unadivsable, as you can not maintain your application in a reasonable way, as your templating is client-side. See what Peter-Paul Koch says here:
Although templating is the correct solution, doing it in the browser is fundamentally wrong. The cost of application maintenance should not be offloaded onto all their users’s browsers (we’re talking millions of hits per month here) — especially not the mobile ones. This job belongs on the server.
Further reading : Why client-side templating is wrong.

First approach looks good for me, but generally it's a little bit ugly to transfer raw HTML via AJAX, if you have to transfer raw HTML it's better to use techniques called PJAX, see jquery-pjax plugin for more information of how to use and customize it.
From my point of view best approach would start using jquery-template to avoid transferring HTML over AJAX and start transfer only object witch would be rendered to template on frontend.Call doit method within handling success is ok until it use data provided in response.

I would rather go with a variation of first approach. But, it depends on the kind of generated HTML that you are currently returning from the server-side.
If it is a simple element, then you could just return a JSON object from server with one of the properties identifying the element.
For example, the response from the web-service would be like:
{'elem': 'b', 'text': 'bold', 'value': '42'}
And you consume that in the AJAX call like this:
$.ajax({
datatype: "json",
...
success: function(response) {
// create the required element client-side
var elem = document.createElement(response.elem);
// use other properties of the response object
elem.textContent = response.text + doit(response.value);
// add the element to your div
$('#mydiv-1')[0].appendChild(elem);
}
});
Where doit is the Javascript function that is already part of your client-side code-base and you just use the arguments returned by the web-service.
Alternatively, if your generated HTML is a complex fragment, then you need to identify common patterns and use client-side templates to transform the returned data into presentation.
For example, your client-side template may look like this:
<script type='text/template' id='tmpl'>
<div><h3></h3><p></p><h5></h5></div>
</script>
Your web-service returns something like this:
{'title': 'title', 'text': 'paragraph', 'value': '42'}
And you consume that in the AJAX call like this:
$.ajax({
datatype: "json",
...
success: function(response) {
// clone the client-side template
var template = $('#tmpl').html(), $elem = $(template);
// append to your div
$('#mydiv-2').append($elem);
// populate the cloned template with returned object properties
$elem.find('h3').text(response.title);
$elem.find('p').text(response.text);
$elem.find('h5').text(doit(response.value));
}
});
This way you avoid returning generated HTML from your server and manage the presentation details at the client-side only. Your web-service needs not to know the presentational aspects and deals only with raw data (consuming or spewing). The client-side code gets data from the web-service and deals with using and/or presenting that data as part of the client-side app.
Demo for both the variations: https://jsfiddle.net/abhitalks/wuhnuv99/
Bottom-line: Don't transfer code. Transfer data. Code should then use that data.

Related

.Net: Passing values from JavaScript to C# without a Postback

I making a .Net web app using a third party gridview(DevExpress web form ASPxGridView).
Lets say I have two grids(Grid1 and Grid2, both devexpress).
I am running into an issue where I need to update values in Grid2 based on which column is clicked on Grid1(during the onClick event).
I am able to capture the row and column in JavaScript but am not able to pass it back to my serverside code.
The grid has some settings tied to the edit mode, that if the page does a full postback, the grid loses its edits.
I have tried setting a HiddenField and calling a postback, but that erases edits in my grid. I have tried passing the variables to a static method , but I cannot access the controls on my page to update Grid2. I have looked into trying to do a callback instead of a postback, but it looks like callbacks are referencing Client-Side methods.
Does any one know of a way to pass a client-side variable to c# without a postback, or to call a non-static c# method from JavaScript? Any suggestions would be greatly appreciated.
The most basic approach to do this would involve two parts, part 1) add an ajax js function on your your existing grid page to handle the click event and make the data request. Part 2) Code up a separate C# web page to receive your client-side Grid1-variable, process it accordingly, and then respond with the data for Grid2. Here's some pseudocode of what the ajax call might look like, hope it helps.
//in your javascript section
$("#Grid1Cell").click(function(){
$.ajax({
type: "GET",
url: '#Url.Action("GetGrid2Data", "SomeController")"?yourVar=' + encodeURI(yourVal),
//alternatively url: "yourNonMVCpage.aspx?yourVar=" + encodeURI(yourVal),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.SomeValues == "blah") {
$("#Grid2Cell").text(response.SomeValues); //update Grid2
}
}});
});
If you need to "connect c#", it is necessary to perform a request to the server (using any of the available techniques - callback, postback, etc.).
If you need to refresh another control (Grid2) rendering during this request, the corresponding HTML content should be returned as a results of this request.
According to the provided description, you need to implement "cascaded grids" - i.e., update a dependent grid when changing a main grid. If so, use the approach illustrated in the https://github.com/DevExpress-Examples/how-to-show-detail-information-in-a-separate-aspxgridview-e70 example and force the dependent grid custom callback (and further refreshing) via the client-side PerformCallback method + handle the server-side CustomCallback event.

Ajax call. Passing value to another php file

I have a problem and hope you can help.
Ii have a status.PHP file containing a js.
STATUS.PHP
<? ..stuff... ?>
<html>
<head>
<title>BCM Status Page</title>
<script src="jquery-3.3.1.min.js"></script>
<script src="updater.js"></script>
</head>
<body bgcolor="#305c57" onload='init();'>
As you can see in the html ihave included a JS, during "onload" i'm calling the init() function of the javascript called updater.js
Now in the UPDATER.JS
function init() {
setInterval(read, 2000)
}
function read() {
$.ajax({
type: 'POST',
url: 'readDB.php',
dataType: 'jsonp',
success: function (data) {
console.log(data);
var json_obj = $.parseJSON(data);
console.log(json_obj[0].gwnumber);
},
error: function () {
console.log("Error loading data");
}
});
}
I'm doing an ajax call to the readDB.php that is working as intended, infact i have the correct value in the json_obj.
My question is: how can i get the json_obj value and pass it to the status.PHP file that is the one who's including the JS too?
Hope you can help. TY
Ok, there is a lot to say in this argument, but i will be the briefiest possible.
first things first
php and Javascript are two different programming language with a completely different paradigm.
The first is a back-end focused programming language;
Javascript instead is more front-end focused, just for entirety i have to mention that JS is used also for the backend part with a special eviroment called Node.js
back to the problem, the things that you are trying to do is not impossible but is excactly as you asked, your're idea (if i got it) was to pass the data from the js to the php like a parameter in a function...
the thing is that the php is elaborate and renderizated before in the server and the javascript is executed in the client, in the client web page there is no more footprint the php. This process is described very well at this link: http://php.net/manual/en/intro-whatis.php
The possible solution is:
FRONT-END(js): make another ajax call(request) to the same page that you are displaying with all the data that you want to elaborate.
BACK-END(php): controll if this request has been made, then access the data with the global variables $_POST & $_GET (depending on the type of the request), then elaborate this data.
if I can I suggest you to make a check if the manipulation that you want to do on those data need to be done in the server-side and not by the js!
Consider the order of execution:
User visits status.php
Browser requests status.php
Server executes status.php and sends response to browser
JS requests readDB.php
Browser requests readDB.php
Server executes readDB.php and sends response to browser
JS processes response
Go To 4
By the time you get to 7, it is too late to influence what happens at step 2.
You could make a new Ajax request to status.php and process the response in JS, but since status.php returns an entire HTML document, that doesn't make sense.
You could use location to load a new page using a URL that includes status.php and a query string with information from the Ajax response, but that would making using Ajax in the first place pointless.
You should probably change readDB.php to return *all** the data you need, and then using DOM methods (or jQuery wrappers around them) to modify the page the user is already looking at.
The simpliest and fastest (maybe not the sexiest way) to do it :
create global variable var respondData; in STATUS.PHP
within you ajax request on success function assign your data callback to it
respondData = data;
Now you have an access to it from every place in your code even when the ajax request is done. Just bare in mind to ensure you will try to access this variable after the page will fully load and after ajax will process the request. Otherwise you will get 'undefined'

Programmatically view content of html element loaded from another file

I would like to get the contents of a file on the server into a string. What is the easiest way to do this? Right now I am trying:
<script type="text/template" src="partials/someTemplate.html"
id="someTemplate"></script>
<script>
console.log($('#someTemplate').html()); //nothing comes up
</script>
A hacky way to do this is:
$('<div>').appendTo(document.body)
.load('partials/someTemplate.html', function () {console.log(this.innerHTML);} );
and then get the innerHTML of that, but that's a waste of an HTML element. Any thoughts? I feel like this should be silly easy.
Just use $.get():
var html;
$.get('partials/someTemplate.html', function(res)
{
html = res;
});
You basically need to use an asynchronous server request (ajax) to get the content of a file and process it later.
This can be done in pure JavaScript using XMLHttpRequest but the most popular and easiest way to do this is using jQuery's $.ajax function.
$.ajax({
url: "partials/someTemplate.html"
}).done(function( content ) {
console.log( "Your returned content is " + content );
});
You can configure this ajax call in many ways as described in documentation, you can pass parameters to the file, cache the request or demand a specific content type to be returned if that is necessary, but given example would do just fine for what you are trying to accomplish.
Please note that there are many ways to do an ajax request in jQuery, like .load(), $.post(), $.get(), $.getScript() and $.getJSON() but those are all just shorthand methods for an Ajax request so if you use those you are basically using an $.ajax with some predefined parameters.
Also, make sure that you need to use JavaScript and an async request at all. Getting content of a file inside some other file is mostly often done using some server side processing language like PHP (require() and include()),.NET, Java etc., and while that seems obvious for some people I felt obligated to say that since you didn't provide enaugh information about why you need that content and what you want to do with it.

JSON external file vs defined in JS

What are some arguments as to when to use JSON external file such as with jQuery's
$.getJSON('external.json',function(data){});
(ajax retrieving) versus defining it in javascript with
var myJson = { "someVar": { "1": ["test1","test2"], "2": ["test3","test4"]} }
What is the "proper" way of doing it? Does it depend on JSON length or are there any other factors that can tell you what approach to use?
The way I see it: choose between loading another file which is supposed to be slow as you are loading data via ajax call or adding plenty of lines into already packed javascript file which is not a good thing either. Surely there must be some distinction as to where you should use one or another ... ?
I am not interested only in speed difference (getting file from ajax is of course slower) but also in other aspects such as what is generally used when and what should be used in some case ...
The first one is a shorthand for:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
This is an Ajax request which will take more time than having a simple JSON object into the file.
I would prefer the second one IF it's possible. Also if you attend to have good performances the first one is longer.
time( Loading+parsing 2 files ) >> time( Read a Javascript object )
If your data is known at page creation time you're probably best to use an object literal like:
var myJson = {...}
However, as Kursion mentions,
$.getJSON(...)
is a shorthand method for retrieving json data asynchronously via ajax. You'd use it if you want to retrieve data from the server that wasn't known at the time of page load...
For example, if a user enters a search term in an input control, you might want to retrieve JSON in response to that without performing a whole page update. You couldn't simply define a javascript object up-front because you wouldn't know what the search term was in advance.

Javascript + jQuery UI: After externalizing a JSON variable to a file, how to read the value back?

I'm quite a beginner in JS and even more in jQuery UI. I don't understand if my problem has a very simple synchronous solution, or if I need to write callback functions to cope with something that cannot be anything else than asynchronous...
I had this in a script associated with an HTML document:
var json = "[{ ... some object ... }]"
As the JSON object must be changed, I've created a text file and moved the value into it. Now I've to read the value from the file to assign it to the variable.
I see that when in production, the HTML page will be served by an HTTP server, and the file must be remotely retrieved using HTTP on the server. But also that if I want to test the page on my development machine, with no server, this is just reading a local file.
Is there a single piece of code that can read the JSON value in both situation, in a synchronous mode, so that something like this would be possible:
var json = ... piece of code...
I initially thought using:
$.getJSON("file.json", function(obj) { json = obj; });
expecting a read error would lead to json variable being the empty or null, but it seems the call is asynchronous and requires more code in callback functions.
Any guidance appreciated.
First of all, the call definitely should be synchronous. Just move the rest of your code into the callback, it's not that hard - and it will make your browser responsive while the file is downloaded.
If this is really a big problem, you can use the async option in $.ajax:
$.ajax({
async: false,
url: 'file.json',
dataType: 'json',
success: function (value) { json = value; }
});
Note: This will only work if the file you're requesting is from the same domain, and may or may not fail for local files, depending on the browser.

Categories