I am trying to assign a JS variable to a ViewBag property and use that property in an Html ActionLink.
However, I'm getting a design time compile error: "Syntax error" right below the getJSON method as #ViewBag.CustomerID = data.CustomerID;
Can someone help me out with how this is done?
Here is my code:
#Html.ActionLink("Click to edit Customer", "EditCust", "Customer", new { ViewBag.CustomerID }, null);
<script type="text/javascript">
$(function ()
{
var selID = null
$("#Name").change(function ()
{
selID = $("#Name option:selected").val();
var url = '/Project/SpecificCustomer';
var param = { Id: selID };
$.getJSON(url, param, function (data)
{
#ViewBag.CustomerID = data.CustomerID;
var html = "<table border='1' cellpadding='3'>";
html += "<tr>";
html += "<td>" + "Customer ID: " + data.CustomerID + "</td>";
html += "</tr>";
html += "<tr>";
html += "<td>" + "Email: " + data.Email + "</td>";
html += "</tr>";
html += "<tr>";
var FirstName = data.FirstName;
FirstName == null ? "" : FirstName;
var LastName = data.LastName;
LastName == null ? "" : LastName;
html += "<td>" + "Name: " + FirstName + " " + LastName + "</td>";
html += "</tr>";
html += "<tr>";
var date1 = new Date(parseInt(data.CreatedDate.substr(6)));
date1 == null ? "" : date1;
html += "<td>" + "Created: " + date1 + "</td>";
html += "</tr>";
html += "<tr>";
var date2 = new Date(parseInt(data.UpdatedDate.substr(6)));
date2 == null ? "" : date2;
html += "<td>" + "Updated: " + date2 + "</td>";
html += "</tr>";
html += "</table>";
$("#divData").html('');
$("#divData").append(html);
});
});
});
</script>
This won't work. ViewBag works on server side and it will be out of scope when you get the response of an AJAX request. You should use JavaScript to update the values in your view once you get the response.
You also get the error because an assignment should be in a code block:
#{ ViewBag.CustomerID = data.CustomerID; }
However this still won't work because data is a JavaScript variable.
Related
I have a class project where I need to pull data from my SQLite DB and place it into <table>.
But every time I reload the page I get this Table image and I was hoping for some help. I'm new to JavaScript and I need to finish this task in a few hours, I've tried to pull the data into an object and from the object into this line str += "<td>" + results.rows.item(i).Firstname + "</td>" and still it didn't work.
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM Customers_Table ', [], function (tx, results) {
var len = results.rows.length, i;
document.getElementById("tablea").innerHTML = '';
var str = '';
str += "<th>FirstName</th>";
str += "<th>LastName</th>";
str += "<th>Address</th>";
str += "<th>City</th>";
str += "<th>Email</th>";
for (i = 0; i < len; i++) {
str += "<tr>";
str += "<td>" + results.rows.item(i).Firstname + "</td>";
str += "<td>" + results.rows.item(i).Lastname + "</td>";
str += "<td>" + results.rows.item(i).Address + "</td>";
str += "<td>" + results.rows.item(i).City + "</td>";
str += "<td>" + results.rows.item(i).Email + "</td>";
str += "</tr>";
document.getElementById("tablea").innerHTML += str;
str = '';
}
});
});
Well, considering that you have data in results. It should be used as:
results.rows.item[i].Firstname
NOT
results.rows.item(i).Firstname
Finally figured out the problem, the .Firstname and the rest didn't match the column names from the Db table, it was lowercase,look carefully at your code guys!!
This question already has answers here:
How to return an image from http source in Javascript
(5 answers)
Closed 3 years ago.
Hi I want to display multiple image into html table using jquery check my code for more clearification.
In Console i get only image source as
<img src="uploads/">
$.ajax({
url : 'check.php',
success: function (data) {
data = $.parseJSON(data);
var html = "";
for(var a = 0; a < data.length; a++) {
var firstName = data[a].first_name;
var email = data[a].email;
var dob = data[a].dob;
var country = data[a].country;
var gender = data[a].gender;
var meal= data[a].meal;
var img = data[a].profile_pic;
var array = img.split(',');
for (var i = 0; i < array.length; i++) {
var src = "uploads/"+ array[i];
var img1 = '<img src='+ src +'>';
}
html += "<tr>";
html += "<td>" + firstName + "</td>";
html += "<td>" + email + "</td>";
html += "<td>" + dob + "</td>";
html += "<td>" + country + "</td>";
html += "<td>" + gender + "</td>";
html += "<td>" + meal + "</td>";
html += "<td>" + img1 + "</td>";
html += "</tr>";
document.getElementById("data").innerHTML += html;
}
},
Just move your img content inside for loop.
$.ajax({
url : 'check.php',
success: function (data) {
data = $.parseJSON(data);
var html = "";
for(var a = 0; a < data.length; a++) {
var firstName = data[a].first_name;
var email = data[a].email;
var dob = data[a].dob;
var country = data[a].country;
var gender = data[a].gender;
var meal= data[a].meal;
var img = data[a].profile_pic;
var array = img.split(',');
html += "<tr>";
html += "<td>" + firstName + "</td>";
html += "<td>" + email + "</td>";
html += "<td>" + dob + "</td>";
html += "<td>" + country + "</td>";
html += "<td>" + gender + "</td>";
html += "<td>" + meal + "</td>";
html += "<td>";
for (var i = 0; i < array.length; i++) {
var src = "uploads/"+ array[i];
var img1 = '<img src='+ src +'>';
html += img1
}
html += "</td>";
html += "</tr>";
document.getElementById("data").innerHTML += html;
}
},
I'm trying to get a xml from this php:
<?php
// ...
$row = mysqli_fetch_array($result);
$xml = new DOMDocument("1.0", "UTF-8");
$book = $xml->createElement("book");
$book = $xml->appendChild($book);
$bookId = $xml->createElement("id",$row['id']);
$bookId = $book->appendChild($id);
$bookAuthor = $xml->createElement("author",$row['author']);
$bookAuthor = $book->appendChild($bookAuthor);
$bookTitle = $xml->createElement("title", $row['title']);
$bookTitle = $book->appendChild($bookTitle);
$bookGenre = $xml->createElement("genre",$row['genre']);
$bookGenre = $book->appendChild($bookGenre);
$bookDescription = $xml->createElement("description",$row['description']);
$bookDescription = $book->appendChild($bookDescription);
echo($xml->asXML());
mysql_close($con);
?>
To this js function (using AJAX):
function ByTitle(title) {
document.getElementById("results").innerHTML = "";
var xmlDoc;
var Output = "";
if (title != "") {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.open("GET", "getBooksByTitle.php?title=" + title, true);
xmlhttp.send(null);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
xmlDoc = xmlhttp.responseXML;
var x = xmlDoc.getElementsByTagName('book');
alert(x.textContent);
Output = "<table><br><p><b>Results:</b></p><table><tr><th>id</th><th>author</th><th>title</th><th>genre</th><th>price</th><th>description</th></tr><tr>";
Output += "<td>" + x.documentElement.getElementsByTagName('id')[0].childNodes[0].nodeValue + "</td>";
Output += "<td>" + x.documentElement.getElementsByTagName('author')[0].childNodes[0].nodeValue + "</td>";
Output += "<td>" + x.documentElement.getElementsByTagName('title')[0].childNodes[0].nodeValue + "</td>";
Output += "<td>" + x.documentElement.getElementsByTagName('genre')[0].childNodes[0].nodeValue + "</td>";
Output += "<td>" + x.documentElement.getElementsByTagName('price')[0].childNodes[0].nodeValue + "</td>";
Output += "<td>" + x.documentElement.getElementsByTagName('description')[0].childNodes[0].nodeValue + "</td></tr></table>";
document.getElementById("results").innerHTML = Output;
}
}
But unfortunately the only I get is TypeError:
x.documentElement is undefined (:Mozilla).
I've tried a lot of different "solutions" but none of them make any difference...
You don't need to call x.documentElement as you already have xmlDoc
so you should just use something like this:
Output += "<td>" + xmlDoc.getElementsByTagName('id')[0].childNodes[0].nodeValue + "</td>";
Output += "<td>" + xmlDoc.getElementsByTagName('author')[0].childNodes[0].nodeValue + "</td>";
Output += "<td>" + xmlDoc.getElementsByTagName('title')[0].childNodes[0].nodeValue + "</td>";
Output += "<td>" + xmlDoc.getElementsByTagName('genre')[0].childNodes[0].nodeValue + "</td>";
Output += "<td>" + xmlDoc.getElementsByTagName('price')[0].childNodes[0].nodeValue + "</td>";
Output += "<td>" + xmlDoc.getElementsByTagName('description')[0].childNodes[0].nodeValue + "</td></tr></table>";
Also: It is easier to consume JSON as server response for ajax requests, because you'd only need to use JSON.parse(data) to use your response as plain JS object.
This is the function in my javascript. Triggered by an onclick function by an another function.
function getValueUsingParentTag(){
var tv_type = [];
var screen_size = [];
var connectivity = [];
var features = [];
var chkArray = [tv_type,screen_size,connectivity,features];
$("#tvtype input:checked").each(function() {
tv_type.push($(this).val());
});
$("#screensize input:checked").each(function() {
screen_size.push($(this).val());
});
$("#connection input:checked").each(function() {
connectivity.push($(this).val());
});
$("#feature input:checked").each(function() {
features.push($(this).val());
});
console.log(chkArray);
//alert(JSON.stringify(chkArray));
alert('hello');
$.get("output-tv.php",{tv_type:tv_type,screen_size:screen_size,connectivity:connectivity,features:features},function(chkArray){
});
}
This is the sample json object returned
{"result":[
{"product_code":"B2810","tv_name":"32B2810","size":"32","tv_type":"INTERNET TV"},
{"product_code":"B2610","tv_name":"48B2610","size":"48","tv_type":"INTERNET TV"}
]}
I need to create a table in javascript based on the json object returned. I dont know how. Please Help.
following function builds the table in a string.
function getTable(data) {
var html = "";
html += "<table><tr><td>product_code</td><td>tv_name</td><td>size</td><td>tv_type</td></tr>";
html += "<tr>";
for(var i = 0, ceiling = data.result.length; i < ceiling; i++) {
var row = data.result[i];
html += "<td>" + row.product_code + "</td>";
html += "<td>" + row.tv_name + "</td>";
html += "<td>" + row.size + "</td>";
html += "<td>" + row.tv_type + "</td>";
}
html += "</tr>";
html += "</table>";
return html;
}
suppose you have a div with id mydiv, you can add the table to this div with following code:
document.getElementById("mydiv").innerHTML = getTable(data);
Here's a simple Javascript only loop example:
http://jsfiddle.net/mCLVL/
var tableData = {"result":[
{"product_code":"B2810","tv_name":"32B2810","size":"32","tv_type":"INTERNET TV"},
{"product_code":"B2610","tv_name":"48B2610","size":"48","tv_type":"INTERNET TV"}
]};
var tableHTML = "<table>";
for (var i = 0; i < tableData["result"].length; i++) {
tableHTML += "<tr>";
tableHTML += "<td>" + tableData["result"][i]["product_code"] + "</td>";
tableHTML += "<td>" + tableData["result"][i]["tv_name"] + "</td>";
tableHTML += "<td>" + tableData["result"][i]["size"] + "</td>";
tableHTML += "<td>" + tableData["result"][i]["tv_type"] + "</td>";
tableHTML += "</tr>";
}
tableHTML += "</table>";
console.log(tableHTML);
It will be so simple by using JSRender. I made a fiddle using jsrender template check it.
Using JSRender Fiddle
I have a jQuery getJson method which correctly returns a selected CustomerID. When that happens, a button is enabled to send the CustomerID to another Controller method which would then open up a form to modify the customer.
I check the Form collection, but there is no value associated with the ID of the Collection. It simply comes out as "CustomerID" with no value.
How can I successfully pass this value to the other Controller with the Form Collection?
I know that the script section contains the var CustomerID and the BeginForm has the hiddenfield value, but obviously, there is no "linkage" between the two. I'm wondering how I can do this...
So basically, how can I get the JS variable value inside CustomerID into the Form?
JS
#section scripts {
<script type="text/javascript">
$(function ()
{
var selID = null;
var CustomerID = null;
$("#Name").change(function ()
{
selID = $("#Name option:selected").val();
var url = '/Project/SpecificCustomer';
var param = { Id: selID };
$.getJSON(url, param, function (data)
{
var html = "<table border='1' cellpadding='3'>";
html += "<tr>";
html += "<td>" + "Customer ID: " + data.CustomerID + "</td>";
CustomerID = data.CustomerID;
html += "</tr>";
html += "<tr>";
html += "<td>" + "Email: " + data.Email + "</td>";
html += "</tr>";
html += "<tr>";
var FirstName = data.FirstName;
FirstName == null ? "" : FirstName;
var LastName = data.LastName;
LastName == null ? "" : LastName;
html += "<td>" + "Name: " + FirstName + " " + LastName + "</td>";
html += "</tr>";
html += "<tr>";
var date1 = new Date(parseInt(data.CreatedDate.substr(6)));
date1 == null ? "" : date1;
html += "<td>" + "Created: " + date1 + "</td>";
html += "</tr>";
html += "<tr>";
var date2 = new Date(parseInt(data.UpdatedDate.substr(6)));
date2 == null ? "" : date2;
html += "<td>" + "Updated: " + date2 + "</td>";
html += "</tr>";
html += "</table>";
$("#divData").html('');
$("#divData").append(html);
if (CustomerID != null)
$("#UpdateCust").prop('disabled', false);
});
});
});
</script>
}
#using (Html.BeginForm("Index", "Customer", new AjaxOptions { HttpMethod = "POST" }))
{
<fieldset>
<legend>Edit Customer</legend>
<div class="editor-field">
<input type="hidden" id="custID" name="custID" value="CustomerID" />
<input type="submit" id="UpdateCust" value='#Resources.Update' disabled="disabled" />
</div>
</fieldset>
}
Other Controller method
public ActionResult Index(FormCollection form)
{
string custID = form["custID"];
...
It's not clear, but if the form resides on the same page as the getJSON script, then you could change the last lines of your JavaScript to be:
if (CustomerID != null) {
$("#UpdateCust").prop('disabled', false);
$("#custID").val(data.CustomerID);
}