How to use ajax in mvc? - asp.net-mvc

I am a very beginner to mvc and ajax both.
I have tried many examples on net but I don't understand how ajax is used practically?
I have a controller named members which has GetAllMembers Method.
GetAllMembers returns a List<Members>
Now I want to use JQuery and ajax something like :
$(document).click(function () {
$.ajax({
url: "Members/GetAllMembers",
success: function () {
},
error: function () {
alert("Failed to get the members");
}
});
});
Is my URL right?
Upon success I want to display that List in a ListBox.
How can I get it? Can anyone give me a start?

$.ajax({
type: "POST",
url: "Members/GetAllMembers", //Your required php page
data: "id="+ data, //pass your required data here
success: function(response){ //You obtain the response that you echo from your controller
$('#Listbox').html(response); //The response is being printed inside the Listbox div that should have in your html page.
},
error: function () {
alert("Failed to get the members");
}
});
Hope this will help you.. :)

$(document).click(function () {
$.ajax({
url: "Members/GetAllMembers",
success: function (result) {
// do your code here
},
error: function () {
alert("Failed to get the members");
}
});
});
So your request give response in "result" variable. So you have to easily manage result variable value in foreach loop and set value in ListBox HTML.

Follow this example:
suppose you have this html:
<p>List Box - Single Select<br>
<select id="listBox" name="listbox">
</select>
</p>
So we have this js:
var template = '<option value="$value">$name</option>';
var getAllMembers = function() {
$.ajax({
url: 'Members/GetAllMembers',
dataType: 'json', //Assuming Members/GetAllMembers returns a json
success: function(response) {
$.each(response, function(index){
var option = template.replace(/\$value/g, this.value)
.replace(/\$name/g, this.name);
$('#listBox').append(option);
});
}
});
};
EDIT: Now you only need to call getAllMembers(); function.
Hope this help.
Pablo.

Related

<function> is not defined at HTMLButtonElement.onclick

