Hello everyone I'm currently working on a ASP.NET MVC environment using C#, so right now I'm getting a table from a URL using AJAX and using C# to render it inside my cshtml.
Anyways right now I have a problem where I don't find a way to post data from a button since I'm using javascript mostly to do this I'm kind of lost.
<script>
$(document).ready(function(){
// code to read selected table row cell data (values).
$("#mydataTable").on('click','.btnSelect',function(){
// get the current row
var currentRow=$(this).closest("tr");
// get current row 1st table cell TD value
var col1=currentRow.find("td:eq(9)").html();
var data=col1;
alert(data);
});
});
</script>
Right now this is the script I'm using to get data from the row I want to get data from.
How can I submit this variable at the same time using AJAX to my Controller
I currently use this other script to send data to my controller but it takes the values out of <input> name="", the value I need to get is from a table I render using c# in my cshtml
<script>
function load() {
$.ajax({
url: '#myproject.Models.Base.RootDir()Controller/View',
type: 'post',
dataType: 'text',
contentType: 'application/x-www-form-urlencoded',
data: $("#myForms").serialize(),
success: function (response) {
$('#divToDisplayData').html(response);
},
error: function (error) {
console.log(error);
}
});
}
</script>
If anyone has a question please ask, I'll be around all day
And this is the button I use to submit data
<button class="btnSelect">Seleccionar</button>
You can Pass data inside your form, you just need to take one hidden field inside your form, so when you button clicked, set the value of that hidden field.
<form id="myForms">
//your controlls
//one extra hidden field
<input type="hidden" id="cellValue" />
</form>
Now on button click, set the value of above hidden field.
<script>
$(document).ready(function(){
// code to read selected table row cell data (values).
$("#mydataTable").on('click','.btnSelect',function(){
// get the current row
var currentRow=$(this).closest("tr");
// get current row 1st table cell TD value
var col1=currentRow.find("td:eq(9)").html();
var data=col1;
$('#cellValue').val(data);
});
});
</script>
so finally, when your load() method call, in the $("#myForms").serialize() you will get your cell value in the hidden field control.
Here, you need to take care that whenever you pass html from view to controller, controller will deny your request because it is not safe content. so you need to use [ValidateInput(false)] on your action as below.
public class YourController: Controller{
[ValidateInput(false)]
public ActionResult View()
{
return View();
}
}
Related
This is the screen
the php file named "fetching_book_title_for_barcode.php".
<?php
require_once('db.php');
$response=array();
$sql="select book_title from book where barcode_id LIKE '%".$_POST['value']."%'";
$result=mysql_query($sql);
if(mysql_num_rows($result)){
$book_title=mysql_fetch_assoc($result);
$response["book_title1"]=$book_title;
}
echo json_encode($response);
?>
Here is the java script file with some ajax call.
var searchTimeout;//Timer to wait a little before fetching the data
$("#barcode_id_textBox").keyup(function() {
var searchKey = this.value;
clearTimeout(searchTimeout);
searchTimeout = setTimeout(function() {
barcodeTextboxFill(searchKey);
}, 400); //If the key isn't pressed 400 ms, we fetch the data
});
function barcodeTextboxFill(searchKey){
$.ajax({
url: 'fetching_book_title_for_barcode.php',
type: 'POST',
dataType: 'json',
data: {value: searchKey},
success: function(data) {
$("#book_title_textBox").val(data);
}
});
}
The HTML
<input type="text" id="barcode_id_textBox">
<input type="text" id="book_title_textBox">
`I am making Library management system for my university according to their requirements.
In MySql database i have a table of book in which i inserted the book records in which one of the column is for barcode id and one of the column is for book title.
I have an html page on which i have 2 inline textboxes, one of which is for barcode id and the other one is for book title.
Now i want that when barcode id is entered then at the same time the book title fetched from the database and showed in the book title's textbox.
I tried alot on it but i didn't find any solution. I tried it through ajax but i didn't get the required answer. what is the problem in it?
everyone help would be appreciated.
Thanks in advance.
Use AJAX and jQuery.
In your text box add an onChange like so, <input type="text" id="barcodeTextBox" onChange="BarcodeBoxFill()">, the onChange will call the JS function BarcodeBoxFill() whenever the text box is altered.
Then the JS function should take the input from the box, var text = $('#barcodeTextBox').val()
Then on the same function should be your AJAX call which passed the value of the text box as a parameter. Then in the page the AJAX calls will be some SQL that gets the right value for the other box, (in this case the book title). As the success part of the AJAX you can change the value of the other text box,
success: function(data) {
$('#bookTitleTextBox').val(data);
}`
I have a simple PHP form containing two (2) textboxes a dropdownlist and finally a SUBMIT button. In this form, before hitting the Submit button, the user has to select an item from the dropdown list. Upon selection of an item from the dropdown list, it's onchange event fires and populates the other 2 textboxes with some data fetched from the database.
The code to fetch data:
var wd_pid = document.getElementById("ddlUnder").value;
var dataString = 'wdpid='+ wd_pid;
$.ajax({
type: "POST",
url: "ldd_pop_wd_pdata.php",
data: dataString,
cache: false,
success: function(result){
var v1= result.substring(0,result.indexOf('='));
var v2= result.substring(result.indexOf('=')+1);
$("#txtMLI").val(v1);
$("#txtMLIURL").val(v2);
}
});
The above code works perfectly, populating the two textboxes with correct data. This forms 'action' attribute points to an another php page containing logic to save form data into the database. My problem begins in the next page. After form submit, in the next php page, the post variables $_POST['txtMLI'] & $_POST['txtMLIURL'] are empty.Why is it so?? Please advise what's going wrong.
Thanks in advance.
The data part of your AJAX call is not properly formatted. It is supposed to be formatted in JSON as follows.
{ wdpid: wd_pid }
And not
"wdpid=" + wd_pid
I am using:
Python 3.4
Flask 10.1
SQLAlchemy 0.9.6
JQuery 2.1.1
I'm working on a forum application that will show a table of forum threads based on tags selected by the user. The tags are a list of on/off buttons generated as per the below Jinja2 template. (Should be around 8, max 16 tags).
<UL class="ForumTagList">
{% for Tag in Forum.ForumTags.filter_by(Visible=True): %}
<li Class="ForumTag VisibleTrue" id ="liTag{{Tag.TagID}}" >
<input id="{{Tag.TagID}}" type="hidden" value="1" name="Name{{Tag.TagID}}"></input>
<DIV class="Tag{{Tag.TagID}}" onclick="toggle_tag('{{Tag.TagID}}');"> {{Tag.Name}}</DIV>
</li>
{% endfor %}
</UL>
There is a JS script that manages the changing of the values to 0 or 1.
The table will be loaded by an AJAX call as per below. It will initially load an unsorted table but the user will be able to refresh to see if new threads appear.
<script type="text/javascript">
$(document).ready(function(){
ThreadTableRefresh();
});
function ThreadTableRefresh(){
$('#ThreadsHolder').load('{{Forum.ForumID}}/ForumThreads');
}
</script>
<div id="ThreadsHolder">
</div>
I understand from reading the documentation on JQuerys Load Method that I can submit a second argument to the .load() method as an object. I hope to submit the on/off values from the users selection, which will then be used to generate the table only showing the tags the user wants.
I am very new to HTML and JQuery, would anyone be able to point me in the right direction as to how to take the various values from those HTML controls and post them as a list or dictionary to a Flask template?
If you need any addition information, please let me know.
You can send a dictionary or json to your flask template. For each TagID, there is a 1 or 0 value, e.g. {1:0, 2:0, 3:1, 4:0}.
Check out the .ajax jquery function to send a json object to your flask route. This should get you started.
Step by step:
click the refresh button
for each tag, add the id and toggle (1/0) value to a dictionary
convert the dictionary to a json object
use ajax function to send the object to your flask route
flask route takes the values, sends back the new html data
the ajax function will substitute the new html upon success
Javascript
$('#refresh-button').click(function() { //selector for refresh button
data = {}
$('input').each(function(){ //might need more specific selector
id = $(this).attr('id')
toggle = $(this).val()
data[id] = toggle
});
data = JSON.stringify(data);
$.ajax({
url: '/YourFlaskRoute'
type: 'POST',
data: data,
contentType: 'application/json;charset=UTF-8',
cache:false,
success: function (response) {
$(".ForumTagList").html(response); //your flask route needs to send back the html for just your list items
},
error: function(response){
alert('Error refreshing forum items')
}
});
});
Flask
#myblueprint.route('/YourFlaskRoute', methods = ['POST'])
def refresh_tags():
if request.method == 'POST':
data = request.json
#access your data
for key, value in data.items():
key = id
value = id
# run your query
tags = ...
#send back your list items template
return render_template('list_items.html', tags = tags)
I've an html form with multiple elements. Now, in particular to which I want your attention are two dropboxes and beside that an "add" button.so, once the user makes selection from the dropdown and presses the "add" button, it'll add the data to a table and that table will show up just below those dropboxes.So, basically user can add multiple data through the dropdowns and see it in a table. Now, the problem arises when I want to retrieve the data from this table when the form gets submitted. I'm not sure if $_PHP[''] would be able to fetch the data from the table I created.
So, as an alternative I'm trying to pass the data using AJAX when form gets submitted!
HTML:
<form name="input" id="formToSubmit" action="process-host.php" method="post" enctype="multipart/form-data">
/* Form data goes here*/
<input type="button" class="submit" value="Submit Request" onclick="valField(this.form); "/>
valField() method validates
and submits the form.
JS:
function valField(form) //field validation for the form before submit
{
/*Validation code goes here*/
//if(validated){
$("#formToSubmit").submit(function(e) { //this.submit(function(e)){
e.preventDefault();
var tableForNew = new Array(); //to store the infoDisplayTable data
$('#infoDisplayTable1l tr').each(function() {
tableForNew.push($(this).find("td:first").html());
tableForNew.push($(this).find("td:second").html());
});
// Get all INPUT form data and organize as array
var formData = $(this).serializeArray();
// Encode with JSON
var tableForNew1 = JSON.stringify(tableForNew);
// Add to formData array
formData.push({name: 'tableForNew', value: tableForNew1});
// Submit with AJAX
$.ajax({
url: "./process-host.php",
data: formData,
type: 'post',
success: function() {
alert("BOOM! IT WORKED;");
}
});
});
On the server side, in process-host.php,
$tableForNew = json_decode($_POST['tableForNew']);
This obviously isn't working out, so when I'm debugging with Firebug, I can see that it is not going inside the submit function. It just submits the form, without going through inside code! and thats why its not posting any table data to server and gives error notice Undefined index: tableForNew .
So, what can I do here to make it work? any suggestions?
When you use an inline onclick handler you need to return false or else the default action will be triggered (submitting the form).
However, the way you have this setup right now the valField function will just define the submit handler and return - which means that even if you return false you will have to click the button a second time to trigger the submit event, which will also fire the valField function and redefine the submit handler (inception!).
You should remove the onclick handler you have on button element, move the submit handler out of the valField function, and only do the ajax call if the form is valid.
Well, making AJAX call while submitting the form didn't workout for me after all, but I did succeed in fetching the data from HTML table on the server side somehow! The solution that worked for me now is adding hidden fields to the form.Basically I'm adding hidden <input> fields to form when user inputs values and presses "Add" button, so it's in "Add" button's onClick event handler! Here's how that function looks like,
function addData1(){
if($("#consumerDropDown").val() != "" && $("#authenticationTypeDropDown").val() != "")
{
$("#infoDisplayTable1").show();
$("#infoDisplayTable1").attr("disabled", false);
$("#infoDisplayTable1").append("<tr><td >"+$("#consumerDropDown").val()+"</td><td>"+
$("#authenticationTypeDropDown").val()+"</td></tr>");
$("#tester").append("<input type='text' value='" +$("#consumerDropDown").val() + "----->"+$("#authenticationTypeDropDown").val() + "' name='dTable1"+ counter1+ "'>");
counter1++;
}
else
{
alert("Please make a valid selection from a drop-down before adding it to the list!");
}}
Here,note that I've defined counter1 as globel variable in JS file.Tester is id assigned to a <div> tag with attribute display:none. More on, I'm assigning name attribute of <input> tag dynamically(for example,here it'd be dTable10, dTable11 etc.), so it'd be easier to access it on server side! And finally just before submitting the form I'm passing that counter1 variable to hidden field just like how I did it above, $("#tester").append("<input type='text' name='counter1' value='"+counter1+"'>"); form.submit();
Server side:
$counterA = intval($_POST['counter1']);
for($i=0;$i<$counterA;$i++)
{
$createReq['comment'] .= $_POST["dTable1"."{$i}"]."\n";
}
Here basically I'm appending this values to a string variable. It's gonna loop through each item, and gonna append to the variable. So, this worked for me as a solution for now! But, I'd have been more satisfied if the AJAX call would had worked while submitting the form(what I was trying to do before)!
I'm making an webpage using ASP.NET MVC.
I have the following input hidden definied:
<%=Html.Hidden("inputHiddenSelectedMenuId") %>
And i set its value in this js function:
function SetSelectedMenu(id) {
$('#inputHiddenSelectedMenuId').val(id);
}
After a make a postback in the js init function i want to use the value set in the input hidden but the value is string empty.
$(document).ready(function() {
$('div.nav > a').removeClass('active');
var id = $('#inputHiddenSelectedMenuId').val();
if (id != "") {
$("#" + id).addClass('active');
}
});
Can anyone give a hint why this is happening?
You are trying to read the value of the input in javascript. When you click a button on a form and it does a post back your page is being reloaded and the javascript re-runs every time the page is loaded. If all you are doing is reading the value of an input in javascript you do not need to perform a postback.
$('#inputHiddenSelectedMenuId').bind('click', function ()
{
var id = $('#inputHiddenSelectedMenuId').val();
// do stuff with it.
});
The click function will be performed without a postback.
Now, if you are trying to read the contents of the hidden field from within MVC after a post then this is a different issue. You will have to pull it from the form data through model binding (or reading it directly through the Request.Form[] collection.
public ActionResult SomeActionToPostTo(int inputHiddenSelectedMenuId)
{
//model binding should find the form field called inputHiddenSelectedMenuId and populate the argument in this method with it's value. If it's not an integer then just change the type of the argument to the appropriate type.
}