Why i can not fetch data from controller from ajax function? - ajax

I'm beginner in asp.net mvc ,and want to fetch simple json from controller to ajax variable,for that purpose in view page write this ajax function:
<script>
var OutPut;
OutPut = "behzad";
function CallService() {
$.ajax({
url: '#Url.Action("callService", "myPassword")',
type: 'GET',
dataType: 'json',
cache: false,
data: { 'id': 2 },
success: function (color) {
OutPut= color;
},
error: function () {
alert('Error occured');
}
});
alert("I think is ok!"+":"+OutPut);
}
</script>
and this controller:
[HttpGet]
public JsonResult callService(int id)
{
string JSON = "behzad";
return Json(JSON,JsonRequestBehavior.AllowGet);
}
that ajax function call with this html code in view page:
<button type="button" class="btn btn-success" onclick="CallService()">Success</button>
but this line in ajax function:
alert("I think is ok!"+":"+OutPut);
Output is undefined,what happen?is controller return null?or why i get undefined alert?thanks.

Since the AJAX call is asynchronous, you should place the alert inside the success callback:
<script>
function CallService() {
$.ajax({
url: '#Url.Action("callService", "myPassword")',
type: 'GET',
cache: false,
data: { 'id': 2 },
success: function (color) {
alert("I think is ok!" + ":" + color);
},
error: function () {
alert('Error occurred');
}
});
}
</script>

Related

ajax post is returning null at the actionmethod

I am trying to retrieve the array of integers by posting it from ajax post as:
function myFunction() {
var items = [];
for(var i = 0; i<7;i++)
{
items[i]= i;
}
SubmitForm(items);
}
function SubmitForm(obj) {
$.ajax({
url: "/Home/Index",
method: "POST",
data: obj,
success: function (data) {
alert(data);
}
,
error: function (err) {
console.log(err);
}
})
}
<input type="submit" value="Submit" class="btn" onclick="myFunction();" />
My controller is as:
Public JsonResult Index(int[] arr)
{
return View();
}
I have tried it with every parameter type but it still wont bind values to my action parameter. Do anyone knows what i am doing wrong?
Try the following. You should try and pass the array as a JSON
function SubmitForm(obj) {
$.ajax({
url: "/Home/Index",
type: "POST",
data: JSON.stringify({"arr": obj}),
contentType: 'Application/json',
success: function (data) {
alert(data);
}
,
error: function (err) {
console.log(err);
}
})
}

How to load data from database using autocomplete?

Here is my jQuery:
$(function() {
$( "#user_role" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "ajax/search_username",
dataType: "json",
data: request,
success: function(data){
if(data.response == 'true') {
response($data);
}
}
});
},
minLength: 1,
select: function( event, ui ) {
//Do something extra on select... Perhaps add user id to hidden input
},
});
}());
here is my HTML,
<input type="text" id="user_role" name="user_role">
Here is my controller,
function search_username() {
$keyword=$this->input->get('term');
$this->load->model('chat_model');
$data=$this->chat_model->GetRow($keyword);
echo json_encode($data);
}
Here is my model
public function GetRow($keyword) {
$this->db->like('user_type', $keyword, 'both');
return $this->db->get('lc_user_types')->result_array();
}
What I my trying to do is to load data form database using ajax but it's response is no properties but data is already there in table, please anyone help me for get rid of this.
First of all check this function it will return result or not
public function GetRow($keyword) {
$this->db->like('user_type', $keyword, 'both');
return $this->db->get('lc_user_types')->result_array();
}
If it returning change the function
$(function() {
$( "#user_role" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "ajax/search_username",
dataType: "json",
data: request,
success: function(data){
response($.map(data, function (value, key) {
return {
id:key,
label: value,
value: value
};
}));
}
});
},
minLength: 1,
select: function( event, ui ) {
//Do something extra on select... Perhaps add user id to hidden input
},
});
}());

How to load a file using AJAX once and use its data multiple times?

I have this code where I load an XML file through AJAX:
$("#list").on("click", "li", function (event) {
$.ajax({
url: 'test.xml',
type: "get",
context: this,
success: function (data) {
alert("success");
},
error: function () {
alert("failure");
}
});
})
The issue is that I have a long list of clickable elements that use this code which is not very efficient. Is there a way to call AJAX function once and then use the data produced for other items on the list?
Just save the return value somewhere
$("#list").on("click", "li", function (event) {
var data = $("#list").data('test');
if (data){
//use data
}
else{
$.ajax({
url: 'test.xml',
type: "get",
context: this,
success: function (data) {
$("#list").data('test', data);
// use data
alert("success");
},
error: function () {
alert("failure");
}
});
}
})

show ajax-loader.png on a MVC3 form submit in a Jquerymobile application

