Passing a hiddenfield form value to a Controller - javascript

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);
}

Related

unable to load html table through onclick

I have a function which loads a html table with sql data query and a html page to display the table when i click the button but it is not showing the table, it just shows the url changing to match my search but does not display the table
Function code:
function Search()
{
var search = new Object;
search.restaurantName = document.getElementById("searchinput").value; //get input
var searchrestaurant = new XMLHttpRequest();
searchrestaurant.open("POST", Search_url, true);
searchrestaurant.setRequestHeader("Content-Type", "application/json");
searchrestaurant.onload = function()
{
search_array = JSON.parse(request.responseText);
result();
}
searchrestaurant.send(JSON.stringify(search));
}
function result()
{
var table = document.getElementById("result");
table.innerHTML = "";
result = search_array.length
for (var count = 0; count < result; count++)
{
// data from sql
var restaurant_name = search_array[count].restaurant_name;
var Description = search_array[count].Description;
var location = search_array[count].location;
var thumbnail = search_array[count].thumbnail;
var price = search_array[count].price;
var rating = search_array[count].avg_rating;
//table to show all sql data
var AllrestaurantTable = "<table class = fixed style=width:100% border=1px>" +
"<tr>"+
"<td>" +"<a href = 'detailed_restaurant.html' target ='_blank'>"+"<img src ='" + thumbnail + "'style=width:100px;height:100px;></img>"+"</td>" +
"<td>"+"<a href = 'detailed_restaurant.html' target ='_blank'>"+ restaurant_name + "</td>" +
"<td>"+ location + "</td>" +
"<td>"+ Description + "</td>" +
"<td>"+ price + "</td>" +
"<td>"+ rating + "</td>"
"</tr>" +
"</table>";
table.insertAdjacentHTML('beforeend', AllrestaurantTable);
}
}
Html:
<body>
<form id = "SearchForm">
<label>Search </label>
<input type="text" id="searchinput" name="restaurantName">
<input type="button" onclick="Search()" value="Submit">
</form>
<div class="container"></div>
<div id="result" class="row"></div>
</div>
I have already loaded the script into the html site but it is just take my input and does not display the table i created
Concatenation operator is missing after "<td>" + rating + "</td>".
Add the + operator. like "<td>" + rating + "</td>" +.
function result() {
var table = document.getElementById("result");
table.innerHTML = "";
result = 5
for (var count = 0; count < result; count++) {
// data from sql
var restaurant_name = 1;
var Description = 'ddf';
var location = 'location';
var thumbnail = 1;
var price = 'Price';
var rating = 'rating';
//table to show all sql data
var AllrestaurantTable = "<table class = fixed style=width:100% border=1px>" +
"<tr>" +
"<td>" + "<a href = 'detailed_restaurant.html' target ='_blank'>" + "<img src ='" + thumbnail + "'style=width:100px;height:100px;></img>" + "</td>" +
"<td>" + "<a href = 'detailed_restaurant.html' target ='_blank'>" + restaurant_name + "</td>" +
"<td>" + location + "</td>" +
"<td>" + Description + "</td>" +
"<td>" + price + "</td>" +
"<td>" + rating + "</td>" +
"</tr>" +
"</table>";
table.insertAdjacentHTML('beforeend', AllrestaurantTable);
}
}
result();
<div id="result" class="row"></div>
</div>
You have to pass the search array in your result function.
function Search() {
var search = new Object;
search.restaurantName = document.getElementById("searchinput").value; //get input
var searchrestaurant = new XMLHttpRequest();
searchrestaurant.open("POST", Search_url, true);
searchrestaurant.setRequestHeader("Content-Type", "application/json");
searchrestaurant.onload = function () {
search_array = JSON.parse(request.responseText);
result(search_array);
}
searchrestaurant.send(JSON.stringify(search));
}
Hope this will work.

Empty Div tag issue for dynamically rendered table

