transfer selected table's row (javascript DataTables) to server - javascript

here is about a javascript widget DataTables. An example can be found here.
sorry, i am not a javascript specialist. How can i transfer the selected row (practically my objects from server) back to the server in form of json-format ?
i did try to do it with this approach, but it doesn't work:
$('#save_btn').click( function () {
//table.row('.selected').remove().draw( false );
console.log ( table.rows('.selected').data());
var stringData = table.rows('.selected').data().serialize();
$.ajax({
url: '${pageContext.request.contextPath}/ajax/storeSelectedContacts',
data: stringData ,
type: "POST",
cache: false,
success: function (savingStatus) {
alert("success");
},
error: function (xhr, ajaxOptions, thrownError) {
alert("error")
}
});
} );
many thanks

First, its return array of objects.
var stringData = table.rows('.selected').data();
Second, for convert array to JSON ...
var aData = table.rows('.selected').data();
var sData = JSON.stringify(aData)
and for send to server you slould indicate that is JSON dataType: 'json'
$.ajax({
url: '${pageContext.request.contextPath}/ajax/storeSelectedContacts',
data: sData ,
type: "POST",
cache: false,
dataType: 'json',
success: function (savingStatus) {
alert("success");
},
error: function (xhr, ajaxOptions, thrownError) {
alert("error")
}
});
} );

Related

How to store my JSON data in Ck Editor

Here is my code and its not print or display my json data in ckeditor
function getRules(){
$.ajax({
url: "api",
type: "POST",
data: {
version:'0.1'
},
dataType: "json",
success:function(response){
console.log(response.data.recordslist.RulesDetails);
CKEDITOR.instances.txtEdit.setData(response.data.recordslist.RulesDetails);
},
error: function (xhr, ajaxOptions, thrownError) {
//swal("Error!", "Please try again", "error");
}
});
}
If Your URL is correct and you have URL by the name of api only edit success function to
success:function(response){ $('#txtEdit').text(response); }
this show a result in array you need to extract the array.
if you don't want to extract the array. remove
dataType: "json"
it work fine. and write the data in text editor.

Returning String Result from Ajax Method

I have a DoughnutChart chart and I would like to change the color of its parts regarding color hexa-codes saved in the database I used this Ajax method to get the color string by invoking an action method that returns JSON Result ,
getcolors: function getcolors(name) {
return $.ajax({
url: "/api/ideas/getcolors",
data: { name: name },
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data, textStatus, jqXHR) {
// return data;
},
error: function (data) {
// return "Failed";
},
async: true
});
but instead of receiving the string I received Object {readyState: 1} in the console window
However, I can find the color value stored in ResponseText element.I need your help in how can I get the color value as string.
EDIT :
To make things more clear that's where I would like to invoke the ajax method to receive the color string then I will be able to push in the chart color array .
getColorArray: function getColorArray(categories) {
var colors = [];
for (var i = 0; i < categories.length; i++) {
console.log(this.getcolors("Risk"));
//colors.push(this.getcolors(categories[i]));
}
return colors;
}
Why your code is like this?
success: function (data, textStatus, jqXHR) {
// return data;
},
Did you use it?
success: function (data, textStatus, jqXHR) {
console.log(data);
}
Ok, i got it. When you use an ajax request your will work with asynchronous data, to do this you need return a promise in your method. Please, try to use the code below.
getcolors: function getcolors(name) {
return $.ajax({
url: "/api/ideas/getcolors",
data: { name: name },
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
});
}
And for use your function use this code:
getcolors("name").done(function(result){
console.log(result);
});
Or you can use a callback
getcolors: function getcolors(name, success, error) {
return $.ajax({
url: "/api/ideas/getcolors",
data: { name: name },
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
success(data);
},
error: function(data){
error(data);
}
});
}
... And for use with callbacks:
getcolors("name", function(data){
//success function
console.log(data);
}, function(){
//Error function
console.log(data);
})
Try one of this options and tell the result.
The Solution
First of all I would like to thank Mateus Koppe for his efforts, through his solution I got the way to solve my problem ..
What I did simply is just I received the ResponseText from the incoming successful result in my Ajax method and then I passed it to a callback function that handles the result like the following :
getcolors: function getcolors(name, handleData) {
$.ajax({
url: "/api/ideas/getcolors",
data: { name: name },
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
handleData(data.responseText);
//return data.responseText;
},
error: function (data) {
handleData(data.responseText);
//return data.responseText;
},
async: false
});
then I worked with getColorArrayModified to loop through my categories list and populate its own color.
getColorArrayModified: function getColorArrayModified(categories) {
var colors = [];
for (var i = 0; i < categories.length; i++) {
this.getcolors(categories[i], function (output) {
colors.push(output);
});
}
return colors;
}
Thanks for all :).

How to send WebSocket data from View to Controller and reworked data send to View with Ajax

