how to print id from ajax data
data.id is undefined
$.ajax({
url: "userdetails",
type: "get",
success: function (data) {
alert(data);
console.log($(this).serialize());
$("#ajaxdata").append(data);
alert(data.id)
}
});
data value is below
[{
"id": 28,
"firstname": "asddsf",
"lastname": "sss",
"email": "terrymol.christian#roarsinc.com",
"role_id": 1,
"status": "Active"
}, {
"id": 87,
"firstname": "df",
"lastname": "dsfsd",
"email": "sdfsdf#dfds.hgj",
"role_id": 1,
"status": "Active"
}]
The response would be not treated as JSON if the data type is not being specified or server is not mentioning it in the response header.
Try this
$.ajax({
url: "userdetails",
type: "get",
dataType: "json",
success: function (data) {
alert(data);
console.log($(this).serialize());
$("#ajaxdata").append(data);
alert(data.id)
}
});
Update:
The response looks like an array of objects. You would need to try alert(data[0].id)
Related
I am working in mvc and i got the parserError when i call the controller using ajax and want to set list using datatable. but i don't know what i am doing wrong here.
when try to debug then i was not got my self in controller.
After i searched i found that use datatype:'text' but that don't want it.
I want only json data and want to set using data table.
but don't know what i doing wrong here.
Any one have idea, let me share here.
<div class="card-body">
<table id="userGrid" class="table table-bordered table-striped">
<thead>
<tr>
<th>Email</th>
<th>Password</th>
<th>Zipcode</th>
<th>IsAdmin</th>
<th>IsFirstTimeLoggedIn</th>
</tr>
</thead>
</table>
</div>
#section Scripts{
<script type="text/javascript">
$(function () {
$.ajax({
type: "POST",
url: "/User/UserList",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert("failure:"+response.d);
},
error: function (response, jqXHR, textStatus, errorThrown) {
debugger
alert("Error:"+response.d);
}
});
});
function OnSuccess(response) {
$("#userGrid").DataTable(
{
"paging": true,
"lengthChange": false,
"searching": false,
"ordering": true,
"info": true,
"autoWidth": false,
"responsive": true,
"serverSide": true,
"processing":true,
data: response,
columns: [{ "data": "Email" },
{ "data": "Password" },
{ "data": "Zipcode" },
{ "data": "IsAdmin" },
{ "data": "IsFirstTimeLoggedIn" }]
});
};
</script>
}
public ActionResult UserList()
{
try
{
List<User> users = _userService.GetAllUsers().ToList();
return Json(new { data = users }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
_log.ErrorFormat("Error in get user list. Error : {0}", ex.Message);
_log.Error(ex);
throw;
}
}
I want only json data and want to set using data table
Since the json format returned by the UserList method contains data before the users , you need to obtain the returned data collection through response.data in the success method of ajax.
On the other hand, because you get the data in the success method (not directly through ajax), you need to comment out the "serverSide": true statement.
Here is the example:
function OnSuccess(response) {
$("#userGrid").DataTable(
{
"paging": true,
"lengthChange": false,
"searching": false,
"ordering": true,
"info": true,
"autoWidth": false,
"responsive": true,
// "serverSide": true,
"processing":true,
data: response.data,
columns: [{ "data": "Email" },
{ "data": "Password" },
{ "data": "Zipcode" },
{ "data": "IsAdmin" },
{ "data": "IsFirstTimeLoggedIn" }]
});
};
Here is the test result:
How do I send an array with json using ajax? I want to store email and name:
$.ajax({
url: 'index.php?route=module/newsletters/news',
type: 'post',
data: 'email=' + $('#txtemail').val() ,
dataType: 'json',
success: function(json) {
alert(json.message);
}
});
Let's suppose you have an array?
var array = [
"student1" : {
"name": "jon",
"email": "test#example.com"
},
"student2" : {
"name": "jon2",
"email": "test2#example.com"
}
]
$.post('index.php?route=module/newsletters/news', {
data : JSON.stringify(array),
datatype : 'application/json',
}, function(success) {
console.log(success)
});
Your question is not clear.please write your question in correct format.then community can be resolve your question easily.
I assume your problem and give solution for that.
var array = {name:'dua',email:'dua#gmail.com'};
$.post('index.php?route=module/newsletters/news', {
data : JSON.stringify(array)
}, function(success) {
console.log(success)
});
var postData = { "email":email,"name":name }
$.ajax({
url: 'index.php?route=module/newsletters/news',
type: 'post',
data: postData,
dataType: 'json',
success: function(json) {
alert(json.message);
}
});
I need your help, I have this piece of code in the controller side
public bool DraftMessage(message[] draftMessages, HttpPostedFileBase[] files = null)
{
return true;
}
and I use this client side code to send the data
function DraftMessage()
{
var myArray = [{ 'To': [1, 2], "Title": "Hello" }, { 'To': [1, 2], "Title": "Hello" }]
$.ajax({
type: "POST",
url: "#Url.Action("DraftMessage","Activities")",
datatype: "json",
traditional: true,
data: JSON.stringify({ draftMessages: myArray }),
beforeSend: function () { }
}).done(function (data) {});
}
$("input, select, textarea").change(function () { DraftMessage(); });
var contents = $('.note-editable').html();
$(".compose-message").on("blur", ".note-editable", function () {
if (contents != $(this).html()) {
DraftMessage();
contents = $(this).html();
}
});
but when I debug it I found that the array of messages in the controller is null so could anyone guide me about what I did wrong and help me to fix this issue.
You need to set contentType as "application/json"
function DraftMessage() {
var myArray = [{ 'To': [1, 2], "Title": "Hello" }, { 'To': [1, 2], "Title": "Hello" }];
$.ajax({
type: "POST",
url: "#Url.Action("DraftMessage","Home")",
contentType: "application/json",
data: JSON.stringify({ draftMessages: myArray })
}).done(function (data) {
console.log(data);
});
}
The default value of contentType header is "application/x-www-form-urlencoded" . Since we are sending the json stringified version of a a complex data structure, we should explicitly specify the contentType
I need a store to gather data from a URL, but the URL needs a POST of JSON data in order to create the correct response (in this example, a set of disclaimer questions the user must answer, based on the products in his shopping cart.)
Here's what I have so far. I want to send the cart and get the question set in response:
QuestionStore: {
autoLoad: false,
model: 'RefCig.model.Question',
proxy: {
type: 'ajax',
url: '/refcig-services/questionsForCart',
actionMethods: {
create: 'POST',
read: 'POST',
update: 'POST',
destroy: 'POST'
},
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
reader: {
type: 'json'
},
writer: {
type: 'json'
}
}
}
On submit:
var cartStore = Ext.getStore('CartStore');
cartItems = Ext.Array.pluck(cartStore.data.items, 'data');
var questionStore = this.getStore('QuestionStore');
questionStore.load({params:cartItems});
A console.log of Ext.encode(cartItems) is exactly what I want to send to the backend:
[{
"id": 19,
"pricePerUnit": 20,
"denominationsPerUnit": 1,
"blahblahblah": 1,
"unitQuantity": 1,
"total_item_count": null,
"subtotal": 20
}]
Yet the request is malformed:
{
"0": {
"id": 19,
"pricePerUnit": 20,
"denominationsPerUnit": 1,
"unitQuantity": 1,
"total_item_count": null,
"subtotal": 20
},
"page": 1,
"start": 0,
"limit": 25
}
How should I be telling my QuestionStore to form its request body the way I want?
Thanks in advance.
Technically your requirement can be met by using a custom proxy. You implement your own buildRequest method in there, which is a stripped down version of the original one:
Ext.define('MyProxy', {
extend: 'Ext.data.proxy.Ajax',
alias: 'proxy.my',
paramsAsJson: true,
buildRequest: function(operation) {
var me = this,
params = operation.getParams(),
request, operationId, idParam;
operationId = operation.getId();
idParam = me.getIdParam();
if (operationId !== undefined && params[idParam] === undefined) {
params[idParam] = operationId;
}
request = new Ext.data.Request({
params: params,
action: operation.getAction(),
records: operation.getRecords(),
url: operation.getUrl(),
operation: operation,
proxy: me
});
request.setUrl(me.buildUrl(request));
operation.setRequest(request);
return request;
}
});
Then, in the store definition, you simply use the proxy:
proxy: {
type: 'my',
// .....
However, I would recommend another way.
Do something like:
questionStore.load({params: {cartItems: cartItems}});
instead of
questionStore.load({params:cartItems});
That will make the request body look like this:
{
"cartItems": [{
"id": 19,
"pricePerUnit": 20,
"denominationsPerUnit": 1,
"blahblahblah": 1,
"unitQuantity": 1,
"total_item_count": null,
"subtotal": 20
}],
"page": 1,
"start": 0,
"limit": 25
}
You would need to adjust your server side to retrieve the cartItems array from the payload.
Here's the JSON:
{
"page": "1",
"total": "1",
"records": "2",
"rows": [
{
"Id": 3,
"FirstName": "Test",
"LastName": "Testerson",
"CustomerNumber": "1234",
"EmailAddress": "test#test.com",
"Subject": "Test1",
"OrderNumber": "4321",
"Comments": "This is a test"
},
{
"Id": 4,
"FirstName": "Test2",
"LastName": "Testerson2",
"CustomerNumber": "2222",
"EmailAddress": "test#test.com",
"Subject": "Test1",
"OrderNumber": "3333",
"Comments": "This is a test"
}
]
}
Here's my current script and markup (why isn't this working?):
<table id="list1"></table>
<div id="pager1"></div>
<script type="text/javascript">
function getData(pdata) {
var params = new Object();
params.page = pdata.page;
params.pageSize = pdata.rows;
params.sortIndex = pdata.sidx;
params.sortDirection = pdata.sord;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ScriptServices/PNScriptService.asmx/GetContactRequests",
data: JSON.stringify(params),
dataType: "json",
success: function (data, textStatus) {
if (textStatus == "success") {
var thegrid = $("#list1")[0];
thegrid.addJSONData(data.d);
}
},
error: function (data, textStatus) {
alert('An error has occured retrieving the data.');
}
});
}
$(document).ready(function () {
$("#list1").jqGrid({
datatype: function (pdata) {
getData(pdata);
},
jsonReader: {
page: "page",
total: "total",
records: "records",
root: "rows",
id: "Id",
repeatitems: false
},
colNames: ['Id', 'FirstName', 'LastName', 'CustomerNumber', 'EmailAddress', 'Subject', 'OrderNumber', 'Comments'],
colModel: [
{ name: 'Id', index: 'Id', width: 90 },
{ name: 'FirstName', index: 'FirstName', width: 100 },
{ name: 'LastName', index: 'LastName', width: 100 },
{ name: 'CustomerNumber', index: 'CustomerNumber', width: 80, align: "right" },
{ name: 'EmailAddress', index: 'EmailAddress', width: 100 },
{ name: 'Subject', index: 'Subject', width: 80 },
{ name: 'OrderNumber', index: 'OrderNumber', width: 80, align: "right" },
{ name: 'Comments', index: 'Comments', width: 250, sortable: false }
],
rowNum: 10,
rowList: [10, 20, 30],
pager: $('#pager1'),
sortname: 'Id',
viewrecords: true,
sortorder: "desc",
caption: "Contact Requests"
});
});
</script>
btw: The JSON string above is the exact string returned by the script service. I can hit a break point in my script service and grab that string, and I can alert the string in the calling ajax script on success, and the strings are identical. So I know it's not the script service, and I know that that json string is being passed, as shown, into the jqGrid.
Your problem is that you user very very old template code for loading JSON data. If your server produce the JSON data which you posted you can simplify for code to the following.
In another answers you will find more code examples in case you use ASMX, which produce a litle other JSON code as you posted.
Thanks Oleg for the info, but it turned out to be the following:
thegrid.addJSONData(JSON.parse(data.d));
I needed to JSON.parse the data before passing it into the grid.