Converting MVC Ajax to Jquery - ajax

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;
});

Related

Ajax - Parse oData Response

I have an ajax call that gets data from a REST api.
$.ajax({
url: "http://localhost:52139/odata/WEB_V_CIVIC_ADDRESS",
data: { enteredText: "'" + $('#addressTextField').val() + "'" },
type: "GET",
dataType: 'json',
ContentType: "application/json",
success: function (data) {
alert(JSON.stringify(data));
response($.map(data.accountaddressList, function (item) {
return {
item: item.civicaddress,
value: item.accountNumber,
label: item.civicaddress
}
}));
},
error: function (data, xml, errorThrown) {
alert('Error loading address list: ' + errorThrown);
}
});
The odata returned from that call looks like:
{
"#odata.context":"http://localhost:52139/odata/$metadata#WEB_V_CIVIC_ADDRESS/AValues.Classes.Entities.AccountAddress","value":[
{
"#odata.type":"#AValues.Classes.Entities.AccountAddress","accountNumber":88887,"rowNumber":0,"civicaddress":"123 Fake St"
},{
"#odata.type":"#AValues.Classes.Entities.AccountAddress","accountNumber":88888,"rowNumber":0,"civicaddress":"321 Faker St"
}
]
}
So the current code throws an 'Undefined' error on the line: response($.map(data.accountaddressList, function (item) {
How do I map the 'civicaddress' and 'accountNumber' from each value in the odata response to 'item'?
Thanks.
I got it, needed to change it to response($.map(data.value, function (item)

ajax form submits fine, but success does not work?

I have a simple form that submits with jquery and ajax. the form submits fine and the data posts, but the success message will not call... just the error message. can someone tell me what I am doing wrong.
<script type="text/javascript" >
$(function() {
$(".form-submit").click(function() {
var esn = $("#esn").val();
var dataString = 'esn='+esn;
if(esn=='')
{
$('.error').show().fadeOut(3000);
}
else
{
$.ajax({
type: "post",
url: "include/submit_repair_form.php",
data: dataString,
success: function(result) {
alert(result);
$('.testing').hide();
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr.statusText);
}
});
}
return false;
});
});
</script>
You forgot to set the result variable in function()
Like this:
success: function(result) {
alert(result);
$('.testing').hide();
}

BlockUI Ajax loading wrong moment

I know there's other post about this. but there's no answer.
Situation, I have an ajax command. It take time because I have somes things to get.
I want to include a loading between the execution of the ajax.
I want to use jquery BlockUI because its simple and good looking.
But I dont know why the visual effect not working until ajax load the entire data(like when "success" begin).
I try multiple way but not working.
here's my last code :
function from http://www.codeproject.com/Articles/382390/An-Example-to-Use-jQuery-Global-AJAX-Event-Handler
var AjaxGlobalHandler = {
Initiate: function(options) {
$.ajaxSetup({ cache: false });
// Ajax events fire in following order
$(document).ajaxStart(function() {
$.blockUI({
message: options.AjaxWait.AjaxWaitMessage,
css: options.AjaxWait.AjaxWaitMessageCss
});
}).ajaxSend(function(e, xhr, opts) {
}).ajaxError(function(e, xhr, opts) {
if (options.SessionOut.StatusCode == xhr.status) {
document.location.replace(options.SessionOut.RedirectUrl);
return;
}
$.colorbox({ html: options.AjaxErrorMessage });
}).ajaxSuccess(function(e, xhr, opts) {
}).ajaxComplete(function(e, xhr, opts) {
}).ajaxStop(function() {
$.unblockUI();
});
}
};
call ready
var options = {
AjaxWait: {
AjaxWaitMessage: '<h1 class="ui-overlay-loading-content"><img class="ui-overlay-loading-image" src="_inc/img/loading3circle1.gif" />Chargement des données ...</h1>',
AjaxWaitMessageCss: { backgroundColor: '#ffffff' }
},
AjaxErrorMessage: "<h6>Erreur!/h6>"
};
AjaxGlobalHandler.Initiate(options);
call execution
$.ajax({
type: "POST",
url: location.href.split('/').pop() + "?action=" + actionName + "&recherche=" + recherche,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
FillDataGridOnSuccess(response, gridId, dataTypeName);
},
error: function(xhr, ajaxOptions, thrownError) {
alert("xhr.status : " + xhr.status);
alert("thrownError : " + thrownError);
}
});
I try also
var ajaxSettings = function(options) {
return $.extend(
{
beforeSubmit: function() {
//beforeSend: function() {
$.blockUI({ overlayCSS: { backgroundColor: '#ffffff' },
message: '<h1 class="ui-overlay-loading-content"><img class="ui-overlay-loading-image" src="_inc/img/loading3circle1.gif" />Chargement des données ...</h1>'
});
},
complete: function() {
$.unblockUI();
}
},
options
);
};
Every test that I did end with a loading who seems to only appear on ajaxSuccess.
I know there's sample on official blockUI site http://jquery.malsup.com/block/#demos
and they working there, but I cant on my own. did anybody see why?
tank you

Ajax Json multiple parameters

This code below sitting on a ASP.Net application on the Site.Mater....
I need to pass another two parameters from the default.aspx page, one asp:label and one asp:textbox
What is the easiest way to do that?
Thanks
<script type="text/javascript">
$(function () {
$(".tb").autocomplete({
source: function (request, response) {
$.ajax({
url: "TestWebService.asmx/FetchList",
data: "{ 'testName': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item.Name
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2
});
});
In your jQuery autocomplete, You need to change your data parameter to this:
data: "{ 'testName': '" + request.term + "' ,lbl: '" + $(".lblClass").text() + "' ,txt: '" + $(".txtClass").val() + "'}"
And then change your service method like this:
[WebMethod]
public List<string> FetchList(string testName, string lbl, string txt)
{
//...
}
Note:
.lblClass and .txtClass are classes for ASP:Lable and ASP:TextBox respectively.

JSON, jQueryUI Autocomplete, AJAX - Cannot get data when array is not local

I have searched stackoverflow, as well as the web for some insight into how to get the jQueryUI Autocomplete plugin working with my JSON data, and I'm at a loss. I had it working like a charm with a local data array. I was able to pull values and build html.
I ran into a problem when I had to pull JSON form this source:
/Search/AjaxFindPeopleProperties2
?txtSearch=ca pulls up the test data that I am trying to loop through, when I type in 'ca' to populate the autocomplete list. One of the problems is that ?term=ca is appended to the url instead of ?txtSearch=ca and I'm not sure how to change it.
This is an example of the data:
{
"MatchedProperties": [
{
"Id": 201,
"Name": "Carlyle Center",
"Description": "Comfort, convenience and style are just a few of the features you'll ...",
"ImageUrl": "/Photos/n/225/4989/PU__ThumbnailRS.jpg"
}
]
}
...and here is the ajax call I'm trying to implement:
$(document).ready(function () {
val = $("#txtSearch").val();
$.ajax({
type: "POST",
url: "/Search/AjaxFindPeopleProperties2",
dataType: "json",
data: "{}",
contentType: "application/json; charset=utf-8",
success: function (data) {
$('#txtSearch').autocomplete({
minLength: 0,
source: data.d, //not sure what this is or if it's correct
focus: function (event, ui) {
$('#txtSearch').val(ui.item.MatchedProperties.Name);
$.widget("custom.catcomplete", $.ui.autocomplete, {
//customize menu item html here
_renderItem: function (ul, item) {
return $("<li class='suggested-search-item" + " " + currentCategory + "'></li>")
.data("item.autocomplete", item)
.append($("<a><img src='" + item.MatchedProperties.ImageUrl + "' /><span class='name'>" + item.MatchedProperties.Name + "</span><span class='location'>" + "item.location" + "</span><span class='description'>" + item.MatchedProperties.Description + "</span></a>"))
.appendTo(ul);
},
_renderMenu: function (ul, items) {
var self = this,
currentCategory = "Properties Static Test Category";
$.each(items, function (index, item) {
if (item.category != currentCategory) {
ul.append("<li class='suggested-search-category ui-autocomplete-category'>" + currentCategory + "</li>");
//currentCategory = item.category;
}
self._renderItem(ul, item);
});
}
}//END: widget
//return false;
},
select: function (event, ui) {
$('#txtSearch').val(ui.item.MatchedProperties.Name);
//$('#selectedValue').text("Selected value:" + ui.item.Abbreviation);
return false;
}
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
}); //END ajax
}); //END: doc ready
and I'm initializing here:
<script type="text/javascript">
//initialize autocomplete
$("#txtSearch").autocomplete({ //autocomplete with category support
/*basic settings*/
delay: 0,
source: "/Search/AjaxFindPeopleProperties2",
autoFocus: true,
minLength: 2 //can adjust this to determine how many characters need to be entered before autocomplete will kick in
});
//set auto fucus
$("#txtSearch").autocomplete("option", "autoFocus", true);
</script>
any help would be great...
Thanks!

Resources