jQuery Ajax showing 0 instead of Array - javascript

I'm trying pushing json inside of array, but when i send the params with Ajax it put 0 instead of Array...
Not really sure how do i get rid of it..
If anyone have any idea how to fix that I'll really appreciate it!
var $selector = $(this).find('.button-selector');
var $element = $(this).find('.button-type');
var $attr = $(this).find('.selector ul li.active').attr('type');
var $text = $(this).find('textarea').val();
var $buttons = [];
$selector.each(function(){
var $titleBtn = $(this).find('input[name=button-title]').val();
if($attr == 'block'){
var $payload = "";
var $value = $element.find('.block-select select').val();
if($value == 1) {
$payload = "JOIN_CONVERSATION_"+story_id+"";
} else if ($value == 2) {
$payload = "NEXT_BITE_"+story_id+"";
} else if ($value == 3) {
$payload = "INSTANT_ARTICLE_"+story_id+"";
}
button = {
"type": "postback",
"title": $titleBtn,
"payload": $payload
};
$buttons.push(button)
} else if($attr == 'url') {
var $url = $element.find('.url-select input[type=url]').val();
var $webView = $element.find('.url-select select').val();
button = {
"type": "web_url",
"url": $url,
"title": $titleBtn,
"webview_height_ratio": $webView
};
$buttons.push(button)
}
});
$.ajax({
async: false,
type: 'POST',
url: '/variable',
dataType: 'json',
data: {
"element":{
"notification_type": notification_type,
"message": {
"attachment": {
"type": "template",
"payload": {
"template_type": "button",
"text": $text,
"buttons": $buttons
}
}
}
}
}
});
The output for buttons is:
"buttons"=>{"0"=>{"type"=>"postback", "title"=>"rwerwe", "payload"=>"JOIN_CONVERSATION_256"}}
Intead of:
"buttons"=>[{"type"=>"postback", "title"=>"rwerwe", "payload"=>"JOIN_CONVERSATION_256"}]

I hope this should fix your case.
You need to use JSON.stringify to first properly serialize your object to JSON, and then specify the contentType: "application/json" so your server understands it's JSON and deserialize it back. This should do the trick:
var jsonData = {
"element":{
"notification_type": notification_type,
"message": {
"attachment": {
"type": "template",
"payload": {
"template_type": "button",
"text": $text,
"buttons": $buttons
}
}
}
}
};
$.ajax({
async: false,
type: 'POST',
url: '/variable',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(jsonData)
});

Related

Using the content of a variable returned by DataTables in another part of the script

How can I use the "DeviceID" in the "columns:" in another part of the script. I have tried all manner of things like re positioning some of the code but no matter what I do I can't get it to work.
I need to use the "DeviceID" as a variable in
"url: 'get_wayfinder_offline_status.php', data: { DeviceID: deviceid },"
Look at << USE THIS IN PART MARKED "HERE"
$(document).ready(function() {
var table = $('#WayFinderStatusTable').DataTable({
ordering: false,
paging: false,
searching: false,
bInfo: false,
responsive: true,
fixedHeader: true,
scrollX: false,
pageResize: true,
ajax: {
url: 'check_wayfinder_status.php',
dataSrc: ''
},
columns: [{
data: 'DisplayDescription',
"sWidth": "100%"
},
{
data: 'DeviceName',
"visible": false
},
{
data: 'MessageCount',
"visible": false
},
{
data: 'BoardOverride',
"visible": false
},
{
data: 'DeviceID',
"visible": false
}, // << USE THIS IN PART MAKED "HERE"
],
rowCallback: function(row, data, dataIndex) {
if (data.MessageCount == 2) {
$(row).find('td:eq(0)').addClass('WayFinderStatusTableOn HeaderStatusWayfinderRedTextBlink');
} else if (data.BoardOverride == 1) {
$(row).find('td:eq(0)').addClass('WayFinderStatusTableOverrideOn ');
$('#WayFinderStatusTable tbody').on('click', 'tr', function() {
var hotelid = "<?php echo $_SESSION['_amember_user']['hotelid'];?>";
var data = table.row(this).data();
var deviceid = data.DeviceID;
console.log("DEVICE ID", deviceid);
$.ajax({
url: 'get_wayfinder_override_status.php',
data: {
DeviceID: deviceid
},
type: 'POST',
dataType: 'JSON',
success: function(data) {
var result = JSON.stringify(data);
result = JSON.parse(result);
if (result.length > 0) {
console.log("BoardName", result);
$('#EditOverrideWayfinderRecordID').val(result[0]);
$('#EditOverrideWayfinderBoardName').val(result[1]);
var testimage = result[2];
console.log("TEST IMAGE", testimage);
$('#EditOverrideWayfinderImage').val(result[2]);
var imagepath = '../../../../conf/conf_images/override/' + hotelid + '/' + result[2];
$("#EditOverrideWayfinderLookUpCompanyImage").attr("src", imagepath);
$("#EditOverrideWayfinderImagePreview").attr("src", imagepath);
$('#EditOverrideWayfinderRoomFromDate').val(result[3]);
$('#EditOverrideWayfinderRoomFromTimeH').val(result[4]);
$('#EditOverrideWayfinderRoomFromTimeM').val(result[5]);
$('#EditOverrideWayfinderRoomToDate').val(result[6]);
$('#EditOverrideWayfinderRoomToTimeH').val(result[7]);
$('#EditOverrideWayfinderRoomToTimeM').val(result[8]);
$('#EditOverrideWayfinderPromotionName').val(result[9]);
$('#EditOverrideWayfinderHardwareID').val(result[10]);
$('#edit_wayfinder_override_data_modal').modal('show');
}
}
});
});
} else if (data.BoardOverride == "") {
$(row).find('td:eq(0)').addClass('WayFinderStatusTableOff');
}
},
});
$(document).on('click', '.WayFinderStatusTableOff', function(e) {
$('#wayfinder_override_data_modal').modal('show');
});
$(document).on('click', '.WayFinderStatusTableOn', function(e) {
console.log("OFFLINE CLICKED");
$.ajax({
url: 'get_wayfinder_offline_status.php',
data: {
DeviceID: deviceid //<<HERE
},
type: 'POST',
dataType: 'JSON',
success: function(data) {
var result = JSON.stringify(data);
result = JSON.parse(result);
if (result.length > 0) {
// DO SOMETHING
}
}
});
$('#offline_data_modal').modal('show');
});
setInterval(function() {
$('#WayFinderStatusTable').DataTable().ajax.reload();
}, 30000);
});
Based on structure of your datatables and column, clicked on a row the deviceId is find by using the method table.row( this ).data(); and next find the right index of the data.
$('#WayFinderStatusTable').on('click', 'tr', function () {
const data = table.row( this ).data();
const deviceId = data[4];
alert(deviceId + ' -> deviceid');
});