Good day,
I have a button
<button id="4" onclick="UpdateStatus(this.id)" class="btn btn-default" type="button">update</button>
that is calling an ajax function
<script>
$(document).ready(function () {
function UpdateStatus(Id) {
$.ajax({
type: "Post",//or POST
url: '/myController/UpdateSomething?Id=' + Id,
// (or whatever your url is)
data: { data1: var1 },
success: function (responsedata) {
// process on data
alert("got response as " + "'" + responsedata + "'");
}
});
}
}
</script>
My problem is that I receive an error in my view:
UpdateStatus is not defined at HTMLButtonElement.onclick
what am I doing wrong? thanks
Update
When I try to run this code
#section scripts
{
<script>
$(document).ready(function () {
//Carga datos del curso
console.log("asdf");
});</script>}
I do not get the message in my console.
The problem is, You are defining your method definition inside the document.ready event of jQuery. When the button markup was parsed and rendered, the JavaScript method was not defined, hence you are getting the error.
The jquery ready method gets executed a little later when the document is ready (parsing and rendering of the HTML is already done, DOM is safe to be accessed). By this point, the HTML has been already rendered.
Define it outside it.
<script>
function UpdateStatus(Id) {
alert('UpdateStatus called');
}
$(function () {
});
</script>
Another option is to use unobutrusive JavaScript. So instead of wiring up a click event handler to the button markup, you will wire up later, when document ready is fired.
<button id="4" class="btn btn-default" type="button">update</button>
and wire up the click event
$(function () {
$("#4").click(function (e) {
e.preventDefault();
alert('User clicked');
});
});
<script>
function F(user_id) {
var user_id = user_id;
$.ajax({
type:"GET",
url:"http://127.0.0.1:8000/preference",
data: {'user_id':user_id},
async: false,
success: function (result) {
console.log(result)
}
});
}
</script>
the first line is automatically not to display. It is the script's type and src attributes. I used the "text/javascript" and "http://code.jquery.com/jquery-latest.js".
This question I found 2 solutions. One is as the above. To divide the script into two parts. Second is to move the function to under the button tag.
It is really a scope question. But I didn't find the solution's logic. But I solve it.
This is definitely a scoping issue, because UpdateStatus defined within the scope of document.ready() function. You can declare UpdateStatus as variable outside document.ready() block and declare a function inside it:
var UpdateStatus;
$(document).ready(function () {
UpdateStatus = function () {
var buttonId = $('#4').attr('id');
$.ajax({
type: "POST",
url: '/myController/UpdateSomething',
data: { Id: buttonId, ... }, // setting parameters
success: function (responsedata) {
// process on data
alert("got response as '" + responsedata + "'");
}
});
}
});
Additionally, based from standard event registration model and separation of concerns, I suggest you to use unobtrusive JavaScript by retrieving button ID like this:
$(document).ready(function () {
$('#4').click(function() {
var buttonId = $(this).attr('id');
$.ajax({
type: "POST",
url: '/myController/UpdateSomething',
data: { Id: buttonId, ... }, // setting parameters
success: function (responsedata) {
// process on data
alert("got response as '" + responsedata + "'");
}
});
});
});
Because you're using AJAX POST, no need to use query string parameters in URL like url: '/myController/UpdateSomething?Id=' + Id.
Related issues:
Uncaught ReferenceError: (function) is not defined at HTMLButtonElement.onclick
Why is inline event handler attributes a bad idea in modern semantic HTML?

Ajax call will not work without preventDefault

In an MVC page, I have the following jQuery/javascript:
$("form").submit(function (event) {
var inp = $("input"); inp.attr('value', inp.val());
var html = replaceAll(replaceAll($('html')[0].outerHTML, "<", "<"), ">", "<");
// event.preventDefault();
$.ajax({
url: "/Ajax/SetSession",
asynch: false,
dataType: "json",
cache: false,
type: "get",
data: { name: 'html', data: html.substring(0, 1024) },
error: function (xhr, status, error) {
alert("Ouch! " + xhr.responseText);
// $(this).unbind('submit').submit();
},
success: function (data) {
alert("Awesome: " + data);
// $(this).unbind('submit').submit();
},
complete: function (xhr, status) {
alert('Phew!');
$(this).unbind('submit').submit();
}
});
});
It is meant to intercept the normal submit process, capture the html of the page before it's submitted, and then continue on its way as if nothing happened.
But the problem is, with both commented out, the form re-submits, as expected, put the controller never executes the /Ajax/SetSession url. Whereas, if I uncomment them, the /Ajax/SetSession does execute but the unbind does not appear to work as the form does not seem to get resubmitted.
Not sure what's going on here. What am I missing?
Any and all clues appreciated.
event.preventDefault(); should stay uncommented since this prevents form to submit instantly. Apparently you want to control the moment at which form is submitted.
$(this).unbind does not work because inside success and error handles context is no longer form - it is an jQuery ajax context object. You can do two things here to have the behavior you want:
Set context explicitly to be the form object. This can be done via context property:
$.ajax({
...
context: this, //form here!
...
success: function (data) {
alert("Awesome: " + data);
$(this).unbind('submit').submit(); //now this refers to form
},
Refer to form using a different variable:
$("form").submit(function (event) {
var form = this;
...
$.ajax({
...
success: function (data) {
alert("Awesome: " + data);
$(form).unbind('submit').submit(); //using form variable instead of this
},

How to set the locale inside an Ajax call in Ruby on Rails?

I have this Ajax function inside my application.js file:
$("#project_person_id").change(function() {
$.ajax({
url: '/projects/get_invoice_types',
data: 'person_id=' + this.value,
dataType: 'script'
})
});
Is it possible to use a locale inside that function?
When I change line 3 to this:
url: '/de/projects/get_invoice_types',
I get the desired outcome (i. e. the output in German).
But of course I would like to set this dynamically. How can this be done?
Thanks for any help.
you can set it dynamically wherever you like, i.e
var locale = "de"; // set it dynamically
and the use it as a global, like this
$("#project_person_id").change(function() {
$.ajax({
url: "/"+locale+'/projects/get_invoice_types', // use it
data: 'person_id=' + this.value,
dataType: 'script'
})
});
a more elegant why would be to set it as a data attribute to the body tag <body data-locale="de"> or to the HTML head <html lang="de">, and pull it using a function
function locale() { return $("body").data("locale") } or
function locale() { return $("html").attr("lang") } and then retrieve it like this:
$("#project_person_id").change(function() {
$.ajax({
url: "/"+locale()+'/projects/get_invoice_types', // use it
data: 'person_id=' + this.value,
dataType: 'script'
})
});
there are other options of course, these seem straightforward.
I solved this issue modifying $.get and $.post jQuery's functions.
I my case the locale is a parameter in the url, but it can be injected as Sagish did too
(function ($) {
var oPost = jQuery.post;
var oGet = jQuery.get;
jQuery.post=function(url , data , success , dataType ){
if (typeof data === "undefined") {
data={};
}
data=add_locale_to_url(data);
return oPost.apply(this,[url , data , success , dataType]);
}
jQuery.get=function(url , data , success , dataType ){
if (typeof data === "undefined") {
data={};
}
data=add_locale_to_url(data);
return oGet.apply(this,[url , data , success , dataType]);
}
})(jQuery);
And when I call $.get or $.post the locale is automatically added to the URL:
...
var remote_search=$.get("/expenses/search_users/"+$(this).val());
remote_search(function( data ) {
$("#processing").hide();
alert( "Usuari inexistent");
obj_error.val("");
});
...
I solved this issue by adding data attributes to my erb template.
<button type="button" class="btn btn-success" id="save-job-position-btn" data-locale="<%= params[:locale] %>"><%= t("save") %></button>
$( "#save-job-position-btn" ).click(function() {
var locale = $(this).data("locale");
}

Asp.net Mvc jquery ajax?

I have links like following.
Deneme Müşteri 2
Deneme Müşteri 2
I want to use jquery ajax post like this:
$(".customer_details").click(function () {
$.ajax({
url: $(this).attr("href"),
type: 'POST',
beforeSend: function () {
},
complete: function () {
},
success: function (result) {
$("#customer_operations_container").html(result);
},
error: function (result) {
alert("Hata!");
}
}); //end ajax
});
Or this:
$(".customer_details").click(function () {
$("#customer_operations_container").load($(this).attr("href"));
});
And Action Method
public ActionResult _EditCustomer(int CustomerId)
{
// get customer from db by customer id.
return PartialView(customer);
}
But I cant do what I wanted. When I click to link, PartialView does not load. It is opening as a new page without its parent. I tried prevent.Default but result is the same.
How can I load the partialView to into a div?
Note: If I use link like this <a href="#"> it works.
Thanks.
Maybe the problem is with the actionresult, try with Content to see if that changes anything.
public ActionResult _EditCustomer(int CustomerId)
{
// get customer from db by customer id.
return Content(customer.ToString());
}
Try one of these...
$(".customer_details").click(function (e) {
e.preventDefault()
$.ajax({
url: $(this).attr("href"),
//I think you want a GET here? Right?
type: 'GET',
beforeSend: function () {
},
complete: function () {
},
success: function (result) {
$("#customer_operations_container").html(result);
},
error: function (result) {
alert("Hata!");
}
}); //end ajax
});
Or
$(".customer_details").click(function (e) {
e.preventDefault();
$("#customer_operations_container").load($(this).attr("href"));
});
Or
$(".customer_details").click(function (e) {
e.preventDefault();
$.get($(this).attr("href"), function(data) {
$("#customer_operations_container").html(data);
});
});
If none of this works, check if there's any js errors
The problem is when you click on the link you already start navigation to it. So just use e.preventDefault() or return false from the click method to prevent the default behavior
$(".customer_details").click(function (e) {
e.preventDefault();
...
}
This should help you out:
$.ajax({
url: $(this).attr("href"),
type: 'POST',
beforeSend: function () {
},
complete: function () {
},
success: function (result) {
$("#customer_operations_container").html(result);
},
error: function (result) {
alert("Hata!");
}
}); //end ajax
return false;
The only thing you where missing is the prevention of A tag working. By returning false your custom event is called and the default event is not executed.
Try this
$(function(){
$(".customer_details").click(function (e) {
e.preventDefault();
});
});
Using ready event
Demo: http://jsfiddle.net/hdqDZ/

JQUERY GET operation not working

I'm having trouble with the following JQuery script
$('#extra_data').append('<div id="tabs-' + (tab_length + 1) + '"></div>');
$.get(url, function(data) {
$('#tabs-' + (tab_length + 1)).html(data);
});
My trouble is that the $.get(..) operation doesn't return any results - although when using firebug it shows the ajax call as expected.
Any clues?
Thanks.
Controller
<HttpPost()> _
Function GetPartialView() As ActionResult
If (Request.IsAjaxRequest()) Then
Return View("PVTest")
Else
Return View()
End If
End Function
I've filtered the request if it is Ajax. You can even pass an object to your partial view.
jQuery
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: 'POST',
url: 'Home/GetPartialView',
data: {},
dataType: 'json',
beforeSend: function(XMLHttpRequest) {
},
complete: function(XMLHttpRequest, textStatus) {
$('#extra_data').append(XMLHttpRequest.responseText);
}
});
});
</script>
Partial View (PVTest.ascx)
<%# Control Language="VB" Inherits="System.Web.Mvc.ViewUserControl" %>
<div id="01">
Hello World
</div>
Try load method:
$('#extra_data').append('');
$('#tabs-' + (tab_length + 1)).load(url)
I think you need to use Post and [HttpPost] in ASP.NET MVC, I think there is a security
issue related to GET.
I only seem to use Post operations and remember seeing something about security.
Will see if I can verify that...
ADDED:
see: ASP.NET MVC 2.0 JsonRequestBehavior Global Setting
I would use a POST, as Mark suggested:
$.ajax({
type: 'POST',
url: url,
data: { },
dataType: 'json',
beforeSend: function(XMLHttpRequest) {
},
complete: function(XMLHttpRequest, textStatus) {
var Response = $.parseJSON(XMLHttpRequest.responseText);
}
});
the Response should contain the JSON stream. You can append it to your element.
The controller should do something like this:
<HttpPost()> _
Function DoSomething() As ActionResult
Return (Json(myObject, JsonRequestBehavior.DenyGet))
End Function

Resources