I am creating dynamic table and appending it to Div tag on my .php page. On my .php page, I have dynamic buttons and if I click on any of the dynamic buttons, the dynamic table is rendered which has multiple headers and rows (for which I have written for loops with ajax requests). The issue is that, if i click on any of the dynamic buttons again, the current dynamic table data is appended to the previous dynamic table, instead I want to remove previously appended table data and render the current dynamic table data. I tried to empty the div tag but nothing seems working here. Hope I get some help, thanks in advance. Below are my .php and .js files:
.php file- I didnt post the function definition for get_Btns() as it is the basic php function to fetch data from the database:
<?php
function get_Btns() {
include "config.php";
$btns = $stmtDivision->fetchAll(PDO::FETCH_ASSOC);
foreach($btns as $btn){
echo "<input type='button' id='".$btn['divisionid']."' value='".$btn['division_name']."'
onclick=getData('".$btn['divisionid']."') >" ; echo "<br/>"; ?>
<script src="./user.js"></script>
<?php }
}
?>
<?php include "templates/header.php"; ?>
<div id="buttons_panel" style="text-align:center">
<?php echo get_Btns();?> </div>
<div id="div" class="divClass" ></div> <br/>
.js file:
function getData(value) {
document.getElementById("div");
var tableHtml = $('<table></table>');
var selectedManager = value;
var isEmpty = $('#div').empty();
// document.getElementById("div").innerHTML === "";
// document.getElementById("div").HTML === "";
// var isEmpty = $("#div").html() === "";
//$(".divclass").empty();
var teams = null;
$.ajax({
url: 'data.php',
method: 'post',
data: 'selectedManager=' + selectedManager,
async: false,
success: function(data) {
teams = JSON.parse(data);
}
});
for (var k = 0; k < teams.length; k++) {
const selectedteam = teams[k];
var selectedteamid = team[k].teamid;
var htmlth = "";
var html = "";
htmlth = "<tr>" + "<th id='thgrp' colspan='4' background-color: #013466;>" + teams[k].teamname + "</th>" +
"<th colspan='2' background-color: #62b8b6;>" + "<a href='Update.php?groupid=" + selectedteam.teamid + "' >" +
'Update Team member' + "</a>" + "</th>" + "</tr>" +
"<tr>" + "<th>" + "<img src='images/member.png'>" + "<b>" + "<div>" + 'Member' + "</div" + "</th>" +
"<th>" + "<img src='images/phone.png'>" + "<b>" + "<div >" + 'Phone' + "</div" + "</th>" +
"<th>" + "<img src='images/email.png'>" + "<b>" + "<div >" + 'Email' + "</div" + "</th>" + "</tr>";
tableHtml.append(htmlth);
var members = null;
$.ajax({
url: 'data.php',
method: 'post',
data: 'selectedteamid=' + selectedteamid,
async: false,
success: function(data) {
members = JSON.parse(data);
console.log(members);
}
});
for (var i = 0; i < members.length; i++) {
html += "<tr>" + "<td>" + members[i].name + "</td>" +
"<td>" + members[i].phone + "</td>" + "<td>" + members[i].email + "</td>";
}
tableHtml.append(html)
}
$("#div").append(tableHtml);
value = "";
}
Issue solved, I tried to empty the dynamic table that I have created instead of emptying the div tag on my html page. I did this earlier but I didn't do it properly. Thank you so much everyone for your time
This is the code:
tableHtml.attr('id', 'tableHtmlId');
$('#tableHtmlId').empty();

display multiple image into HTML table using jquery [duplicate]

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 can't show my array in JavaScript

I have some simple code in JavaScript. I was going to create code to add first name, last name and age of students from the client by click on "Add Student" button, and show the list of students including the one just added by clicking on the "Show Students" button.
The add action is successful, but when I click on "Show Students" button it just shows me a table without any information(First Name,Last Name,Age).
var students = new Array();
var i = 0;
function AddStudent()
{
var patt = /i[a-z]/;
var Fname = prompt("enter first name");
var Lname = prompt("enter last name");
var Age = prompt("enter age");
var std= {fname : Fname,lname : Lname,age : Age }
students[i++] =std;
}
function ShowStudents()
{
var table = "<table style='background-color:greenyellow; border:solid;'>";
table += "<tr><th>نام</th><th>نام خانوادگی</th><th>سن</th></tr>"
for( var j=0;j<students.length;j++)
{
table += "<tr>"
table += "<td>" + students[j].fname +"</td>"
table += "<td>" + students[j].lname + "</td>"
table += "<td>" + students[j].age + "</td>"
table +="</tr>"
}
table += "</table>";
document.getElementById("ShowStudents").innerHTML = table;
}
<input type="button" value="Add Student" onclick="AddStudent();"/>
<input type="button" value="Show Students" onclick="ShowStudents();"/>
<div id="ShowStudents"></div>
I think that your browser can not execute instructions without " ; " , so try to add it in this lines :
table += "<tr><th>نام</th><th>نام خانوادگی</th><th>سن</th></tr>"
for( var j=0;j<students.length;j++)
{
table += "<tr>"
table += "<td>" + students[j].fname +"</td>"
table += "<td>" + students[j].lname + "</td>"
table += "<td>" + students[j].age + "</td>"
table +="</tr>"
}
because for me it works like a charm.
i had some comment in my js page and useless functions.finally i clean the comment and useless functions and it worked!

Assigning ViewBag property in javascript

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.

Categories

Resources