Ajax Json multiple parameters - ajax

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.

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)

unsupported_grant_type in Web Api 2

i am beginner in Web Api and implementing authorization and authentication but getting some error as i mentioned below:
I am getting this error while getting token from webApi
{"readyState":4,"responseText":"{\"error\":\"unsupported_grant_type\"}","responseJSON":{"error":"unsupported_grant_type"},"status":400,"statusText":"Bad Request"}
This is my jQuery code to make request for token
$(document).ready(function () {
$("#login").click(function () {
debugger;
var details = "{'grant_type':'password', 'username': '" + $("#UserName").val() + "', 'password': '" + $("#Password").val() + "' }";
console.log(details);
$.ajax({
type: "POST",
contentType: "application/x-www-form-urlencoded",
data: details,
url: "http://localhost:59926/token",
success: function (data) { console.log(JSON.stringify(data)); },
error: function (data) { console.log(JSON.stringify(data)); }
});
});
Your data should be like query string, not JSON object. And you should encode params if need
data: 'username=' + encodeURIComponent(user.username) + '&password=' + encodeURIComponent(user.password) + '&grant_type=password'
contentType is wrong. It should be application/json
$(document).ready(function () {
$("#login").click(function () {
debugger;
var details = "{'grant_type':'password', 'username': '" + $("#UserName").val() + "', 'password': '" + $("#Password").val() + "' }";
console.log(details);
$.ajax({
type: "POST",
contentType: "application/json",
data: details,
url: "http://localhost:59926/token",
success: function (data) { console.log(JSON.stringify(data)); },
error: function (data) { console.log(JSON.stringify(data)); }
});
});

Syntax Error JSON file read with AJAX

I am getting a syntax error for the square bracket '[' from my JSON file. Given below is the JSON.
[
{
"Product Name":"CPE 10281",
"Application":"Tyres",
"Weight":150,
"Cost to Produce":5000,
"Grade":"A",
"Cost to Sell":40000,
"Strength":100
},
{
"Product Name":"CPE 10282",
"Application":"computers",
"Weight":250,
"Cost to Produce":4000,
"Grade":"H",
"Cost to Sell":25000,
"Strength":90
}
]
I am trying to use AJAX to read my JSON file.
$.ajax({
url: "dataProductJSON.json",
dataType: 'json',
mimeType: "application/json",
success: function (data) {
var item = [];
$.each(data, function (key, val) {
item.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'interest-list',
html: item.join('')
}).appendTo('body');
},
});
I am running my html from Eclipse with Apache Geronimo as the server.
Please Help.
You are missing a { in the below line
success: function (data)
Make it
success: function (data) {
Edit
You are having parsing the data incorrectly , do it as below
$.ajax({
url: "test.html",
dataType: 'json',
mimeType: "application/json",
success: function (data) {
var item = [];
$.each(data, function (key, val){
$.each(val, function (innerKey, innerValue){
item.push('<li id="' + innerKey + '">' + innerValue + '</li>');
});
});
$('<ul/>', {
'class': 'interest-list',
html: item.join('')
}).appendTo('body');
},
});
You need to use 2 loop , one for the array and the other to loop through the object property
I tried things and it is working fine

ajax jquery pass null value

I get null values in the controller when I process the request using jquery ajax
Controller
[HttpPost]
public ActionResult UpdateAnswers(string answers, string question, string controlid, int eventid)
{
var replacetext=string.Empty;
if (answers.Length>0)
replacetext = answers.Replace("\n", ",");
_service.UpdateAnswers(eventid, replacetext, controlid);
return PartialView("CustomizedQuestions");
}
Jquery - Ajax Code
var test = "{ answers: '" + $("#answerlist").val() + "', question: '" + title + "', controlid: '" + controlid + "', eventid: '" + eventid + "' }";
$.ajax({
url: '#Url.Action("UpdateAnswers")',
type: 'POST',
dataType: 'html',
contentType: 'application/html; charset=utf-8',
context: $(this),
// data: "{ answers: '"+$("#answerlist").val()+"' ,question: '"+ title +"', controlid:'"+ controlid +"',eventid:'"+ eventid+"'}",
data: JSON.stringify(test),
success: function (result) {
$(this).dialog("close");
},
error: function () {
//xhr, ajaxOptions, thrownError
alert('there was a problem saving the new answers, please try again');
}
});
Your contentType is wrong. Why did you set it to application/html when you pass JSON? Try like this:
var test = { answers: $('#answerlist').val(), question: title, controlid: controlid, eventid: eventid };
$.ajax({
url: '#Url.Action("UpdateAnswers")',
type: 'POST',
dataType: 'html',
contentType: 'application/json; charset=utf-8',
context: $(this),
data: JSON.stringify(test),
success: function (result) {
$(this).dialog("close");
},
error: function () {
//xhr, ajaxOptions, thrownError
alert('there was a problem saving the new answers, please try again');
}
});
or using application/x-www-form-urlencoded which is the default:
var test = { answers: $('#answerlist').val(), question: title, controlid: controlid, eventid: eventid };
$.ajax({
url: '#Url.Action("UpdateAnswers")',
type: 'POST',
dataType: 'html',
context: $(this),
data: test,
success: function (result) {
$(this).dialog('close');
},
error: function () {
//xhr, ajaxOptions, thrownError
alert('there was a problem saving the new answers, please try again');
}
});

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