I am trying to add the json string to an html table. The object data is correct but it is not appending to the table. What am I doing wrong with my jquery append statement?
function GetSongs(id) {
$.ajax(
{
type: "Get",
url: "#Url.Action("GetSongs", "Game")",
data: { playlistId : id },
success: function (data) {
json = data;
obj = JSON.parse(json);
for (var i = 0; i < data.length; i++) {
$('#song-table').append('<tr>'+ htmlEncode(obj[i].SongURL) +'</tr>');
}
}
});
}
HTML Table:
<div id="player-playlist">
<table id="song-table" style="width:420px">
<tr>
<th>Song</th>
</tr>
<tr>
<td>http://www.youtube.com/v/CFF0mV24WCY</td>
</tr>
</table>
</div>
First try to debug the output what data you getting on ,is it a JSON string you returning from server side, also try to append td inside tr, and for htmlEncode write the custom function htmlEncode as shown below
function GetSongs(id) {
$.ajax(
{
type: "Get",
url: "#Url.Action("GetSongs", "Game")",
data: { playlistId : id },
success: function (data) {
console.log(data);
json = data;
obj = $.parseJSON(json);
for (var i = 0; i < data.length; i++) {
$('#song-table').append('<tr><td>'+ htmlEncode(obj[i].SongURL) +'</td></tr>');
}
}
});
}
function htmlEncode (value) {
if (value) {
return jQuery('<div />').text(value).html();
} else {
return '';
}
}
remove htmlEncode() because it is not defined in your js, define it or remove it
for (var i in obj) {
$("#song-table").append("<tr><td>"+ obj[i].SongURL +"</td></tr>");
}
OR
for (var i in obj) {
$("#song-table").append("<tr><td>"+ htmlEncode(obj[i].SongURL) +"</td></tr>");
}
function htmlEncode(string)
{
var pre = document.createElement('pre');
var text = document.createTextNode(string);
pre.appendChild(text);
return pre.innerHTML;
}//end htmlEncode it escapes HTML
You are trying to append it to <tr> rather than <td>. Change it to:
$('#song-table').append('<tr><td>'+ htmlEncode(obj[i].SongURL) +'</td></tr>');
Related
im trying to get my checked input value from my ajax but it only return my first tick...here is my code
function getBranchAjax(cuid, stid) {
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name=csrf-token]').attr('content')
}
});
$.ajax({
url: "{{ route('reporting.getBranchAjax',['cuid','stid']) }}",
method: 'GET',
data: { cuid: cuid, stid: stid },
dataType: 'json',
success: function (data) {
console.log(data);
console.log(data.branch.length);
//remove all option except the first option the append with new option
//remove all option except the first option the append with new option
for (var x = 0; x < data.branch.length; x++) {
//console.log(data.branch[x].cb_branch_Name);
$('#brRecord').append(`<tr><td style='width: 110px; text-align: left;'>${data.branch[x].cb_branchcode}
</td><td style='width: 600px; text-align: left;'>${data.branch[x].cb_branch_Name}</td>
<td style='width: 20px;'>
<input type="checkbox" class="ss" name="ss" id="ss" value="${data.branch[x].cb_branch_Name}" /></td><td>
</td></tr>`);
}
},
fail: function (xhr, textStatus, errorThrown) {
alert('request failed');
}
})
}
Get value by class name which is only return value of my first tick
var checkedValue = null;
var inputElements = document.getElementsByClassName('ss');
for(var i=0; inputElements[i]; ++i){
if(inputElements[i].checked){
checkedValue = inputElements[i].value;
break;
}
}
console.log(checkedValue); // only return a value of my first tick
I expect to get more value based on my input tick value
Multiple values would need to be held in an Array (or similar).
For example:
var checkedValues = Array.from(document.getElementsByClassName('ss')).filter(el => el.checked).map(el => el.value);
console.log(checkedValues);
Or, since the question is tagged jQuery:
var checkedValues = jQuery('.ss:checked').get().map(el => el.value);
console.log(checkedValues);
With the values in an array, you can then do whatever you want with them, eg display them or perform some transform on them.
It is because you add a break in your for loop.
Removing it will solve your problem.
for(var i=0; inputElements[i]; ++i){
if(inputElements[i].checked){
checkedValue = inputElements[i].value;
}
}
If you want to get all the latest clicked checkbox you can use onChange
function checkedInput()
{
cosnt checkedValue = [];
for(var i=0; inputElements[i]; ++i){
if(inputElements[i].checked){
checkedValue.push(inputElements[i].value);
}
}
return checkedValue ;
}
$(document).on('change', '#ss', function () {
console.log(checkedInput());
})
Here is my problem: I want to put JSON data that I catch with an Ajax call in an HTML div.
function showEspece(espece, categorie, object) {
$.ajax({
type: 'POST',
url: 'getespece.php',
data: {
espece: espece,
categorie: categorie
},
dataType: 'json',
success: function(data) {
console.log(data);
$('#output').html(data); //what i try to do but don't work
},
error: function(xhr, status, error) {
console.log(error);
}
});
}
<div id="output"></div>
And here is what the variable data contains:
How can I show the variable's content in an HTML div - in a table particularly?
You can use pre tag to display JSON.
var data = {"NOMA":["Chachi","Rafiki","Chakra"],"SEXE":["F","M","F"],"DATENAISSANCE":["05-MAY-15","07-JAN-15","17-SEP-17"]};
$('pre').html(JSON.stringify(data, undefined, 2));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre></pre>
Your data variable it's a JS object you need to convert it to string or the format you want to show it before calling $('#output').html(data).
You can do something like:
function showEspece(espece, categorie, object)
{
$.ajax({
type : 'POST',
url: 'getespece.php',
data: {espece: espece, categorie: categorie },
dataType: 'json',
success: function(data)
{
console.log(data);
data = JSON.stringify(data)
$('#output').html(data); //what i try to do but don't work
},
error: function(xhr, status, error) {
console.log(error);
}
});
}
as your json data children are array you can use $.each function:
Example:
var noma = data.NOMA;
var html_append = '';
$.each(noma, function(key,value) {
html_append += value +'<br>';
});
$('#output').html(html_append);
The same code you can use for also data.DATENAISSANCE and data.SEXE
Since your data returned is already in a JSON format, i suggest you to use $.getJSON and change your $_POST by $_GET variables in your getespece.php.
Also, your JSON Objects seems to be kind of not formatted correctly.. If you want to display your "especes" in an HTML table, the right JSON format could be something like this:
{
"Columns": [
"DateDeNaissance",
"Nom",
"Sexe"
],
"Especes": [{
"DateDeNaissance": "05-MAY-15",
"Nom": "Chachi",
"Sexe": "F"
}, {
"DateDeNaissance": "07-JAN-15",
"Nom": "Rafiki",
"Sexe": "M"
}, {
"DateDeNaissance": "17-SEP-17",
"Nom": "Chakra",
"Sexe": "F"
}]
}
Once you have this output from your PHP, change your JS to this:
$.getJSON("getespece.php", {
espece: espece,
categorie: categorie
})
.done(function(json) {
// Build the html Table
var html = "<table>\n";
html += "<thead>\n";
html += "<tr>\n";
// Columns
$.each(json.Columns, function(k, value) {
html += "<th>" + column + "</th>\n";
});
html += "</tr>\n";
html += "<tbody>\n";
// Rows
$.each(json.Especes, function(column, values) {
html += "<tr>\n";
// Cells
$.each(values, function(k, val) {
html += "<td>" + val + "</td>\n";
});
html += "</tr>\n";
});
html += "</tbody>\n";
html += "</table>\n";
$("#output").html(html);
});
var data = {
DATENAISSANCE: [...],
...
}
var root = document.getElementById("output");
var table = element("table");
root.appendChild(table);
var dataName;
for (dataName in data) {
if (data.hasOwnProperty(dataName)) {
var row = element("tr", element("th", dataName));
data[dataName].forEach(function (dataValue) {
row.appendChild(element("td", dataValue));
});
table.appendChild(row);
}
}
// Create a convenient function `element` which creates an element and sets its content
function element(nodeName, content, attributes, eventListeners) {
var node = document.createElement(nodeName);
appendChildren(node, content);
return node;
}
function appendChildren(node, content) {
var append = function (t) {
if (/string|number/.test(typeof t)) {
node.innerHTML += t;
} else if (t instanceof HTMLElement) {
node.appendChild(t);
}
};
if (content instanceof Array) {
content.forEach(function (item) {
append(item);
});
} else {
append(content);
}
}
I have this javascript and once the AJAX process is executed I want to replace this variable to some other variable.
window.onload = function() {
oldvariable = [];
var chart = new Chart("Container2", {
data: [{
type: "column",
dataPoints: oldvariable
}]
});
}
When I process the AJAX request and fetch JSON data which is stored in oldvariable, it is not written so I have few options. I tried ads they are working in HTML but not under script tag.
If I can define oldvariable='<div class="second"></div>'; and replace this with processed JSON data then it is working and giving correct output in HTML but in javascript < tag is not allowed as variable so we cant define oldvariable like that.
$( "div.second" ).replaceWith( ''+newvariable +'' );
So is there anyway I can replace javascript variable as HTML tags are not allowed in variable and without tag javascript can't replace.
I have one more probable solution.regex. Search for oldvariable in entire HTML code and replace with newvariable but that process will be very slow so what is the best way to do this.
My vairables are globally defined and AJAX request is in external file and above codes are embeded in HTML.
========edit
how we can replace oldvariable with newvariable in above javascript
====== ajax code- variable name is different
$(document).ready(function() {
(function() {
$('#upload-form2').ajaxForm({
dataType: 'json',
success: function(data) {
var oldvariable = '',
downlo;
for (var i = 0; i < data.length; i++) {
downlo = data[i];
oldvariable += '' + downlo.ndchart + '';
}
$('#chek').html(oldvariable );
}
})
})();
});
you need to update chart datapoints and re-render the chart after ajax success like this
ajax :
...
success:function(response)
{
chart.options.data[0].dataPoints=response;
//response is (array) of dataSeries
chart.render();
}
.......
update 1 : As per your code data should be updated like this
.....
success:function(data) {
var new_data = [];
for (var i = 0; i < data.length; i++)
{
new_data.push({y:data[i].ndchart });
}
chart.options.data[0].dataPoints=new_data;
chart.render();
}
.....
update 2:
$(document).ready(function() {
(function() {
$('#upload-form2').ajaxForm({
dataType: 'json',
success: function(data) {
var new_data = [];
for (var i = 0; i < data.length; i++)
{
new_data.push({y:data[i].ndchart });
}
chart.options.data[0].dataPoints=new_data;
chart.render();
}
})
})();
});
I have a problem to send table global from view to controller the table in controller is full but in controller affect a null for the composant of table
and this is the controller method :
public Boolean ajoutermodule(string nom, modules[] global, int cv)
{
return true;
}
And this the view and method ajax how i append my table global and how i sent this table global from view to controller :
function Addmodule() {
var nom = $("#nomprojet_I").val();
var cv = global.length;
$.ajax({
url: "/Module/ajoutermodule",
type: "POST",
dataType: 'json',
data: {
"nom": nom,
"global": global,
"cv": cv,
},
success: function (responseText) {
debugger;
if (responseText == "True") {
alert("Succes");
}
else {
alert("error");
}
}
});
}
var global = [];
function OnGetSelectedFieldValues(s, e) {
var SelectedUsers = $("#teamlist_I").val() + " " + $("#teamid_I").val();
listbox.AddItem(SelectedUsers);
var nom = $("#teamlist_I").val();
var id = $("#teamid_I").val();
global.push({ "id": id, "nom": nom });
debugger;
}
and when i added the length it send him correctly to controller.
but method ion your controller like this:
public Boolean ajoutermodule(string nom, stirng s, int cv)
{
return true;
}
and add this to your method ajax
var s = JSON.stringify(global);
function Addmodule() {
var nom = $("#nomprojet_I").val();
var s = JSON.stringify(global);
var cv = global.length;
$.ajax({
url: "/Module/ajoutermodule",
type: "POST",
dataType: 'json',
data: {
"nom": nom,
"s": s,
"cv": cv,
},
success: function (responseText) {
debugger;
if (responseText == "True") {
alert("Succes");
}
else {
alert("error");
}
}
});
}
it will work inchallah
Please try this code for ASP.NET MVC –
View.cshtml
<table id="StepsTable">
<tr>
<td>Step 1</td>
<td>#Html.TextBox("step1")</td>
</tr>
<tr>
<td>Step 2</td>
<td>#Html.TextBox("step2")</td>
</tr>
<tr>
<td>Step 3</td>
<td>#Html.TextBox("step3")</td>
</tr>
</table>
<input id="SendToControllerButton" type="button" value="Send to the server"/>
<script>
$(document).ready(function () {
$("#SendToControllerButton").click(function () {
var data = {};
//Collects the data from textboxes and adds it to the dictionary
$("#StepsTable tr").each(function (index, item) {
var tds = $(this).find("td");
var textBoxTitle = $(tds).eq(0).text();
var textboxValue = $(tds).eq(1).find("input").val();
data["stepsDictionary[" + index + "].Key"] = textBoxTitle;
data["stepsDictionary[" + index + "].Value"] = textboxValue;
});
//Makes ajax call to controller
$.ajax({
type: "POST",
data: data,
url: "/Home/ProcessStepsValues",
success: function (message) {
alert(message);
}
});
});
});
</script>
And then sends the data to controller
Controller.cs
[HttpPost]
public string ProcessStepsValues(Dictionary<string, string> stepsDictionary)
{
string resultMessage = string.Empty;
if (stepsDictionary != null)
{
resultMessage = "Dictionary data passes to controller successfully!";
}
else
{
resultMessage = "Something goes wrong, dictionary is NULL!";
}
return resultMessage;
}
Please refer the site for more details
https://alexkuznetsov.wordpress.com/2013/05/08/asp-net-mvc-pass-dictionary-data-from-view-to-controller/
In MVC 4 application I want when click a link, to show some related Products list in lightbox. I have method returns products I need:
public ActionResult GetRelatedProducts(int id)
{
var realProducts = GetRelatedProducts(id);
List<object> productsObjectList = new List<object>();
foreach (var item in realProducts)
{
productsObjectList .Add(new
{
id = item.Id,
fullname = item.Name
});
}
return Json(productsObjectList , JsonRequestBehavior.AllowGet);
}
HTML is:
<a class="show" id="show">Show</a>
<div id="productBox" style="display: none;">
// Product list will get here
</div>
And script:
$('#show').click(function (e) {
url = '#Url.Action("GetRelatedProducts", "Product")';
var data = { id: '#Model.Id' };
$.post(url, data, function (result) {
$('#productBox').lightbox_me({
onLoad: function () {
//How to send returned product list to light box, to show them by foreach loop
}
});
e.preventDefault();
});
});
How can I send product list to productBox to show products?
You code:
$('#show').click(function (e) {
url = '#Url.Action("GetRelatedProducts", "Product")';
var data = { id: '#Model.Id' };
$.post(url, data, function (result) { // <- "result" will contain array
$('#productBox').lightbox_me({
onLoad: function () { ... }
});
e.preventDefault(); // <- this must prevent "a" tag, put it outside
});
});
You could use your list on client side like this:
$.post(url, data, function (result) {
var list = '<ul>';
for(var i = 0; i < result.length; i++)
{
list += '<li>' + result[i].fullname + '</li>';
}
list += '</ul>';
$('#productBox').html(list).lightbox_me();
});
OR as Vladimir Bozic wrote, just use PartialViewResult, from controller return PartialView, it is like normal view, but without layout, just html block and you can use it like:
$.post(url, data, function (result) {
$('#productBox').html(result).lightbox_me();
});