I am using Jquery Ajax to set the values of a Label and a ListBox in my form. I realize that values are set properly by the function. But just after that , the page just refreshes clearing all previously set values . Why is this happening ? Iam new to Jquery/Ajax. Am I missing any fundamentals here ? Thanks in Advance.
Iam pasting the entire code
$(document).ready(function () {
$('#Button1').bind('click', function clk() {
$.ajax({
type: "POST",
url: "WebForm5.aspx/TestMethod",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert(result.d.ListBox.length);
for (var i = 0; i < result.d.ListBox.length; i++) {
alert(result.d.ListBox[i]);
$(document.createElement("option")).attr("value", result.d.ListBox[i]).html(result.d.ListBox[i])
.appendTo('#<%=ListBox1.ClientID %>');
$('#Label1').text(result.d.MyProperty);
}
}
});
})
});
Button1 in your code is an asp button which is a submit button. When you click on it, it will submit the page and refresh the whole page. If you want to stop the page from being submitted on button click return false, it will work.
$('#Button1').bind('click', function clk() {
$.ajax({
type: "POST",
url: "WebForm5.aspx/TestMethod",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert(result.d.ListBox.length);
for (var i = 0; i < result.d.ListBox.length; i++) {
alert(result.d.ListBox[i]);
$(document.createElement("option")).attr("value", result.d.ListBox[i]).html(result.d.ListBox[i])
.appendTo('#<%=ListBox1.ClientID %>');
$('#Label1').text(result.d.MyProperty);
}
}
});
return false;
})
Related
I have a List which look like the following
I want to send this list into my controller,
I am using ajax call to send data from client side to server side
here is my ajax call
$.ajax({
url: '/Main/updateTripundHoliday',
data: d.weekendLeave,
type: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
}
});
and my method in controller
public bool updateHoliday(List<Holidaysclass> data)
{
for (var i = 0; i < data.Count(); i++)
{
insertHolidays(data.ElementAt(i).Date, data.ElementAt(i).Day, data.ElementAt(i).HolidayName, data.ElementAt(i).isActive, data.ElementAt(i).currentYear, data.ElementAt(i).isHolidayWeekend, data.ElementAt(i).OfficialID);
}
return true;
}
here my List<Holidaysclass> data is showing null
what can I do here?
To send data from browser to controller you need to use POST type and then pass data inside ajax call. you can directly map your entites in action method.
$.ajax({
url: '/Main/updateTripundHoliday',
data: d.weekendLeave,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
}
});
and in controller put HttpPost Data Annotation
[HttpPost]
public bool updateHoliday(List<Holidaysclass> data)
{
for (var i = 0; i < data.Count(); i++)
{
insertHolidays(data.ElementAt(i).Date, data.ElementAt(i).Day, data.ElementAt(i).HolidayName, data.ElementAt(i).isActive, data.ElementAt(i).currentYear, data.ElementAt(i).isHolidayWeekend, data.ElementAt(i).OfficialID);
}
return true;
}
Using ajax get method we cant send data from client to server is not best way. try using POST method send data from client to server.
Reference : https://api.jquery.com/jquery.post/
$.ajax({
url: '/Main/updateTripundHoliday',
data: d.weekendLeave,
type: "POST",
......
});
You can do it like this :
$(document).ready(function () {
var things = [
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }
];
things = JSON.stringify({ 'things': things });
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Home/PassThings',
data: things,
success: function () {
$('#result').html('"PassThings()" successfully called.');
},
failure: function (response) {
$('#result').html(response);
}
});
});
Please follow this link for more information :
link
You can not post data in get request. Instead you need to use POST type request.
Here is your updated request.
$.ajax({
url: '/Main/updateTripundHoliday',
data: d.weekendLeave,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
}
});
Also your action should have [HttpPost] annotation.
try this:
$.ajax({
url: '/Main/updateHoliday',
data: {list: d.weekendLeave},
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
}
});
[HttpPost]
public bool updateHoliday(List<Holidaysclass> list)
i have some problem when i use jquery.when function in web form using master page
This is my code in web form using master page
$(document).ready(function(){
$.when(masterPageFunction()).done(function(){
webFormFunction();
});
})
And this my master page
function masterPageFunction() {
//In this function i call 2 ajax like this
$.ajax({
type: "POST",
url: "/api/master/xxx/",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$.ajax({
type: "POST",
url: "/api/master/xxx2/",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
}
})
}
})
}
result is web function is running when master page function not done
please help, thank you so much
You're close, but the when, then and done functions rely on promises. You aren't returning any promises in your code, so it's just running straight through.
First, you'll need to obtain the result of the promise after it completes in the done function in your master page. We'll do that by adding a response parameter to the callback, then passing it through to webFormFunction.
$(document).ready(function(){
$.when(masterPageFunction()).done(function(response){
webFormFunction(response);
});
})
Next, we need to add a promise to masterPageFunction and return it. You resolve the promise with the response you want to send back to the done function in your master page. Like so:
function masterPageFunction() {
// Create the promise
var deferred = $.Deferred();
//In this function i call 2 ajax like this
$.ajax({
type: "POST",
url: "/api/master/xxx/",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$.ajax({
type: "POST",
url: "/api/master/xxx2/",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
// Resolve the promise with the response from $.ajax
deferred.resolve(response);
}
});
}
});
// Return the promise (It hasn't been resolved yet!)
return deferred.promise();
}
In this way, webFormFunction won't be called until the second ajax call completes, which resolves the promise.
I was facing some problem with AJAX code. I was using MVC3 for our project. My requirement is bind the dropdown value using AJAX when page load. What happens when loading the page, the AJAX request send to the controller properly and return back to the AJAX function and binds the exact values in dropdown. But sometimes (When page refreshed or first time load) its not binding retrieved value. Rather its showing default value. Pls see my code and suggest me where i am doing wrong.
Edit: Even i tried to use async property to false. Its not at all send to the controller action method for getting the data.
Code
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("GetUser", "Invoices")',
data: "{'id':" + JSON.stringify(currval) + "}",
dataType: "json",
async: true,
success: function (data) {
$("#User-" + curr).select2("data", { id: data.Value, Name: data.Text });
$(this).val(data.Value);
}
});
Thanks,
Let's say your Action method is below
public JsonResult hello(int id)
{
return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
}
and JQuery should be like below
<script language="javascript" type="text/javascript">
$(document).ready(function () {
var currval = 2;
$.ajax({
url: 'URl',
async: true,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ id: currval }),
success: function (data) {
}
});
});
</script>
You are declaring your data property incorrectly. Try this:
data: { id: currval },
I have an AJAX call to a function as follows:
$("#<%=gridview.ClientID%> tr:has(td)").click(function(e) {
var id = $(this).children("td:eq(3)").find(':input').val();
$.ajax({
type: "POST",
url: "Docs.aspx/BtnTest",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
if (msg.d == 'Success') {
window.open('/view.aspx?Id=' + id, '_blank');
}
}
});
e.preventDefault();
});
As you can see in above code on success I am opening another page with id as querystring. How can I call Colorbox or any other lightbox plugin to open this in iframe?
Try this:
$.colorbox({ href: 'your link goes here', iframe:true, width:"80%", height:"80%"});
Same problem:
add colorbox to dynamicly created item with url content
So here's the problem. I have three pages that make web service calls. The first time I land on the page and make the call it works fine, however if I switch to the second page it tries to make a web service call to the wrong service. Here's some info:
pages:
Page1.aspx - has Page1.js
Page2.aspx - has Page2.js
js files:
Page1.js
var filterCriteria = "";
function GetList() {
$.ajax({
type: "POST",
url: "/webServices/Page1.asmx/Page1List",
contentType: "application/json; charset=utf-8",
data: "{'letter':'" + filterCriteria + "'}",
dataType: "json",
success: function (result) {
DisplayList(result.d);
}
});
}
function GetSearchResults() {
$.ajax({
type: "POST",
url: "/webServices/Page1.asmx/Page1FilteredList",
contentType: "application/json; charset=utf-8",
data: "{'searchCriteria':'" + $("#Search").val() + "'}",
dataType: "json",
success: function (result) {
DisplayList(result.d);
}
});
}
function DisplayList(object) {
var html = '';
for (var i = 0; i < object.length; i++) {
//format results and append
}
if (object.length == 0) {
html += "<li class=\"filteredList\" style=\"padding: 10px;\">No Results Found</li>";
}
$("#Page1List").html(html);
}
Page2.js
var filterCriteria = "";
function GetList() {
$.ajax({
type: "POST",
url: "/webServices/Page2.asmx/Page2List",
contentType: "application/json; charset=utf-8",
data: "{'letter':'" + filterCriteria + "'}",
dataType: "json",
success: function (result) {
DisplayList(result.d);
}
});
}
function GetSearchResults() {
$.ajax({
type: "POST",
url: "/webServices/Page2.asmx/Page2FilteredList",
contentType: "application/json; charset=utf-8",
data: "{'searchCriteria':'" + $("#Search").val() + "'}",
dataType: "json",
success: function (result) {
DisplayList(result.d);
}
});
}
function DisplayList(object) {
var html = '';
for (var i = 0; i < object.length; i++) {
//format results and append
}
if (object.length == 0) {
html += "<li class=\"filteredList\" style=\"padding: 10px;\">No Results Found</li>";
}
$("#Page2List").html(html);
}
So both have the same calls and the same information and the only real difference is that the results are different and they make a web service call to different web services that get different data.
Now each time that I switch between I get a new js file which is
jQuery-1.7.1.min.js/eval/seq/1
jQuery-1.7.1.min.js/eval/seq/2
jQuery-1.7.1.min.js/eval/seq/3
jQuery-1.7.1.min.js/eval/seq/4
depending on how many times I switch back an forth. Is there any way to stop the eval or is there something in my code that is causing the jQuery to store evals of the code I am using and what can I do to resolve it?
So the problem was that I was loading page transitions from jquery mobile. What was happening was that jquery mobile appends new page data to the DOM instead of forcing a page load. This was causing both javascript files to be loaded simultaneously meaning that which ever js file was loaded last was the primary and because both js files were calling functions with the same name it would load them multiple times.
Resolution
remove the $.mobile.load() event and force the click event to append the pathname to the url
$("#GoPage1").on("click", function () { window.location = "/dir/Page1.aspx"; });
$("#GoPage2").on("click", function () { window.location = "/dir/Page2.aspx"; });