I have a mobile application with MVC3 and Jquerymobile. At form submission (with ajax function) I want to display loading icon (ajax-loader.png) while submit and redirect.
Thanks!
my ajax function:
$("#add").click(function () {
$.validator.unobtrusive.parse($('form')); //added
if ($("form").valid()) {
var IDs = new Array($("#SelectedProduct").val(), $("#SelectedAccount").val(), $("#SelectedProject").val(), $("#SelectedTask").val(), $("#date").val(), $("#duration").val());
$.ajax({
url: '#Url.Action("SaveLine", "AddLine")',
type: 'post',
data: { ids: IDs },
dataType: 'json',
traditional: true,
success: function (data) {
if (data.success == true) {
$("#ajaxPostMessage").html(data.Success);
$("#ajaxPostMessage").addClass('ajaxMessage').slideDown(function () {
window.location.href = '#Url.Action("Index", "AddLine")';
}).delay(1800)
}
else {
$("#ajaxPostMessage").html(data.Error);
$("#ajaxPostMessage").addClass('ajaxMessage');
$("#ajaxPostMessage").show();
}
}
});
}
return false;
});
I would do something like this:
Ajax = {
Submit: function() {
Ajax.Loading();
//ajax stuff
//Ajax.Message('form complete, blah blah');
},
Loading: function() {
$('#ajax').html('ajax-loader.png');
},
Message: function(msg) [
$('#ajax').html(msg);
}
}

Converting MVC Ajax to Jquery

I am in the process of learning how to convert MVC Ajax to jquery ajax so I can do more.
This is the old ajax, I took out the loading stuff
#Ajax.ActionLink("Update Tweets", "Index", "Home",
new AjaxOptions
{
UpdateTargetId = "TweetBox",
InsertionMode = InsertionMode.InsertBefore,
HttpMethod = "Get",
})
I need to convert this to jquery ajax. It seems to be working lets see the code
<script>
$(document).ready(function () {
$("#StartLabel").click(function (e) {
$.ajax({
type: "Get",
url: '/Home/Index',
// data: "X-Requested-With=XMLHttpRequest",
// contentType: "application/text; charset=utf-8",
dataType: "text",
async: true,
// cache: false,
success: function (data) {
$('#TweetBox').prepend(data);
alert('Load was performed.');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
complete: function (resp) {
alert(resp.getAllResponseHeaders());
}
});
});
});
</script>
In the microsoft ajax it sets XML Request in the headers. Do I need to add that too? I am just paging my controller that performs a query to twitter and appends the data to the top.
I am using fiddler to see how the requests are different but the results are the same.
I also noticed if i put the text in the data: object its puts it in the header. i dont think that is right by any means.
You could define a normal anchor:
#Html.ActionLink("Update Tweets", "Index", "Home", null, new { id = "mylink" })
And then unobtrusively AJAXify it:
$(document).ready(function () {
$("#mylink").click(function (e) {
$.ajax({
type: "GET",
url: this.href,
success: function (data) {
$('#TweetBox').prepend(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
complete: function (resp) {
alert(resp.getAllResponseHeaders());
}
});
return false;
});
});
Notice that I return false from the click handler in order to cancel the default action. Also notice that I am using the anchor's href property instead of hardcoding it.
The 2 AJAX requests should be identical.
Here is simple example using Ajax with Jason data
// Post JSON data
[HttpPost]
public JsonResult JsonFullName(string fname, string lastname)
{
var data = "{ \"fname\" : \"" + fname + " \" , \"lastname\" : \"" + lastname + "\" }";
return Json(data, JsonRequestBehavior.AllowGet);
}
in the view add a reference to the query as following
#section Scripts{
<script src="~/Scripts/modernizr-2.6.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.intellisense.js"></script>
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
}
in the view add the js
note: (jsonGetfullname).on is a button
<script type="text/javascript">
$("#jsonGetfullname").on("click", function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "#(Url.Action("JsonFullName", "Home"))",
data: "{ \"fname\" : \"modey\" , \"lastname\" : \"sayed\" }",
dataType: "json",
success: function (data) {
var res = $.parseJSON(data);
$("#myform").html("<h3>Json data: <h3>" + res.fname + ", " + res.lastname)
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
})
});
</script>
you can also use (POST\GET) as following:
[HttpPost]
public string Contact(string message)
{
return "<h1>Hi,</h1>we got your message, <br />" + message + " <br />Thanks a lot";
}
in the view add the js
note: (send).on is a button
$("#send").on("click", function () {
$.post('', { message: $('#msg').val() })
.done(function (response) {
setTimeout(function () { $("#myform").html(response) }, 2000);
})
.error(function () { alert('Error') })
.success(function () { alert('OK') })
return false;
});

Resources