how to access properties of json string

I have a JSON string coming from my database table but it has empty root element name
{"": [
{"ID":18,"MenuName":"dsadasdasd","IsActive":"InActive"},
{"ID":17,"MenuName":"Karachi","IsActive":"Active"},
{"ID":2,"MenuName":"User Management","IsActive":"Active"},
{"ID":1,"MenuName":"Home","IsActive":"Active"}
]}
I am trying to access this JSON with below jquery ajax call method
function Get_DataTable() {
$.ajax({
url: "GridView_JqueryFunctionality.aspx/CallDataTable_EmptyRootName",
type: "POST",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data.d) // showing json is fine
var MyData = $.parseJSON(data.d);
for (i = 0; i < Object.keys(MyData).length; i++) {
alert(MyData[i].ID + ' : ' + MyData[i].MenuName);
}
}
});
}
My Webmethod
[WebMethod(true)]
public static string CallDataTable_EmptyRootName(){
List<Category> Categories = new List<Category>();
clsMenu objMenu = new clsMenu();
DataTable dt = new DataTable();
objMenu.GetAllMenu(dt);
if (dt.Rows.Count > 0){
string jsonString = ConversionExtension.DataTabelToJson(dt);
return jsonString.ToString();
}else{
return "";
}
}
it is giving me undefined : undefined... Please help me. I am stuck now
Try this:
function Get_DataTable() {
$.ajax({
url: "GridView_JqueryFunctionality.aspx/CallDataTable_EmptyRootName",
type: "POST",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data.d) // showing json is fine
var MyData = $.parseJSON(data.d)[""];
for (i = 0; i < MyData.length; i++) {
alert(MyData[i].ID + ' : ' + MyData[i].MenuName);
}
}
});
}
Assuming you have a variable name for your object, you can reference it with an empty string as the key.
var a = {
"": [
{
"ID": 18,
"MenuName": "dsadasdasd",
"IsActive": "InActive"
},
{
"ID": 17,
"MenuName": "Karachi",
"IsActive": "Active"
},
{
"ID": 2,
"MenuName": "User Management",
"IsActive": "Active"
},
{
"ID": 1,
"MenuName": "Home",
"IsActive": "Active"
}
]
}
console.log(a[""]);
Try running the above code notice we can still access the objects elements despite having an empty root name.
You have to access with brackets the no-name property in the root object, and then iterate over the array of items.
success: function(response) {
var data = $.parseJSON(response.d);
var list = data[""];
list.forEach(function(item, i) {
console.log(item);
console.log(item.ID, ' -> ', item.MenuName);
});
}

Read JSON data from AJAX [duplicate]