I'm trying send websocket data from view to controller and again reworked data send to view in for example table with button or something like this.
Now sending data to controller works:
View:
<script type="text/javascript">
var webSocket;
var webSocketValue;
function webSocketResults() {
webSocket = new WebSocket("ws://......");
webSocket.onmessage = function (event) {
webSocketValue = event.data;
$("#webSocketValue").text(webSocketValue);
$.ajax({
url: "#Url.Action("getWebSocketResults", "Home")",
type: "POST",
contentType: "application/json",
data: webSocketValue
});
};
showCurrenciesData(webSocketValue);
}
function showCurrenciesData() {
$.ajax({
cache: false,
type: "GET",
url: "#Url.Action("getWebSocketResults", "Home")",
dataType: 'json',
success: function (result) {
alert("Sukcess!!" + result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed to retrieve data.');
}
});
}
window.onload = webSocketResults;
Controller
public ActionResult getWebSocketResults(Currencies currencies)
{ //do something with data "currencies" and dynamicly send this to view
var webSocketItems = currencies.items.ToList();
return Json(webSocketItems, JsonRequestBehavior.AllowGet);
}
In Controller i have data (Object) from View.
How to send this data dynamically. New data from WebSocket arrives every minute.
Sending data to view does'nt work.
you called two times. first times did not handle result. second times no have paremeter.
<script type="text/javascript">
var webSocket;
var webSocketValue;
function webSocketResults() {
webSocket = new WebSocket("ws://......");
webSocket.onmessage = function (event) {
showCurrenciesData(event.data);
};
}
function showCurrenciesData(data) {
$.ajax({
cache: false,
type: "GET",
url: "#Url.Action("getWebSocketResults", "Home")",
dataType: 'json',
data: data,
success: function (result) {
alert("Sukcess!!" + result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed to retrieve data.');
}
});
}
window.onload = webSocketResults;

Error occurs when i use jQuery Ajax

$('#deviceLoadMore') is a link. When this link is being clicked, it will trigger a ajax to the web service I have created.
The problem I'm having now is it keeps on throwing this error in the console.log
Uncaught TypeError: Converting circular structure to JSON. But when I just paste the ajax part in the console.log, it able to retrieve the data back. I have checked that all the value is just a normal string and integer.
I was wondering why i can trigger in console log without having any issue and couldn't if i just click on the link?
var currentContextSection = '<%=currentSection %>';
var currentTemplateIds = '<%=templateIds %>';
var currentItemPerPage = <%=itemPerPage %>;
var currentPageIndex = <%=currentPage %>;
var arguments = { templateIds:'<%=templateIds %>' , currentSection:'<%=templateIds %>', currentPage:currentPageIndex, itemPerPage:currentItemPerPage };
$(document).ready(function () {
$('#deviceLoadMore').click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/AJAX/WS.asmx/GetItems",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(arguments),
dataProcess: false
}).done(function (data) {
test = data;
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
});
});
});
------ EDIT -------
If I have this:
var arguments = {"templateIds":currentTemplateIds ,"currentSection":currentContextSection,"currentPage":currentPageIndex,"itemPerPage":currentItemPerPage};
and executing with the ajax data:JSON.stringify(arguments), i will get the following errror:
Converting circular structure to JSON.
When I console.log the "arguments", it displays:
Object {templateIds: "963C1D18A93849309D6014CE2135173C", currentSection: "Personal", currentPage: 1, itemPerPage: 8}
And it displays this when I console.log JSON.stringify(arguments):
"{"templateIds":"963C1D18A93849309D6014CE2135173C","currentSection":"Personal","currentPage":1,"itemPerPage":8}"
After google around for some successfully implemented ajax sample, I changed my code to the following, and it works! And I have no idea why it works this way.
$(document).ready(function () {
$('#deviceLoadMore').click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/AJAX/WS.asmx/GetItems",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({"templateIds":currentTemplateIds ,"currentSection":currentContextSection,"currentPage":currentPageIndex,"itemPerPage":currentItemPerPage}),
dataProcess: false
}).done(function (data) {
test = data;
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
});
});
});
try after removing, JSON.stringify from
data: JSON.stringify(arguments),

Unable to access json data retrieved from php page using jquery $.ajax

How to access this json data in JavaScript.
when I alert it the result is undefined
Here is jQuery code
$.ajax({
type: "POST",
url: "frmMktHelpGridd.php",
data: {
labNo: secondElement
},
dataType: "json",
beforeSend: function () {
// Do something before sending request to server
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error has occured');
alert(errorThrown);
},
success: function (data) {
//Here is the problem
alert(data[0]['Result']);
}
});
This is PHP code
$data=array($no);
for($i=0;($i<$no && ($row=mysql_fetch_array($result)));$i++)
{
$data[$i]=array();
$data[$i]['Result'] = $row['Result'];
$data[$i]['TestCode'] = $row['TestCode'];
$data[$i]['TestStatus'] = $row['TestStatus'];
$data[$i]['SrNo'] = $row['SrNo'];
}
$data1=json_encode($data);
echo $data1;
exit;
I have tested the PHP file independently,
The json data is output as follows:
[{"Result":"1","TestCode":"22","TestStatus":"0","SrNo":"1"},{"Result":"1","TestCode":"23","TestStatus":"1","SrNo":"2"}]
$.ajax({
type: "POST",
url: "frmMktHelpGridd.php",
data: {
labNo: secondElement
},
dataType: "json",
beforeSend: function () {
// Do something before sending request to server
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error has occured');
alert(errorThrown);
},
success: function (data) {
//Added parse json
var data = jQuery.parseJSON(data)
alert(data[0]['Result']);
}
});
You can access to your data by doing
data[0].Result
It's an Object, not an array.
so data[0]['Result'] it's not the proper way
EDIT:
Since you have more objects, you have to do a loop this way:
$.each(data, function(key, val){
console.log(val.Result);
console.log(val.TestCode);
//...
});
When you see something like
{
"foo":"bar",
...
}
you can access to it the same way as above:
name_of_the_object.foo
that will have the value "bar"
Try to add parse JSON. I have added. Now it may be work.
$.ajax({
type: "POST",
url: "frmMktHelpGridd.php",
data: {
labNo: secondElement
},
dataType: "json",
beforeSend: function () {
// Do something before sending request to server
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error has occured');
alert(errorThrown);
},
success: function (data) {
//Added parse json
var data = $.parseJSON(data)
alert(data[0]['Result']);
}
});

Categories