I have a method in my controller
def returnJames = {
JSONObject jsonObject = new JSONObject()
jsonObject.put("name","James")
return jsonObject
}
and then I have a view:
<html>
<!--import gsp that has all the jquery imports-->
<script>
function changeName()
{
$.ajax({
url:"<g:createLink url="[action:'returnJames',controller:'mycontroller']" />",
dataType: "json",
asnyc: false,
success: function(data) {
$('mytextbox').val(it.name)
}
});
}
</script>
<g:form controller="mycontroller" method="post" >
<g:textField name="mytextbox" value="" />
<button name = "mybutton" id = "mybutton" onclick="changeName()">change name</button>
</g:form>
</html>
However it just tries to change the page to the index view of the mycontroller controller which doesn't exist. How can I get it to just fill in the textbox with "James"?
User render instead of return
render jsonObject
and change in jQuery
success: function(data) {
$('#mytextbox').val(data.name)
}
change button to
<input type="button" id = "mybutton" onclick="changeName()" value="change name"/>
Related
I am trying to capture the data from checkbox by assigning value in jquery and passing it to backend each time search is run by the user. It is not working for me, tried several ways.
Use case: As a user I would like to search and be able to check for various search options.
template:
$('a#process_input').bind('click', function () {
$.getJSON('/background_process', {
checkbox1: $('input[name="checkbox1"]').val(),
input_search: $('input[name="input_search"]').val(),
},
function (data) {
ul.empty();
$.each(data.result, function (index, element) {
...
... <some irrelevant code...>
<input type=text size=40 name=input_search>
<a href=# id=process_input>
<button class='btn btn-default'>Submit</button>
</a>
</form>
<form method="POST" action="/">
<p>Please select allergy options below:</p>
<input type="checkbox" name="checkbox1"/>Allergy 1
backend
#app.route('/background_process', methods=['GET', 'POST'])
def background_process():
try:
checkbox1 = request.args.get("something")
search_word = request.args.get('input_search', 0, type=str)
if search_word:
return jsonify(result=yummly_search(search_word, checkbox1))
else:
return jsonify(result='Try again.')
except Exception as e:
return str(e)
I am not comfortable with getJSON function but the other way to do it is ajax. Here is a runnable code, I hope it helps:
html:
<input type=text size=40 name="input_search">
<a href=# id=process_input>
<button class='btn btn-default'>Submit</button>
</a>
<p>Please select allergy options below:</p>
<input type="checkbox" name="checkbox1"/>Allergy 1
<div id="login_result"></div>
javascript:
<script>
$(document).ready(function () {
$("#process_input").bind('click', function () {
var login_result = $('#login_result');
var input_search = $('[name="input_search"]').val();
var checkbox1 = $('[name="checkbox1"]').is(":checked");
console.log(input_search);
console.log(checkbox1);
var list = new FormData()
list.append("input_search", input_search)
list.append("checkbox1", checkbox1)
var urlBackgroundProcess = "{{ url_for('background_process') }}";
var ajaxRequest = $.ajax({
type: "POST",
url: urlBackgroundProcess,
data: list,
contentType: false,
cache: false,
processData: false,
success: function (msg) {
login_result.html(msg.data);
console.log("AJAX ok 2!");
}
});
});
});
</script>
and the flask back end:
#app.route('/background_process',methods=['GET','POST'])
def background_process():
msg=''
if request.form.get("input_search"):
msg=('I got that search pattern at the back end: \'%s\' \n the checkbox value is set to: \'%s\' ') \
% (request.form.get("input_search"),request.form.get("checkbox1"))
else:
msg='I got the Ajax call but cannot read the data, try again! :('
return jsonify(data=msg)
Programming a ASP.net webapp to insert an entry into a database on form submit.
I've tried numerous configurations of find() and children() and they either
1) error
2) pass empty strings instead of what I type
This one errors like this:
Whats the correct way to select the individual children of myform?
Javascript (the first block here is the code I'm asking about)
var entry_array = [];
entry_array[0] = $('#myform').children('#01').css().text();
entry_array[1] = $('#myform').children('#02').css().text();
entry_array[2] = $('#myform').children('#03').css().text();
entry_array[3] = $('#myform').children('#04').css().text();
$(document).ready(function () {
$("#myform").submit(function () {
alert("Function ran");
$.ajax({
url: 'Home/SubmitEntry', //(rec)= Controller's-name
//(recieveData) = Action's method name
type: 'POST',
datatype: 'json',
traditional: true,
data: { 'entry_array': entry_array },
success: function(response) {
console.log(response);
},
error: function (response) {
console.log(response);
}
});
alert("Function finished running");
});
});
Controller
[HttpPost]
public ActionResult SubmitEntry(List<String> entry_array)
{
String firstname = entry_array[0];
String lastname = entry_array[1];
String town = entry_array[2];
String order = entry_array[3];
knightsEntities db = new knightsEntities();
int nextiD = 0;
nextiD = db.Apprentenceship_Sheet.ToList().Last().id + 1;
var newApprentenceship_Sheet = new Apprentenceship_Sheet();
newApprentenceship_Sheet.first_name = firstname;
newApprentenceship_Sheet.last_name = lastname;
newApprentenceship_Sheet.hailed_town = town;
newApprentenceship_Sheet.order = order;
newApprentenceship_Sheet.id = nextiD;
db.Apprentenceship_Sheet.Add(newApprentenceship_Sheet);
db.SaveChanges();
return View();
}
View
<script src='https://code.jquery.com/jquery-3.1.0.min.js'></script>
<script src="~/scripts/custom.js"></script>
#{
ViewBag.Title = "Home Page";
}
<div>
<form id= "myform" method="post">
First_name:<br>
<input type="text" id="01" name="firstname"><br>
Last_name:<br>
<input type="text" id="02" name="lastname"><br>
Town:<br>
<input type="text" id="03" name="town"><br>
Order:<br>
<input type="text" id="04" name="order"><br>
<br>
<input type='submit' id="05" name="Submit">
</form>
</div>
You can get the values of the text boxes directly by using $('#01').val(), or if you want refer it with reference to your form. You can use $('#myform').find('#01').val(). It will give the value of the text-box. Here is the jsfiddle for u.
$('#myform').find('#01').val()
$('#01').val()
http://jsfiddle.net/71weztcn/
This is my controller.
public class HomeController : Controller
{
public static string commString = "";
public HomeController()
{
FWUtility.connString = "data source=.;initial catalog=northwind;uid=sa;password=123";
}
public ActionResult Index()
{
return View();
}
public static DataTable GetData(string customerID)
{
string strFilter = "'" + customerID + "%'";
commString = "select * from customers where CustomerID like " + strFilter;
return FWUtility.GetDataTable(commString);
}
This is the view.
<script type="text/javascript">
function buttonClick() {
var value = $('#text1').val();
alert('#HomeController.GetData("D").Rows.Count.ToString()');
}
</script>
<input type="text" id="text1" value="A" />
<input type="text" id="text2" />
<input type="button" value="Show" id="button1" onclick="buttonClick()" />
I want to catch the value which is stored in the textbox and display it in the alert box, where I have mentioned "D". In my controller I have a sql query assigned.And here I am calling the controller. My out put will be suppose I put "A" inside the text box and click the button, i will get the count of all the names starting with letter "A". Like this
It's not clear from the question, but assuming you want more than a simple alert(value), then:
I suggest that you add an additional action to go with the GetData function to return row count directly:
public ActionResult GetDataRowCount(string id)
{
var count = GetData(id).Rows.Count;
return new JsonResult
{
Data = new { count },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
then you can use jquery ajax to get this value from the controller:
<script type="text/javascript">
function buttonClick() {
var value = $('#text1').val();
$.get({
url: '#Url.Action("GetDataRowCount", "Home")',
data: { id = value },
success: function(result) {
alert(result.count);
}
});
}
</script>
<input type="text" id="text1" value="A" />
<input type="button" value="Show" id="button1" onclick="buttonClick()" />
Well, done it at last. Here is the solution.
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script type="text/javascript">
function buttonClick() {
var value = $('#text1').val();
$.ajax({
url: '../Home/GetData',
method: 'POST',
data: { customerID: value },
success: function (data) {
result = data;
alert(result);
},
});
}
</script>
<input type="text" id="text1" value="A" />
<input type="button" value="Show" id="button1" onclick="buttonClick()" />
can anyone tell how to add tooltip for dynamically created button.In my page i have one submit button,and it will create dynamic buttons with respect to the xml data.i want to create tooltip for this buttons.here is my code
<script>
$(document).ready(function () {
$("#Submit").click(function () {
$.ajax({
type: "GET",
url: "mars.xml",
dataType: "xml",
success: function (xml) {
$(xml).find('student').each(function () {
var Name = $(this).find('name').text();
var Mark = $(this).find('marks').text();
var Sid = $(this).find('id').text();
var student_id = "#"+$(this).attr("id");
$("#content").append("<li><input type='button' class='dyna_btn' id = '"+$(this).attr("id")+"' value='"+Name+"'/></li>");
var hue = '#'+(0x1000000+(Math.random())*0xffffff).toString(16).substr(1,6);
$(student_id).css('color', hue);
$("#content").append('<li>' + Sid + '<li>');
});
}
});
});
});
$(document).on("click", ".dyna_btn", function() {
alert("button"+$(this).attr("id"));
console.log("button clicked");
});
</script>
<body>
<form id="From1" method="post">
<input type="button" value="submit" name="Submit" id="Submit" />
<div id="content">
</div>
</form>
</body>
Just add title="" attribute in same way like this:
<input type='button' class='dyna_btn' id = '"+$(this).attr("id")+"' value='"+Name+"' title='"+Name+"' />
In the Index view I just have a button with a javascript function for when it's clicked:
<script>
function AddCat() {
$.ajax({
type: "GET",
url: '#Url.Action("AddCategory")',
data: {},
});
}
</script>
#Html.DropDownList("Languages", new SelectList(Model.lstLanguages, "LanguageID", "Name", Session["langID"] ?? "1"), new { id = "ddlLanguages" })
<div id="categoriesPlace"></div>
<input type="button" id="btnAddCategory" onclick="AddCat()" value="AddCategory" />
When I click on the button, as you see I should be redirected to the AddCategory action, which adds a record in the database and returns the AddCategory view. The problem is that when it reaches the drop-down in my AddCategory view, it goes straight to the Addbtn_CLick() function as if it's clicked and then it redirects me to the Index action. Can you explain this behavior?
So, here is my CategoryController:
public class CategoryController : Controller
{
public ActionResult AddCategory()
{
CategoryViewModel vm = new CategoryViewModel();
vm.AddNewCategory();
return View(vm);
}
public ActionResult AddCategoriesLanguages(int catID, int lanID, string title, string shrtDescription, string description)
{
CategoryViewModel vm = new CategoryViewModel();
vm.AddCategoriesLanguages(catID, lanID, title, shrtDescription, description);
return RedirectToAction("Index");
}
}
And, here is my AddCategory view:
#model Onion.Web.ViewModels.CategoryViewModel
#{
ViewBag.Title = "AddCategory";
}
<h2>AddCategory</h2>
#Html.DropDownList("Languages", new SelectList(Model.lstLanguages, "LanguageID", "Name",#HttpContext.Current.Session["langID"]),new { id = "ddlLanguages" })
<br />
<label for="txbTitle">Title:</label>
<input type="text" id="txbTitle"/>
<br />
<label for="txbShortDescription">Short Description:</label>
<input type="text" id="txbShortDescription" />
<br />
<br />
<input type="button" id="btnAdd" onclick="btnAdd_Click" value="Add" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script>
function btnAdd_Click() {
$.ajax({
type: "GET",
url: '#Url.Action("AddCategoriesLanguages")' + '?catID=' +#Model.newCategoryID +'&lanID=' + $("#ddlLanguages").val() + '&title=' + $('#txbTitle').val() + '&shrtDescription=' + $('#txbShortDescription').val() + '&Description=' + $('#txbDescription').val(),
data: {}
});
}
</script>
In your AddCategory view, try changing your button's onclick attribute to include the function name and parenthesis as shown below:
<input type="button" id="btnAdd" onclick="btnAdd_Click()" value="Add" />
I am not 100% sure if that is the issue, but it stood out to me.