This question already has answers here:
How to 'output' a JavaScript variable into an HTML div
(5 answers)
Closed 5 years ago.
Consider:
$.ajax({
type: "POST",
url: "/myurl",
async: false,
data: JSON.stringify({}),
contentType: "application/json",
complete: function (data) {
var results = data["responseText"];
alert(results)
},
error: function () {
alert("Error")
}
});
The JSON returned:
{"jsonrpc": "2.0", "id": null, "result": "{\"ids\": [{\"id\": 1, \"name\": \"Messi\"}, {\"id\": 2, \"name\": \"Ronaldo\"}]}"}
How can I append the data in div like the following?
1 Messi
2 Ronaldo
Pick the ids property from your Ajax response, loop through it and prepare your required HTML structure using that info. In the end, insert this HTML string in your HTML page.
/*
$.ajax({
type: "POST",
url: "/myurl",
async: false,
data: JSON.stringify({}),
contentType: "application/json",
complete: function (data) {
var response = data["responseText"];
var insertDatas = JSON.parse(response.result);
var htmlString = "";
insertDatas.ids.forEach(function( item ){
htmlString += '<li>'+item.name+'</li>';
});//forEach()
$("#players-list").html( htmlString );
},
error: function () {
alert("Error")
}
});
*/
var response = {
"jsonrpc": "2.0",
"id": null,
"result":
{"ids":
[
{"id": 1, "name": "Messi"},
{"id": 2, "name": "Ronaldo"}
]
}
};
var htmlString = "";
response.result.ids.forEach(function(item){
htmlString += '<li>' + item.name + '</li>';
});//forEach()
$("#players-list").html( htmlString );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<ol id="players-list"></ol>

Toggle between ajax data objects

I'd like to toggle between 2 ajax data objects on click of a link. Its not possible to do this with the method below, can anyone suggest a way I can do this? Thanks!
jQuery.ajax({
url: "/somefile.php",
dataType: 'JSON',
type: 'POST',
jQuery(".togglesearch").toggle(
function () {
data: JSON.stringify({
"Name": jQuery("#searchfield").val(),
"Number": ""
}),
},
function () {
data: JSON.stringify({
"Name": "",
"Number": jQuery("#searchfield").val()
}),
}
);
var data = ["Name", "Number"];
var obj = {"Name":"", "Number":""};
var val = jQuery("#searchfield").val();
var n = 0;
var res;
$("button").click(function() {
obj[data[n]] = val;
obj[data[n === 0 ? n + 1 : n- 1]] = "";
res = JSON.stringify(obj);
$("label").text(JSON.stringify(res));
// do ajax stuff
/*
jQuery.ajax({
url: "/somefile.php",
dataType: "JSON",
type: "POST",
data: res
})
*/
n = n === 0 ? 1 : 0
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<button>click</button>
<input type="text" id="searchfield" value="123" /><label></label>
I think you'll have to put each different ajax call inside the toggles:
jQuery(".togglesearch").toggle(
function () {
jQuery.ajax({
url: "/somefile.php",
dataType: 'JSON',
type: 'POST',
data: JSON.stringify({
"Name": jQuery("#searchfield").val(),
"Number": ""
})
});
},
function () {
jQuery.ajax({
url: "/somefile.php",
dataType: 'JSON',
type: 'POST',
data: JSON.stringify({
"Name": "",
"Number": jQuery("#searchfield").val()
})
});
}
});
Try this:
jQuery(".togglesearch").toggle(function() {
var data = { "Name": "", "Number": jQuery("#searchfield").val() };
callAjax(data);
}, function(){
var data = { "Name": jQuery("#searchfield").val(), "Number": "" };
callAjax(data);
});
function callAjax(data) {
jQuery.ajax({
url: "/somefile.php",
dataType: 'JSON',
type: 'POST',
data: JSON.stringify(data),
success: function(response) { }
)};
}
In toggle finally call a function with ajax call. Let me know if it works for you.

Populating the AJAX url in a JSTree with model information

I am populating a JSTree view with ajax commands. My current JS code is as follows
$(document).ready(function() {
$("#navigation").jstree({
"json_data": {
"ajax": {
"url": function (node) {
var nodeId = "";
var url = "";
if (node == -1) {
url = "#Url.Action("BaseTreeItems", "Events")";
} else {
nodeId = node.attr('id');
url = "#Url.Action("EventTreeItems", "Events")" +"?selectedYear=" + nodeId;
}
return url;
},
"dataType": "text json",
"contentType": "application/json charset=utf-8",
"data": function(n) { return { id: n.attr ? n.attr("id") : 0 }; },
"success": function() {
}
}
},
"themes": {
"theme": "classic"
},
"plugins": ["themes", "json_data", "ui"]
});
});
I would like to eliminate the if statement from the "ajax" property and fill it with the JSON data that is coming from the server. The JSON data looks like this
[{"data":{"title":"2012","attr":{"href":"/Events/EventList?selectedYear=2012"}},"attr":{"id":"2012","selected":false,"ajax":"/Events/EventTreeItems?selectedYear=2012"},"children":null,"state":"closed"},.....]
How can I feed the "ajax" property from the json into the "ajax" property in the JSTree?
For future reference I fixed it by doing the following
.jstree({
"json_data": {
"ajax": {
"url": function (node) {
var url;
if (node == -1) {
url = "#Url.Action("BaseTreeItems", "Events")";
} else {
url = node.attr('ajax');
}
return url;
},
"dataType": "text json",
"contentType": "application/json charset=utf-8",
"data": function(n) { return { id: n.attr ? n.attr("id") : 0, ajax: n.attr ? n.attr("ajax") : 0 }; },
"success": function() {
}
}
},

Categories