I have looked for a solution , but nothing that fits my needs was found on the site, so here goes:
I have a Controller that returns a Json:
return Json(new { Item = searchModule});
searchModule is a list of Profiles:
{ "Item":[{"ProfileID":4854,"NickName":"Johnny","users":null,"FirstName":"John","LastName":"Doe"}]}
In JavaScript we have:
$.ajax({
type: "POST",
url: action/controller,
data: "{queryString:'" + searchVal + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data.Item)
}
})
That returns an object. How can I obtain: Firstname,LastName and NickName ???
Additional answer: If I write the code like below:
var request = $.ajax({
type: "POST",
url: action/controller,
data: "{queryString:'" + searchVal + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
}
}).responseText
var obj = json.Parse(request)
, request is null.
since they're objects structured according to the JSON, you should be able to just access the properties like so: data.Item[0].Firstname. You may or may not need to use jQuery.parseJSON to get to this step - calling that is trivial.
Related
A web-service is available at http://www.cs.sun.ac.za/rw334/products.php?
limit=12&skip=0
I want to get the data in there into a Javascript array. I've searched around and I think I should start like this?
$.ajax({
type: "GET",
url: "http://www.cs.sun.ac.za/rw334/products.php?limit=12&skip=0",
data: {id:id, name:name,url:url},
contentType: "application/json",
dataType: "json",
success: ??
}
});
How should I continue to get this data from the .php file into a Javascript array?
product = [];
$.ajax({
type: "GET",
url: "http://www.cs.sun.ac.za/rw334/products.php?limit=12&skip=0",
dataType: "json",
success: function(data) {
$(data.products).each(function(i, products){
product[products.id] = products.name;
});
console.log(product);
}
});
$(".loadingPnl").removeClass('hdn');
var siteurlA = window.location.protocol + "//" + window.location.host + _spPageContextInfo.siteServerRelativeUrl;
var callUrl = siteurlA + "/_layouts/15/SynchronyFinancial.Intranet/CreateMySite.aspx/SaveAvailableFavoriteItem";
var linkName = $('.txtLinkName').val();
linkName = linkName.replace("'","\'");
$.ajax({
type: "POST",
url: callUrl,
data: "{'linkName': '" + linkName + "', 'webSiteUrl':'" + $('.txtWebAddress').val() + "','iconId':'" + $(".ddlIcons").val() + "'}",
contentType: "application/json; charset=utf-8",
processData: false,
dataType: "json",
success: function (response) {
return true;
},
error: function (response) {
return true;
}
});
return true;
}
The problem is you're building JSON yourself as the request parameters. Moreover, you're building invalid JSON (JSON property names are always with double quotes (")).
Instead, pass an object and let jQuery take care of how to send it - if you pass that instead of a string the server can figure it out. If you really want to do it yourself you can also pass an object to JSON.stringify.
var payload = {
linkName: linkName,
webSiteUrl: $('.txtWebAddress').val(),
iconId: $(".ddlIcons").val()
};
$.ajax({
type: "POST",
url: callUrl,
data: JSON.stringify(payload), // or just payload
contentType: "application/json; charset=utf-8",
processData: false, // if you just pass payload, remove this
dataType: "json"
// you had two `return`s here, but they wouldn't work, make sure
// you understand why
// http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call
});
You can send a JSON instead. Or use JSON.stringify if you want String.
{
'linkName' : linkName,
'webSiteUrl' : $('.txtWebAddress').val(),
'iconId' : $(".ddlIcons").val()
}
Don't create JSON string by yourself AND don't use JSON.stringify().
Problem with creating JSON string yourself is to escape string properly for JavaScript (which could be tricky). see Special Characters
Problem with JSON.stringify is that I found it somehow slower than XMLHttpRequest which is strange because I thought it is using JSON.stringify behind curtains.
XMLHttpRequest is handling this for you. If you just pass your object as a data and XMLHttRequest will do the trick.
$.ajax({
type: "POST",
url: callUrl,
data: {'linkName': linkName,
'webSiteUrl': $('.txtWebAddress').val(),
'iconId': $(".ddlIcons").val()
},
contentType: "application/json; charset=utf-8",
processData: false,
dataType: "json",
success: function (response) {
return true;
},
error: function (response) {
return true;
}
});
I have AJAX POST, the result is JSON:
$.ajax({
type: "POST",
url: "../../api/test",
data: JSON.stringify(source),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var upload = JSON.stringify(result);
console.log(upload);
}
});
The upload result is:
{"Link":0,"Title":"d","Description":"dada","Keywords":"dad"}
How can I get the value of Title?
Do not stringify the result, just use result.Title.
As you already have JSON string, It's simple as a pie!
All you need to do is to call the property you want from the variable you assigned your result to.
for example:
var post_response;
$.ajax({
type: "POST",
url: "../../api/test",
data: JSON.stringify(source),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
post_response = JSON.stringify(result);
console.log("Title: "+post_response.Title);
}
});
hope this helps.
I have searched a lot and not been able to find a working solution to why my post request is not sending it's data to the server. I can send the request without data and I get my results from the server, but I just cannot send my data to the server. I have narrowed it down to the "data" attribute and assume I am just doing something wrong. Thank you.
Client
var scriptURL = "default/scripts/serverside/Scripts.aspx";
$.ajax({
type: "POST",
url: baseURL + scriptURL + "/SaveItem",
data: "{}", //works (to return a result)
//data: "{sendData: '" + dataPackage + "'}", //does not work
//data: dataPackage, //does not work
//data: { sendData: dataPackage }, //does not work
//data: { "sendData": dataPackage }, //does not work
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
de("server result:" +result);
}
});
Server
[WebMethod]
public static string SaveItem(string sendData)
{
string result = "received: " + sendData;
return result;
}
Please help, I just cant seem to get it working and know it has got to be a syntax issue...
Similar problems I have found (but no working answers):
https://stackoverflow.com/questions/7258933/jquery-ajax-data-parameter-syntax
https://stackoverflow.com/questions/7262940/webmethod-not-being-called?lq=1
Try this one:
$.ajax({
type: "POST",
url: baseURL + scriptURL + "/SaveItem",
data: $.toJSON({ sendData: dataPackage }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
de("server result:" +result);
}
});
The toJSON will convert your JS object into a proper JSON string. You could also use JSON.stringify
Try this:
var scriptURL = "default/scripts/serverside/Scripts.aspx";
$.ajax({
type: "POST",
url: baseURL + scriptURL + "/SaveItem",
data: {sendData: "string to send" }
dataType: "json",
success: function (result) {
de("server result:" +result);
}
});
I have the following ASP.net web method:
[WebMethod]
public static string SaveUserNew(string id, string[] roles)
{
doStuff(id, roles);
}
I'm calling this code from jQuery Javascript code, but I don't know the syntax for passing an array. Ordinarily, I write jQuery code to call web methods that looks like this:
$.ajax({
type: "POST",
url: "someUrl.aspx?webmethod",
data: '{"foo":"fooValue"}',
contentType: "application/json;",
dataType: "json",
}
Please shed some light on this.
Update: Here is an example of code without arrays that does work:
[WebMethod]
public static string SaveUserNew(string id)
{
return "0";
}
var jdata = '{ "id": "3TWR3"}';
$.ajax({
type: "POST",
url: "UserMgmt.aspx/SaveUserNew",
data: jdata,
contentType: "application/json;",
dataType: "json",
traditional: true
}
});
My intention is to write some code in a similar style where I pass arrays to my web method.
Passing param to webmethod is a little bit tricky. Try this one
[WebMethod]
public static string GetPrompt(string[] name)
{
return "Hello " + name[0] + " and " + name[1];
}
jscript
var param = "{'name':['jack', 'jill']}";
var option = {
error: function(request, status, error) {
alert(error);
},
cache: false,
success: function(data, status) {
alert(data.d);
},
type: "POST",
contentType: "application/json; charset=utf-8",
data: param,
dataType: "json",
url: "../Server/ArrayParam.aspx/GetPrompt"
};
$.ajax(option);
You need to
1) assign the data parameter to have an object with the properties id and roles.
2) assign the roles property an array of strings.
3) Set the traditional setting to true while passing options to ajax call.
e.g:
$.ajax({
type: "POST",
url: "someUrl.aspx?webmethod",
data: {
"id":"1",
"roles":[
"Admin",
"Something",
"Another Thing"
]
},
contentType: "application/json;",
dataType: "json",
traditional: true //#############################
}