I have this code snippet where I am passing data to another jsp file.
Javascript
$(document).ready(function() {
$("#click").click(function() {
name = $("#name").val();
age = $("#age").val();
$.ajax({
type : "POST",
url : "pageTwo.jsp",
data : "name=" + name + "&age=" + age,
success : function(data) {
$("#response").html(data);
}
});
});
});
HTML
<body>
Name:<input type="text" id="name" name="name">
<br /><br />
Age :<input type="text" id="age" name="age">
<br /><br />
<button id="click">Click Me</button>
<div id="response"></div>
</body>
and in pageTwo.jsp, my code is
<%
String name = request.getParameter("name");
String age = request.getParameter("age");
out.println(name + age);
%>
but this is not working.Is any mistake in my Jquery ?.Can any one please help me?.
$("#click").click(function(e) {
// e.preventDefault();
...
return false;
});
and of course install firebug or use chrome default developer tools (f12). open console and run the code.
$(document).ready(function () {
$("#click").click(function () {
name = $("#name").val();
age = $("#age").val();
$.ajax({
type: "POST",
url: "pageTwo.jsp",
data: "{'name':'" + name + "','age':'" + age + "'}",
contentType: "application/json",
async: false,
success: function (data) {
$("#response").html(data.d);
}
});
});
});
Related
I am working with select2 to display the data return from the API. However, the data didn't manage to load out.Am I doing something wrong? Any ideas how to fix this?
HTML:
<select class="js-example-basic-single form-control select2 select2-hidden-accessible" id="user" name="user_id" autocomplete="off" required="required">
<option value="">Please select</option>
</select>
script:
var url = "{{env('API_URL')}}";
var username = null;
$(".select2").select2({
placeholder: "Please select",
width: null,
ajax: {
dataType: "jsonp",
method: "GET",
data: function (term) {
username = term.term;
return {"username": username};
},
url: url+"user/search/username?",
results: function (data) {
return {
results: data.result.users
};
},
},
formatResult: function (option) {
return "<option value='" + option.id + "'>" + option.username + "</option>";
},
formatSelection: function (option) {
return option.id;
}
});
result return from API:
result : [{"users":["[object] (App\\User: {\"username\":\"Kaki\",\"id\":123456})","[object] (App\\User: {\"username\":\"(Alan)\",\"id\":123457})","[object] (App\\User: {\"username\":\"Alex\",\"id\":123458})","[object] (App\\User: {\"username\":\"Sky\",\"id\":1234569})","[object] (App\\User: {\"username\":\"Kvin\",\"id\":123460})"]}] []
One thing is your JSON return from API who is not well formatted.
[{
"users":[
"[object] (App\\User: {\"username\":\"Kaki\",\"id\":123456})",
"[object] (App\\User: {\"username\":\"(Alan)\",\"id\":123457})",
...
]
}]
should be
[{
"users":[
{"username":"Kaki","id":123456}),
{"username":"(Alan)","id":123457}),
...
]
}]
I don't know what is Select2 version you use, but > 4 is advice.
Use functions templateResult and templateSelection is better, later you can return HTML for nicer rendering.
You can use this snipplet demo.
$(".select2").select2({
placeholder: "Please select",
width: null,
ajax: {
dataType: "json",
method: "GET",
url: function (params) {
// return 'url+"user/search/username?' + params.term;
// Fake url to make demo working, use upper line
return 'http://ip.jsontest.com/';
},
processResults: function (data) {
// Use this function to convert api result to Select2 result
// return {"results":data.users};
// Build fake answer for demo
return {"results":[{"username":"Kaki","id":123456},{"username":"(Alan)","id":123457}]};
},
},
templateResult: function (dataRow) {
if (dataRow.loading) return dataRow.text;
return dataRow.username;
},
templateSelection: function (dataRow) {
return dataRow.username;
}
});
.select2 {
width:50%
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/select2/4.0.1/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/select2/4.0.1/js/select2.full.js"></script>
<select class="form-control select2" id="user_id" name="user_id" autocomplete="off" required="required">
<option value="">Please select</option>
</select>
$(".select2").select2({
placeholder: "Please select",
width: null,
ajax: {
dataType: "json",
method: "GET",
url: function (params) {
// return 'url+"user/search/username?' + params.term;
// Fake url to make demo working, use upper line
return 'http://ip.jsontest.com/';
},
processResults: function (data) {
// Use this function to convert api result to Select2 result
// return {"results":data.users};
// Build fake answer for demo
return {"results":[{"username":"Kaki","id":123456},{"username":"(Alan)","id":123457}]};
},
},
templateResult: function (dataRow) {
if (dataRow.loading) return dataRow.text;
return dataRow.username;
},
templateSelection: function (dataRow) {
return dataRow.username;
}
});
.select2 {
width:50%
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/select2/4.0.1/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/select2/4.0.1/js/select2.full.js"></script>
<select class="form-control select2" id="user_id" name="user_id" autocomplete="off" required="required">
<option value="">Please select</option>
</select>
I am trying to get jQuery autocomplete in a textbox. But I don't seem to be able to display the data from my JsonResult in the view, I checked with firebug and verfied that the data is transferred from server, just doesn't disply in the TextBox. I don't get any errors.
Here's my code :
public JsonResult search(string term)
{
// string prefixText =SearchString;
var FamilyLastName = _repository.FamilySearch(term);
var data=FamilyLastName.ToList();
return Json(data);//.Select(x => new { label = x, ID = x }));
}
#using (Html.BeginForm())
{
<label for="SearchString">My Autocomplete:</label>
<input class="form-control" type="text" name="SearchString" id="SearchString" autocomplete="off" />
}
<script type="text/javascript">
$(document).ready(function () {
var param = { "searchstring": $("#SearchString").val() };
$("#SearchString").autocomplete({
autoFocus: true,
source: function (request, response) {
// call your Action
$.ajax({
url:'search?term=' + $("#SearchString").val(),
// data:"{'term':'" +$("#SearchString").val() + "'}",
dataType: 'json',
method: "post",
contentType: "application/json; charset=utf-8",
success: function (data) {
return{
label:data.FamilyLastName
};
},
select:
function (event, ui) {
$('#SearchString').val(ui.item.label);
return false;
},
});
},
minLength: 1,// requ
What am I missing here? I'm trying to pass 2 fields(CustomerID and CompanyName) from my view into my controller. When I put a break point on my controller's action, both custID and Company name are null. I'm sure whatever I'm missing is easy but I'm just not getting into Angular. Any help would be greatly appreciated. Thanks!
HTML
<input type="text" class="form-control" ng-model="new.CustomerID" />
<input type="text" class="form-control" ng-model="new.CompanyName" />
Javascript
$scope.AddCustomer = function () {
debugger;
var urlPost = "/Home/SaveCustomer/";
console.log($scope.new);
alert(urlPost);
$http({
method: 'POST',
url: urlPost,
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
data: { custID: $scope.new.CustomerID, CompanyName: $scope.new.CompanyName }
}).success(function() {
alert('Update Successfully!');
});
}
C#
[HttpPost]
public void SaveCustomer(string custID, string CompanyName)
{
}
EDIT
A few weeks after this was posted and an answer was accepted, I found an easier way to accomplish this. Here is a code sample:
HTML
<input type="number" placeholder="CustomerID" ng-model="newCustomer.CustomerID" class="form-control" style="width: 130px" required/>
<input type="text" placeholder="Customer Name" ng-model="newCustomer.CustomerName" class="form-control" style="width: 200px" required />
<input type="text" placeholder="Email" ng-model="newCustomer.CustomerEmail" class="form-control" style="width: 200px" required />
JavaScript
$scope.newCustomer = {
CustomerID: '',
CustomerName: '',
CustomerEmail: ''
};
$scope.addCustomer = function () {
$http.post("/Home/GetCustomer",
{
customerID: $scope.newCustomer.CustomerID,
customerName: $scope.newCustomer.CustomerName,
customerEmail: $scope.newCustomer.CustomerEmail
}).error(function (responseData) {
alert(responseData);
})
.success(function () {
alert('Updated Successfully');
});
C# Controller
[HttpPost]
public void GetCustomer(int customerID, string customerName, string customerEmail)
{
//do something with values
}
I mean your problem is because the binding that web api uses there is base on querystring, so please update your code, I do an example:
public class UsersController : ApiController
{
[HttpPost]
[Route("Users/Save/{custID}/{CompanyName}")]
public string Save(string custID, string CompanyName)
{
return string.Format("{0}-{1}",custID, CompanyName);
}
}
And the html:
<body ng-app="myApp">
<div ng-controller="myController">
<h1>Demo</h1>
<input type="button" value="Save" ng-click="AddCustomer()" />
</div>
<script src="~/Scripts/angular.js"></script>
<script>
var app = angular.module("myApp", []);
app.controller("myController", function($scope, $http) {
$scope.new = {
CustomerID: "CustId1",
CompanyName: "Company 1"
}
$scope.AddCustomer = function () {
var urlPost = "/Users/Save/" + $scope.new.CustomerID + "/" + $scope.new.CompanyName
$http({
method: 'POST',
url: urlPost,
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).success(function () {
alert('Update Successfully!');
});
}
});
</script>
</body>
And if I test:
Regards,
make these changes :
//either define parent object scope only
$scope.new = {}
//or if you want to define child object too . May be to show some default value .
$scope.new = {
CustomerID: '', //empty or may be some default value
CompanyName: ''
}
I'm using the MVC4 Ajax helper functions on a form and I'd like to submit the form from script.
The problem is when I call the submit function, it does not load into the proper div. Any thoughts?
#using (Ajax.BeginForm("NewGame", "Home", new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "targetDiv" }, new { id = "newGameForm" }))
{
<input type="hidden" name="client_seed" id="client_seed" />
<input type="submit" value="New Game" id="NewGameButton" />
<a class=button onclick="$('#newGameForm').submit();">New Game</a>
}
Clicking the standard submit button load the results of the call into the targetDiv. Clicking on the anchor replaces the current div.
The key is to prevent default browser behavior via .preventDefault() or to return false at the end of the event handlers.
This is how I'd do it:
<div id="targetDiv"></div>
#using(Html.BeginForm("NewGame", "Home", FormMethod.Post,
new { id = "newGameForm" }))
{
<input type="hidden" name="client_seed" id="client_seed" />
<input type="submit" value="New Game" id="NewGameButton" />
}
<script type="text/javascript">
$(document).ready(function () {
$("#newGameForm").on("submit", function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr("action"),
data: $(this).serialize(),
type: $(this).attr("method") // "POST"
})
.done(function(result) {
$("#targetDiv").html(result);
})
.fail(function((jqXHR, textStatus, errorThrown) {
// handle error
});
});
});
</script>
If you insist on using an anchor <a>...
New Game
<script type="text/javascript">
$(document).ready(function() {
$("#submit-link").on("click", function(e) {
e.preventDefault();
$("#newGameForm").submit();
});
$("#newGameForm").on("submit", function(e) {
e.preventDefault();
$.ajax({
...
});
});
</script>
Edit There is also an AjaxHelper.ActionLink method. If you're already using the AjaxHelper in other parts of your code you might want to stick with that.
Pseudo Code.
<a class=button onclick="PostAjax();">New Game</a>
function PostAjax(){
$.ajax({
url:"Home/NewGame",
data:$('#newGameForm').serialize(),
DataType:"HTML", // assuming your post method returns HTML
success:function(data){
$("#targetDiv").html(data);
},
error:function(err){
alert(err);
}
})
}
This similar to Question https://stackoverflow.com/questions/13693170/changed-version-of-knockout-js
I would like move the code from jsfiddle to local system for testing. The code works for adds, checked, delete. But, what it does not do is load the fake data from within the model.js. I have changed /echo/json. to local url. What else do I need to do? Using latest firefox.
model.js >>>>
$(document).ready(function() {
var fakeData = [{
"title": "Wire the money to Panama",
"isDone": true},
{
"title": "Get hair dye, beard trimmer, dark glasses and passport",
"isDone": false},
{
"title": "Book taxi to airport",
"isDone": false},
{
"title": "Arrange for someone to look after the cat",
"isDone": false}];
function Task(data) {
this.title = ko.observable(data.title);
this.isDone = ko.observable(data.isDone);
}
function TaskListViewModel() {
// Data
var self = this;
self.tasks = ko.observableArray([]);
self.newTaskText = ko.observable();
self.incompleteTasks = ko.computed(function() {
return ko.utils.arrayFilter(self.tasks(), function(task) { return !task.isDone() && !task._destroy });
});
// Operations
self.addTask = function() {
self.tasks.push(new Task({ title: this.newTaskText() }));
self.newTaskText("");
};
self.removeTask = function(task) { self.tasks.destroy(task) };
self.save = function() {
$.ajax("/ds", {
data: {
json: ko.toJSON({
tasks: this.tasks
})
},
type: "POST",
dataType: 'json',
success: function(result) {
alert(ko.toJSON(result))
}
});
};
//Load initial state from server, convert it to Task instances, then populate self.tasks
$.ajax("/ds", {
data: {
json: ko.toJSON(fakeData)
},
type: "POST",
dataType: 'json',
success: function(data) {
var mappedTasks = $.map(data, function(item) {
return new Task(item);
});
self.tasks(mappedTasks);
}
});
}
ko.applyBindings(new TaskListViewModel());
});
ds.html
<script type="text/javascript" src="static/js/jquery-1.6.3.min.js"></script>
<script type="text/javascript" src="static/js/knockout-2.0.0.js"></script>
<p>
<div class="codeRunner">
<h3>Tasks</h3>
<form data-bind="submit: addTask">
Add task: <input data-bind="value: newTaskText" placeholder="What needs to be done?" />
<button type="submit">Add</button>
</form>
<ul data-bind="foreach: tasks, visible: tasks().length > 0">
<li>
<input type="checkbox" data-bind="checked: isDone" />
<input data-bind="value: title, disable: isDone" />
Delete
</li>
</ul>
You have <b data-bind="text: incompleteTasks().length"> </b> incomplete task(s)
<span data-bind="visible: incompleteTasks().length == 0"> - it's beer time!</span>
<button data-bind="click: save">Save</button>
</div>
</p>
<script type="text/javascript" src="static/js/model.js" ></script>
The ajax requests in the fiddle are just mock requests to simulate real-world scenarios, they're not really necessary.. you can use that fake data without any ajax requests. For example change these parts:
self.save = function() {
alert(ko.toJSON({tasks: this.tasks}));
};
//Load initial state from server, convert it to Task instances, then populate self.tasks
var mappedTasks = $.map(fakeData, function(item) {
return new Task(item);
});
self.tasks(mappedTasks);
If you want to use ajax requests to get real data, you'll need to post the data in the format required by your own server API (i.e. not with that 'json' field in the data that is used in jsfiddle's json-echo service API)