I'm getting data as json result from controller.
But in my ajax that data is empty. Why?
Controller:
public JsonResult GetMealType(string mType)
{
var obr = new Obroci();
var obrGrid = obr.GetMealType(mType);
return Json(obrGrid, JsonRequestBehavior.AllowGet);
}
Json variable has value.:
string:
[{"Type":"M1","Price":25,"Description":"Topli obrok"}]
ajax :
var newText = $('option:selected', this).text();
$.ajax({
url: "/Dumas/GetMealType?mtype=" + newText,
type: "POST",
data: 'json',
success: function (data) {
alert(data.success);
$("#lType").val(obj.Description);
},
error: function (status, error) {
alert("An AJAX error occured: " + status + "\nError: " + error);
}
});
You must correct your Ajax code to:
$.ajax({
url: "/Dumas/GetMealType",
type: "POST",
data: JSON.stringify({ mtype: newText }),
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.success);
$("#lType").val(obj.Description);
},
error: function (data) {
alert("An AJAX error occured: " + status + "\nError: " + error);
}
});
Related
I have ajax function where i am sending two stringify objects like this:
function SaveOffsetOrder() {
var temp = sessionStorage.getItem('book');
var viewName = $.parseJSON(temp);
var BookObj = JSON.stringify({ obj: viewName })
var OffsetCommonModel = {
ProductId: $('#OffProductId').val(),
CustomerId: $("#OffCustomerId").val(),
}
var OffsetCommonObj = JSON.stringify({ 'OffsetCommonObj':
OffsetCommonModel });
$.ajax({
contentType: "application/json; charset=utf-8",
type: "Post",
url: "#Url.Content("~/Estimate/CreateOffset")",
data: OffsetCommonObj + '&' + $.param(BookObj),
dataType: 'json',
success: function (data) {
}
});
this is my action method :-
public ActionResult CreateOffset(OffsetCommonModel OffsetCommonObj, CalculationModel obj)
{
// do something with objects
}
but when i check in the console its giving error "Invalid JSON primitive"
where i am doing wrong please help..Thanks
Your data part in ajax should be something like this and no need to stringify objects individually, do that once
function SaveOffsetOrder() {
var temp = sessionStorage.getItem('book');
var viewName = $.parseJSON(temp);
// var BookObj = { obj: viewName }
var OffsetCommonModel = {
ProductId: $('#OffProductId').val(),
CustomerId: $("#OffCustomerId").val(),
}
// var OffsetCommonObj = { 'OffsetCommonObj': OffsetCommonModel };
$.ajax({
contentType: "application/json; charset=utf-8",
type: "Post",
url: "#Url.Content("~/Estimate/CreateOffset")",
data: JSON.stringify({ 'OffsetCommonObj': OffsetCommonModel, 'obj': viewName }),
dataType: 'json',
success: function (data) {
}
});
}
I need to get the value for #odata.context property from the following Json response in ajax:
{
"#odata.context":"https://site.sharepoint.com/_api/",
"#odata.type":"#oneDrive.permission",
"#odata.id":"https",
"link":{"scope":"anonymous"}
}
I would like to do something like that in code:
$.ajax({
type: "POST",
beforeSend: function (request) {
request.setRequestHeader("Authorization", 'Bearer ' + bearerToken);
},
url: serverUrl,
data: JSON.stringify(params),
dataType: 'json',
contentType: " application/json",
success: function (data) {
var myvalue= data.#odata.context; // ****???
var jsonObject = JSON.parse(data); //this line throws an error Unexpected token o in JSON at position 1
}
});
I think you can get data by this:
data["#odata.context"]
And about the JSON.parse throw exception, it caused by the data is not a JSON string.
Example
I have a database of movies, and I am looking to create a Json, and then access that json in my view. I have successfully created the json within the controller using the following code:
var movies = from m in db.Movies
select m;
string jsonData = JsonConvert.SerializeObject(movies);
This creates a json, which I have passed to the Console via writeline, and it generates the following JSON:
[{"ID":1,"Title":"When Harry Met Sally","ReleaseDate":"1989-01-11T00:00:00","Genre":"Romantic Comedy","Price":7.99,"Rating":"PG","Review":79.90},
{"ID":2,"Title":"Ghostbusters ","ReleaseDate":"1984-03-13T00:00:00","Genre":"Comedy","Price":8.99,"Rating":"PG","Review":94.90},
{"ID":3,"Title":"Ghostbusters 2","ReleaseDate":"1986-02-23T00:00:00","Genre":"Comedy","Price":9.99,"Rating":"15","Review":89.90},
{"ID":4,"Title":"Rio Bravo","ReleaseDate":"1959-04-15T00:00:00","Genre":"Western","Price":3.99,"Rating":"U","Review":91.90},
{"ID":5,"Title":"The Hangover","ReleaseDate":"2008-01-01T00:00:00","Genre":"Comedy","Price":9.99,"Rating":"18","Review":83.80},
{"ID":6,"Title":"Test","ReleaseDate":"2013-06-01T00:00:00","Genre":"Action","Price":10.00,"Rating":"18","Review":89.00}]
I then want to access that json in my view, and print it to my view. I have tried the following Ajax code, but I can't seem to get the json data to display.
<button id="test">Test</button>
<div class="inner"></div>
<script type="text/javascript">
$(document).ready(function () {
$('#test').on('click', function(){
$.ajax({
url: '#Url.Action("Index", "Movies")',
dataType: 'json',
context: document.body
}).done(function(serverdata) {
jsonData = serverdata;
$.each(jsonData, function(i, item) {
$(".inner").append("<p>" + jsonData + "</p>");
});
});
});
});
</script>
Any ideas? What am I doing wrong?
if we are talking about ASP.NET MVC then you can do this:
action code:
[HttpGet]
public JsonResult Index(int? PageId)
{
//other your code goes here
var movies = from m in db.Movies
select m;
return Json(new {result = movies}),JsonRequestBehavior.AllowGet);
}
client code:
$.ajax({
type: "GET",
url: '#Url.Action("Index", "Movies")',
dataType: 'json',
content: "application/json",
cache : false
}).done(function (serverdata) {
if(result.result.length > 0)
{
$.each(result.result, function(i, item) {
$(".inner").append("<p>" +"ID: "+ item.ID +", Title :" + item.Title+ "</p>");
});
}
else
{
alert("No movies in result");
}
}).fail(function (jqXHR, textStatus) {
alert("Internal server error." + "\n" + jqXHR.statusText );
});
try: -
<script type="text/javascript">
$(document).ready(function () {
$('#test').on('click', function(){
$.ajax({
url: '#Url.Action("Index", "Movies")',
method: 'GET',
dataType: 'json',
context: document.body
}).done(function(serverdata) {
var jsonData = serverdata;
$.each(jsonData, function(i, item) {
$(".inner").append("<p>" +"ID: "+ item.ID +", Title :" + item.Title+ "</p>");
});
});
});
});
</script>
OK new at this / long time away from it...
I have a json list created thus:
$.ajax({
url: 'http://www.somewebsite.com/land.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status) {
$.each(data, function(i, item) {
var balance = '<p>' + item.itemm + ' ' + item.amount + ' ' + item.status +
' ' + 'edit' + ' ' +
' delete' +
'</p><hr>';
total2 = total2 + parseInt(item.amount);
$("#mylbl").append(balance);
$("#mylbl5").html(total2);
});
},
error: function() {
output.text('There was an error loading the data.');
}
I'm using this method as I'm using phonegap...I have display items and add items working but want to add in edit and delete functionality...
I'm trying to add edit and delete links on each row (as above) but just cant get it sorted....
Only at delete stage .. and have tried this delete function..
function deleteRecord(id) // Get id of record . Function Call when Delete Button Click..
{
mysql_connect("localhost","454547_yeah","password");
mysql_select_db("454487_mydbdb");
var deleteStatement = mysql_query("DELETE FROM balance WHERE id=?");
db.transaction(function (tx) { tx.executeSql(deleteStatement, id, onError); alert("Delete Sucessfully"); });
}
Any help or pointers greatly appreciated ....I've trawlled the web and found nought that might help...
you can try this one
formDataEdit = {
itemm: $("#itemm"),
amount: $("#amount"),
status: $("#status")
};
$.ajax({
url: 'http://www.somewebsite.com/delete.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
data: formDataEdit,
success: function(data, status) {
alert("Edit successful");
},
error: function() {
output.text('There was an error loading the data.');
}
});
formDataDelete = {
id: $("#id")
};
$.ajax({
url: 'http://www.somewebsite.com/delete.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
data: formDataDelete,
success: function(data, status) {
alert("Delete successful");
},
error: function() {
output.text('There was an error loading the data.');
}
});
html
<b><a onclick="edit(1);">Edit</a> | <a onclick="delete(1);">Delete</a></b>
js
currentPage = {};
currentPage.edit = function(id){ //also can use for delete
alert(id);
};
I want to return multiple values from Ajax call. So I modified my codes based on this page Jquery return multiple values in ajax call
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "AJAX_custom_function.aspx/AJAX_GetFullName",
data: '{userid: "' + arguments.Value + '"}',
dataType: "json",
async: false,
success: function (data) {
alert(data);
alert(data.fullname);
},
error: function (httpRequest, textStatus, errorThrown) {
alert("status=" + textStatus + ",error=" + errorThrown);
}
});
'alert(data)' returns {"fullname": "Joe", "success" : "true"}
But 'alert(data.fullname)' returns undefined. The correct value should be Joe
Did I missing something? Any advice is very much appreciated.
AJAX_GetFullName
<System.Web.Services.WebMethod()> _
Public Shared Function AJAX_GetFullName(ByVal userid As String) As Object
Dim isValid As Boolean = False 'by default, user always not exist
Dim strFullName As String = ""
isValid = IsUserIDExist(userid, strFullName)
If isValid Then
Return "{'fullname': '" & strFullName & "', 'success': 'true' }"
Else
Return "{'fullname': '', 'success': 'false' }"
End If
End Function
Try this.
$.ajax({
type: "POST",
contentType: "application/json;",
url: "AJAX_custom_function.aspx/AJAX_GetFullName",
data: '{"userid": "' + arguments.Value + '"}',
async: false,
success: function (data) {
try {
// convert single quote to double quotes
var msg = data.replace(/'/g, "\"");
msg = $.parseJSON(msg);
alert(msg.fullname);
} catch (e) {
alert(e.Message);
}
},
error:function (xhr, status, err){
alert( "status=" + xhr.responseText + ", error=" + err );
}
});
No need to specify dataType and charset in contentType.
Try using :
success: function(data) {
if (typeof data == 'string')
{
data = jQuery.parseJSON(data);
}
alert(data.fullname);
}
To convert the string to Json object use JSON.parse(data) function with in the success function of Ajax call. i hope this will help.