jquery - separate JSON and HTML from AJAX Response - javascript

I have a AJAX response something like this.
[{"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11‌​464"}]<table id="table"></table>
It has both JSON and HTML in the response.
I wanted to separate those two things.
And use the JSON for a chart function I've created.
And then append that table to a div.
Any suggestions will be very much fruitful.
Thanks in advance.

In php
$array = 'Your json array';
$html = 'Your html codes';
Make a single array with two keys
$newArray = array();
$newArray['json'] = $array;
$newArray['html'] = $html;
echo json_encode($newArray);
In Jquery
DataType: 'JSON',
success:function(response){
response.json = 'This is your json';
response.html = 'This is your html';
}

Add the HTML to the JSON response and use it like you would your other values (make sure to escape your html). Also use JSONLint to make sure your JSON is valid.
[
{
"label": "label",
"label1": "67041",
"label2": "745",
"label3": "45191",
"label4": "11‌​464",
"html": "<table id=\"table\"></table>"
}
]

While I recommend you not to do that, because is to geeky and hard to maintain, You can solve id by detecting the JSON object using regex, like this:
var data = '[{"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11‌464"}]<table id="table"></table>';
var json_pattr = /\[.*\]/g;
var json_str = json_pattr.exec(data)[0];
var json_data = eval( '(' + json_str.substr(1, json_str.length-2) + ')') ;
var html_pattr = /\}\].*/g;
var html_text = html_pattr.exec(data)[0];
var html_data = html_text.substr(2);
//json_data = [object] {"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11‌464"}
//html_data = [text] <table id="table"></table>
The Best Solution would be to use a template engine like jquery templates to define your html, and then get your data via $.json and evaluate it agains your desired template already on the client, no need to be sending it right along with your data and be doing that kind of processing in run time.
JavaScript
// assuming you keep receiving this
var data =
'[{"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11‌464"},'
+'{"label":"label2","label1":"0000","label2":"222","label3":"333","label4":"11‌333"}]'
+'<table id="table"></table>';
// parse the data with regex
var json_pattr = /\[.*\]/g;
var json_str = json_pattr.exec(data)[0];
var json_data = eval( '(' + json_str + ')') ;
var html_pattr = /\}\].*/g;
var html_text = html_pattr.exec(data)[0];
var html_data = html_text.substr(2);
//json_data = [object] {"label":"label","label1": ...
//html_data = [text] <table id="table"></table> ...
// then use jquery templates to render it
var data = json_data;
$('body').append(html_data);
$('#trTemplate').tmpl(data).appendTo('#table');
HTML
<script id="trTemplate" type="text/x-jquery-tmpl">
<tr>
<td>${label}</td>
<td>${label1}</td>
<td>${label2}</td>
<td>${label3}</td>
<td>${label4}</td>
</tr>
</script>
CSS
#table, td{ border:1px solid #000; padding:5px; }
Here is an working JSFiddle example for you to test it.
Note how this works when you have more than one {json object, it's creates more lines in the table :) }
If you use jquery templates only, and now assuming that you can actually modify your output than the best thing to do is:
New JavaScript Version of Code with template only and no HTML on 'data'
$.json('http://server.com/url/service/someservice.something', function(data){
$('body').append(<table id="#table></table>");
$('#trTemplate').tmpl(data).appendTo('#table');
})
Much more simple don't you think?! Hope this helps guiding you on the right path.
Link to jquery tmpl: http://knockoutjs.com/downloads/jquery.tmpl.min.js.
Although after understanding my example, if you are building a system to scale on, and you are not just doing a simple widget app, I would recommend you to check something more robust in terms of functionalities and support like Knockoutjs as jquery tmpl has been deprecated, unfortunately.

Related

For Loops in Blogger, Replacing all characters in a string with the give character Java Script for Blogger

This is a simple question i have,
I have a simple script here :
//<![CDATA[
$(document).ready(function() {
$('img').each(function(){
var $img = $(this);
var filename = $img.attr('src')
var returnt=filename.substring((filename.lastIndexOf('/'))+1,filename.lastIndexOf('.'));
var returna=filename.substring((filename.lastIndexOf('/'))+1,filename.lastIndexOf('.'));
<b:loop values='returnt.length'>
var ctitle=returnt.replace("%2B", " ");
var calt=returna.replace("%2B", " ");
</b:loop>
$img.attr('title', ctitle);
$img.attr('alt', calt);
});
});
//]]>
I wanted all the %2B in the returnt and returna to be replace with space and stored in ctitle and calt respectively, but without a loop it won't work.
I tried something like
for(int i=0;i<returnt.length;i++)
{
var ctitle=returnt.replace("%2B", " ");
var calt=returna.replace("%2B", " ");
}
But didn't work, now I have put the values='returnt.length' in the script but it's still not working.
I know something is missing and is wrong somewhere, please tell me how to do it.
I want the loop to work like the given above for loop.
And I tried .replaceAll("","") method but didn't work. :(
I want a method to replace all the characters or info on how to write the above for loop in blogger FOR LOOP method.
You can use regex matching in replace. The code will look like -
$(document).ready(function() {
$('img').each(function() {
var $img = $(this);
var filename = $img.attr('src')
var returnt = filename.substring((filename.lastIndexOf('/')) + 1, filename.lastIndexOf('.'));
var returna = filename.substring((filename.lastIndexOf('/')) + 1, filename.lastIndexOf('.'));
var ctitle = returnt.replace(/%2B/g," ");
var calt = returna.replace(/%2B/g," ");
$img.attr('title', ctitle);
$img.attr('alt', calt);
});
});
The b:loop tag is native to Blogger platform. Its values attribute only accepts data tags present in Blogger and not custom JavaScript variables. Refer to the documentation here
The general format for using loops is this:
<b:loop var='identifier' values='set-of-data'>
[repeated content goes here]
</b:loop>
The 'identifier' (i) part can be any name you choose, and will be used
to stand in for each new item in the list, each time through the loop.
The set of data you specify for the values can be any piece of data
described in the data tags article as being a list of items.

Jqgrid inline mode with select2

I have found the #Olegs answer for FORM based select2 integration to jQgid, but I need help to get it to work in inline mode,, this jsfiddle is my attempt to get my problem online somehow I'm new with fiddle so please be patient :)
http://jsfiddle.net/mkdizajn/Qaa7L/58/
function(){ ... } // empty fn, take a look on jsfiddle
On this fiddle I can't make it to work to simulate the issue I have in my local network but the problem with this select2 component is that when I update some record(via local or ajax), the grid does not pick up my change and it sends null for values where select2 fields are!
I'm sorry that I can't make jsfiddle to work like on my PC :(
Thanks for any help you can think off that may be the issue here..
P.S. one veeeery strange thing is that when I console.log( select2-fields ), before, and after the value is picked up correctly but I suspect that the grid loose that value somewhere in between .. and send null values to server..
I'm posting this in a good will that I think will help anyone if come to close incounter with similar problem like me..
I'll try to bullet this problem out step by step..
first, on my server side I generate one html tag somewhere near grid table that holds info what columns, fields are lookup type.. like this:
<div id="hold_lookup_<?=$unique_id?>" style="display: none"><?php echo $lokki; ?></div>
that gives me output like this:
<div id="hold_lookup_table1" style="display: none">col1+++col2+++col3</div>
define onselectrow event somewhere
$onSelectRow = "function(){
f = $(this).attr('id'); // grid name
try{
n = $('#hold_lookup_' + f).text().split('+++');
}catch(e){
console.log(e)
}
rez = ''; // results
temp = 'textarea[name='; // template
$.each(n, function(index, item){
rez += temp + item + '],'
});
rez = rez.slice(0,-1); // rezemo zadnji zarez
$( rez ).select2({ .. define my ajax, my init etc.. });
}";
$dg->add_event("jqGridInlineEditRow", $onSelectRow);
last but very tricky part is here.. I destroy select2 columns before sending to database in jqgrid.src file where function for SAVE inline method is.. like this
if (o.save) {
$($t).jqGrid('navButtonAdd', elem, {
caption: o.savetext || '',
title: o.savetitle || 'Save row',
buttonicon: o.saveicon,
position: "first",
id: $t.p.id + "_ilsave",
onClickButton: function() {
var sr = $t.p.savedRow[0].id;
rez = rez.split(',');
rez1 = '';
$.each(rez, function(index, item) {
rez1 += item + ','
})
rez1 = rez1.slice(0, -1);
rez1 = rez1.split(',');
$.each(rez1, function(index, item) {
$(item).select2('destroy');
});
you can see that I inserted the code onclickbutton event via same 'rez' variable that was defined in my php file where I created grid..
That's it, I hope that helped someone, event if not in this particular problem, but with methods that was used here :)
cheers, kreso

How to create and display XML through Javascript/PHP/

I have some javascript objects that represent the XML that i want to create.
I need a simple way to create/ generate XML, and then somehow hand it over/ show it to the user in a clean way (structurized, like in the screenshot example).
I've been experimenting and researching but haven't yet foudn what i am looking for.
Current test code:
function exportXML(){
var XML = document.createElement("div");
var Node = document.createElement("testing");
Node.appendChild( document.createElement("testingOne") );
Node.appendChild( document.createElement("TestingTwo") );
Node.appendChild( document.createElement("TestingThree") );
XML.appendChild(Node);
//alert(XML.innerHTML);
xmlWin = window.open("","xmlWin","width=800,height=600");
xmlWin.document.write("XML: \n" + XML.innerHTML);
}
xml example:
-<station stationNr="WP006">
-<definitionstat>
<admtyp>A</admtyp>
<responsible>SIEMENS</responsible>
<bildnam>B12</bildnam>
<stattyp>T</stattyp>
</definitionstat>
</station>
What i would like to have:
To create XML:
$xml = new \DomDocument("1.0","UTF-8");
$xml->formatOutput = true;
$xml_data = $xml->createElement("Element_Container","Container Value");
$xml_data = $xml->appendChild($xml_data);
$xml->saveXML();
$xml_status->save($xml_file_path);
To display in formatted way:
$xml = simplexml_load_file($xml_file_path);
foreach ($xml->children() as $key => $child)
{
// Your formatted output here...
}

Is there a limit of the size of data using replaceWIth in jQuery?

I am using the replaceWith() function in jQuery to update my web page. I receive the data from a C# web service program that extracts data from a database to build my HTML code. It works fine except when I replace large amounts of data. In the example that's not working, I replace code in my web page with 39000 bytes of data. After that, none of my links work when clicking on a span to calls a JavaScript function. Is there a limit on the size of data used in the replaceWith() function? The html code I am replacing looks like this:
<td align=left valign=top>
<div id="showitems" class="showitems" style="display:inline; float:left"></div>
</td>
The javascript code looks like this:
function ShowDinerItems() {
var gps = document.getElementById("selectdiner").value;
var pos = gps.indexOf(";");
var len = gps.length;
var latitude = document.getElementById("Hiddenlat").value;
var longitude = document.getElementById("Hiddenlng").value;
var dinerkey = gps.substring(0, pos);
PageMethods.CallShowDinerItems(dinerkey, latitude,longitude, OnShowDinerComplete, OnShowDinerError, dinerkey);
}
function OnShowDinerComplete(result) {
var htmlcode = result[0];
if (result == 'none') {
document.getElementById("Message").value = "Search returned no items";
}
else {
var htmlcode = result[0];
htmlcode = "<div id=\"showitems\" class=\"showitems\" style=\"display:inline\">" + htmlcode + "</div>";
$('.showitems').replaceWith(htmlcode); // size of htmlcode is 39849 bytes
var locations = result[1].split(";");
var lat = locations[0];
var lng = locations[1];
markDiner(lat, lng, "", 'map_canvas');
}
}
The reason I am using jquery to build my webpage is to avoid page reloads. I could easily program the webdata content in my C# program which may be more efficient but page reloads are to be avoided as dictated by the people who own the website. I am will try the recommendations given.
Note: I used the following code to make it work.
$('.showitems').html(result[0]);
Using .text will not work as it displays raw data and not html data. Thanks to those who contributed.
To be honest I think you're going about this the wrong way here.
It seems to me that you're using ReplaceWith to completely overwrite the matched tag when you could just as simply change its properties with jQuery.
For example:
var htmlcode = result[0];
htmlcode = "<div id=\"showitems\" class=\"showitems\" style=\"display:inline\">" + htmlcode + "</div>";
$('.showitems').replaceWith(htmlcode); // size of htmlcode is 39849 bytes
Could easily be changed to this:
$('.showitems').css('float','none').text(result[0]);
Just how many showItems are there going to be by the way, and how do you know how it compares to how many results you get back from the C# call ?
Edit 2: Sorry, didn't realise that the CSS display attribute wasn't actually changing.

Match a String in a Webpage along with HTML tags

With below code, I am trying to match a text in a web page to get rid of html tags in a page.
var body = $(body);
var str = "Search me in a Web page";
body.find('*').filter(function()
{
$(this).text().indexOf(str) > -1;
}).addClass('FoundIn');
$('.FoundIn').text() = $('.FoundIn').text().replace(str,"<span class='redT'>"+str+"</span>");
But it does not seems to work.. Please have a look at this and let me know where the problem is...
here is the fiddle
I have tried the below code instead..
function searchText()
{
var rep = body.text();
alert(rep);
var temp = "<font style='color:blue; background-color:yellow;'>";
temp = temp + str;
temp = temp + "</font>";
var rep1 = rep.replace(str,temp);
body.html(rep1);
}
But that is totally removing html tags from body...
change last line of your code to below one...you are using assignment operator which works with variables not with jquery object ..So you need to pass the replaced html to text method.
$('.FoundIn').text($('.FoundIn').text().replace(str,"<span class='redT'>"+str+"</span>"))
try this.
$('*:contains("Search me in a Web page")').text("<span class='redT'>Search me in a Web page</span>");

Categories

Resources