I am looking to call an ajax function inside the Datatables mRender function that will use an id from the present ajax source to get data from a different ajax source.
To put this into perspective, I have:
A listing of requisitions from different clients in one Datatable.
In this listing I have a client id. I want to get the client Name to be shown on the table instead of the client Id. However the Client Name and other client details are in the clients table hence these details are not in the requisitions json data. But I have the Client Id.
How do I use this to get client name inside the mrender function? E.g
{"sTitle":"Client","mData":null,
"mRender":function(data){
//ajax function
}
},
Thank you in advance,
Regards.
I don't believe this is how you are supposed to deal with your data. However I also use an AJAX data source in my mRender function as stated below.
$(document).ready(function(e){
$('.products').dataTable({
"bProcessing": true,
"sAjaxSource": window.location.protocol + "//" + window.location.hostname + '/product/getAll',
"aoColumns": [
{ "sTitle": "Pid", "bVisible" : false},
{ "sTitle": "Pname" },
{ "sTitle": "Pprice" },
{ "sTitle": "Pgroups",
"mRender" : function( data, type, full ){
console.log( data, type, full );
console.log(category.getAll());
return 'test';
}
}
]
});
});
De category object is initialized in a selfinvoking function. I used this to prevent the function from loading the data remotely each time the function is called.
It looks like this:
(function(){
if(typeof category === 'undefined'){
category = {};
}
category.getAll = function(){
if(typeof category.all === 'undefined'){
$.ajax({
'type' : 'POST',
'async': false,
'url' : window.location.protocol + "//" + window.location.hostname + "/category/getAll",
'success' : function(data){
console.log(data);
category.all = data;
},
'error': function(a,b,c){
console.log("You shall not pass!",a,b,c);
alert('stop');
}
});
}
return category.all;
}
})();
Related
I have this code where i am trying to retrieve data from model.findall() and display in UI as table
model.js
define(['jquery', 'can'], function ($, can) {
var serviceModel = can.Model.extend({
findAll: function (params,servicename) {
return $.ajax({
type: 'POST',
dataType: 'JSON',
contentType: 'application/json',
url: 'data/+ servicename',
success: function (data) {
console.log("Success ");
},
error: function () {
console.log("Error");
}
});
}
}, {});
return serviceModel;
});
controller.js
serviceModel.findAll(params,"SP_table", function(data) {
if (data.status === "success") {
$('#idtable').dataTable().fnClearTable();
$('#idtable').dataTable().fnAddData(data.result);
}else{
alert("inside alert");
}
});
issue is in serviceModel.findAll() i am unable to get data inside serviceModel.findAll() because data is in the form of stored procedure or macro, which i am getting using "servicename" from function above
please let me know how to resolve this issue.
You can access the raw xhr data from the ajax call and convert it to an appropriate format by overriding the parseModels method:
https://canjs.com/docs/can.Model.parseModels.html
Overwriting parseModels If your service returns data like:
{ thingsToDo: [{name: "dishes", id: 5}] } You will want to overwrite
parseModels to pass the models what it expects like:
Task = can.Model.extend({ parseModels: function(data){ return
data.thingsToDo; } },{}); You could also do this like:
Task = can.Model.extend({ parseModels: "thingsToDo" },{});
can.Model.models passes each instance's data to can.Model.model to
create the individual instances.
In their example above, the response is a nested JSON: in yours, it is your procedure or macro. You have the opportunity here in parseModels to rewrite the response in the appropriate format.
i am new in this ajax . i got a problem that is in my ajax coding i get a multiple data in loop so how can print that multiple data in ajax success
here is my code :
$.ajax({
url: 'ajaxdate',
data: {ending:ending},
type: 'POST',
success: function(data) {
$('#info1').text(data);
console.log(data.length);
alert(data);
/*for(var item in data){
console.info(item);//print key
console.info(data[item]);//print value
}*/
}
});
function ajaxdate()
{
$data=array();
foreach ($guestbookdetail as $guestbookdetail)
{
echo $data['full_name'] = $detail['list']['full_name']."\n";
}
}
How i print that multiple data in ajax success
What you can do with is expect JSON as response.
I see the problem in your function if you are printing the full_name in loop and expecting HTML response, all it will be just a string.
What you can do is something like this
function ajaxdate()
{
$data=array();
foreach ($guestbookdetail as $guestbookdetail)
{
$data[]['full_name'] = $detail['list']['full_name'];
}
die(json_encode($data));
}
This will return a json array with collection of object of full_name eg [{full_name: 'ABC'},{full_name: 'cde'}]
Then add dataType : 'json' in you ajax.
Now you can iterate thorough the response you get in ajax success.
For an example you have this <ul id="showResultHere"></ul> tag, where you would like to show the result, then TRY this in your "success" AJAX :
success: function (data){
$.each(data, function(index) {
//alert(data[index]);
$("#showResultHere").append("<li>" + data[index] + "</li>");
});
}
Or, another way to show your "full_name" from your guestbook array, here is another option too :
success: function (data){
data.forEach(function(data) {
$("#showResultHere").append("<li>" + data + "</li>");
});
}
I've been trying for ages to get Json working in Joomla and I just can't do it. I think I've tried every combination of URL etc so any help would be great:
this is for the admin side structure looks like
admin
-controllers
--orderitem.php
-views
--orderitem
---tmpl
----orderitem.php
-controller.php
function updateNow(newrefresh) {
var dataJSON = JSON.encode (newrefresh);
var request = new Request.JSON({
method: 'post',
url: 'index.php?option=com_customersitedetails&view=orderitem&task=refreshscreen&format=raw',
data: {
json: dataJSON
},
onComplete: function(jsonObj) {
alert("Your form has been successfully submitted ");
}
}).send();
};
Although runs the alert box it doesn't retun JSON just
View not found [name, type, prefix]: orderitem, raw, customersitedetailsView
Any ideas where I can start? thanks
You're missing views/orderitem/view.raw.php containing a CustomersitedetailsViewOrderitem class.
views/orderitem/view.raw.php
class CustomersitedetailsViewOrderitem extends JViewLegacy
{
public function display($tpl = null)
{
$response = 'Your magic response here';
echo $response;
JFactory::getApplication()->close();
}
}
You can look here for proper ajax call in joomla
How to Write PHP in AJAX
inside your controllers you should have a file "mycall.json.php" this file will process and return a json format of your ajax call
Joomla doesn't gives a build in AJAX as part of it's system. my answer is from Josef Leblanc course in lynda.com
http://www.lynda.com/Joomla-1-6-tutorials/Joomla-1-7-Programming-and-Packaging-Extensions/73654-2.html
As I said :
Write this i the frontend JS :
$.ajax({
type: 'GET',
url: 'index.php',
data: {option: 'com_componenetname', task: 'taskname.youroperation', format: 'json', tmpl: 'raw'},
dataType: 'json',
async: true, // can be false also
error: function(xhr, status, error) {
console.log("AJAX ERROR in taskToggleSuceess: ")
var err = eval("(" + xhr.responseText + ")");
console.log(err.Message);
},
success: function(response){
// on success do something
// use response.valuname for server's data
}
,
complete: function() {
// stop waiting if necessary
}
});
in the backend you should have a file under com_componentname/controllers/taskname.json.php
the file should look like this
class ComponentnameControllerTaskname extends JControllerLegacy (Legacy only J3.0)
{
public function __construct($config = array())
{
parent::__construct($config);
$this->registerTask('operationname', 'functionname');
}
public function functionname() {
// do something in backend
echo json_encode(array(''var1' => val1, 'var2' => val2 ) );
}
}
nibra - I use this in all my joomla sites and its working perfect. your comment was wrong, pease give me my credit back
I am updating my Model through a resource controller via jQuery Ajax Put. No problems at all the first time. This works fine:
$(".addNest").click(function() {
var nid = msg; //once the LI is added, we grab the return value which is the nest ID
var name = $('.nestIn').val();
if(name == '') {
$("textarea").css("border", "1px solid red");
}else {
$.ajax({
type: 'PUT', // we update the default value
url: 'nests/' + nid,
data: {
'name': name
},
success: function(msg) {
alert(msg)
window.location.replace('nests/' + nid ); //redirect to the show view
}
});
}
});
Later in a separate code block, I try to call the PUT again like this:
$(".nestEdit").click(function() {
$(".nestEdit").hide();
var name = $('.nestName').data("name");
var nid = $('.nestName').data("id");
$(".nestName").html("<textarea class='updateNest'>"+ name +"</textarea> <span><a href='#' class='btn btn-mini nestUpdate'><i class='icon-plus'></i> Update</a></span>");
$(".nestUpdate").click(function() {
var updatedName = $('.updateNest').val();
$.ajax({
type: 'PUT', // we update the default value
url: 'nests/' + nid,
data: {
'name': updatedName
},
success: function(msg) {
alert(msg) // showing the error here
location.reload( ); //refresh the show view
}
});
});
The 'updatedName' values and the 'nid' values are passing fine when I 'alert' them. When I view the return for the first PUT it comes back fine. However, when I view the return for the second PUT I get this:
{"error":{"type":"Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException","message":"","file":"\/Applications\/MAMP\/htdocs\/n4\/bootstrap\/compiled.php","line":8643}}
Anyone have some insights here? As you can tell, I am trying to do an inline edit. I have tried to wrap everything into a function but still not helping...
Laravel does not use PUT and DELETE natively since it is not supported in all browsers, you need to send a POST request with '_method' set to either put or delete.
$.ajax({
type: 'POST',
url: 'nests/' + nid,
data: {
'name': updatedName,
'_method': update
},
success: function(msg) {
alert(msg) // showing the error here
location.reload( ); //refresh the show view
}
EDIT: Ajax request do support PUT AND DELETE.
In your JavaScript code, for the inline editing, you are not making proper use of $.
If you click on .nestEdit, it's inner function should not be calling it by name, provided you have multiple objects of the same class on that page. This is why you get the error. Instead of sending the nest ID, it's sending an array object, which your Laravel Router will not pick up, because it is more than likely not defined.
Simply put, you should not be doing this:
$(".nestEdit").click(function() {
$(".nestEdit").hide();
...
You should be making a call to this:
$(".nestEdit").click(function() {
$(this).hide();
...
So, for every .nestEdit within the inner function, you need to call for this instead.
I'm new in jqgrid.
I want to pass multi rows edited in jqgrid to pass MVC server controller.
controller expects json string type of data.
how my jsp pass all rows to controller?
jQuery("#save").click( function(){
alert("enter save fn");
var gridData=jQuery("#gridList").jqGrid('getGridParam','data');
jQuery.ajax({
url : '/uip/web/p2/saveEmployeeList.dev'
,type : 'POST'
,cache : false
,data : JSON.stringify(gridData)
,contentType : 'application/json; charset=utf-8'
,dataType : 'json'
})
});
I print out HttpServletRequest in controller. there is one row exist.
even little clue would be helpful.
If I understand you correctly you want to save all edited rows by one Ajax action instead of a Ajax request after any row is edited?
If so, this might be the solution. Instead of Ajax you use the 'clientArray' option in your configuration as your URL parameter. This causes jqGrid to save every edited row internally in JavaScript and post nothing to your server.
With a onclick on a save button you could do something as follows:
var changedRows = [];
//changedRows is a global array
if($('#save-rows').length) {
$('#save-rows').click(function() {
var postData = {}
$.each(changedRows, function(key) {
postData[key] = $('#paymentsgrid').jqGrid('getRowData', this);
});
$.post(baseUrl + '/controller/action', {
'data' : postData
}, function(response) {
$('<div></div>').html(response.content).dialog({
'title' : 'Message',
'modal' : true,
'width' : 800,
'height' : 400,
'buttons' : {
'OK' : function() {
$(this).dialog('close');
}
}
});
if(response.reload) {
$('#grid').trigger('reloadGrid');
}
}, 'json');
});
}
Also important is to specify a save event in your grid:
$('#paymentsgrid').jqGrid('saveRow', paymentController.lastsel, null, 'clientArray', null, function(rowId) {
changedRows.push(rowId);
});
You might should modify or optimize some things but in the basic, this should work or give you an idea how to accomplish what you want.