Jump to content

Ajax Post Data to Jquery Datatable and Return Another Value


Recommended Posts

Hi All,

I use a jQuery datatable to display information from a search. The results are posted back via Ajax to a default table placeholder like so:

                <table id="example" class="table table-striped table-responsive hide-me" style="width:100%">
                    <thead>
                        <tr>
				<th>Sponsor</th>	
				<th>Nationality</th>  
				<th>Sector</th>
				<th>Team Sponsored</th>
				<th>Sport</th>
                        </tr>
                    </thead>
                    <tfoot>
                        <tr>
				<th>Sponsor</th>	
				<th>Nationality</th>  
				<th>Sector</th>
				<th>Team Sponsored</th>
				<th>Sport</th>
                        </tr>
                    </tfoot>
                </table>

This is handled by the following:

	$(document).on('click', '.taxonomy-sponsor-link', function(){							 
	
		var action = 'get_sponsors_by_taxonomy';	
		var id = $(this).data('id');
		var tax = $(this).data('tax');
		
		//alert('action: '+action+' tax: '+tax+' id: '+id);
	
		//assing the datatable call to a variable
		let example = $('#example').DataTable({
			"destroy": true,
			
			"responsive":{//this is usefull if you want to use a full responsive datatable just add the responsive css from dataTables.net
				"details": {
					renderer: function ( api, rowIdx, columns ) {
						var data = $.map( columns, function ( col, i ) {
							return col.hidden ?
							'<tr data-dt-row="'+col.rowIndex+'" data-dt-column="'+col.columnIndex+'">'+
							'<td>'+col.title+':'+'</td> '+
							'<td>'+col.data+'</td>'+
							'</tr>' :
							'';
						} ).join('');
	
						return data ?$('<table/>').append( data ) :false;
					}
				}
			},
			
			"autoWidth": false,//fix Bootstrap 4 glitch
			"ajax": {
				method		:"POST",			   
				url			: '<?php echo admin_url('admin-ajax.php');?>',
				data		: {action:action,tax:tax,id:id,},
			},
			"columns": [
				{"data": "sponsor"},
				{"data": "nationality"},
				{"data": "sector"},
				{"data": "team_sponsored"},
				{"data": "sport"}
			],
			"columnDefs": [
				{
					//"className": "dt-center", "targets": "_all"
					"className": "", "targets": "_all"
				}
			]
		});
		example.on( 'xhr', function ( e, settings, json ) {// check is the response is not null and show the table
			if (json != null) {
				$('#example').removeClass("hide-me","");
			}
		} );
	
	});	

And my PHP gathers the data and passes it back via:

echo json_encode($json);

What I'd like to do, is also pass 1 other value from the results but not in the table. So wanted to use something like:

<div id="search-results-header"></div>

After an bit of searching, I can see you can alter the json_encode to be an array, so something like:

echo json_encode(array(
        'example' => $json,
        'search-results-header' => $search
));

However, I then can't work out whether:

a) This is correct

b) How I adjust the above call to output the table results AND the additional parameter.

I wonder if someone would be kind enough to please assist?

Thanks

44 minutes ago, jarvis said:

What I'd like to do, is also pass 1 other value from the results but not in the table. So wanted to use something like:


<div id="search-results-header"></div>

 

What? Do you want to add that markup to the page? Or are you trying to return a value from PHP that should be inserted into that DIV which is already written on the page?

So what you need is to be able to customize how the DataTable does the AJAX request, right? You can perform the actual request yourself, then give the DataTable just the "example" data while you borrow the "search-results-header" data for something else.

When in doubt, check the documentation.

Thanks @requinix

When I previously tried ajaxifying the content, the search on the table didn't work. The code above worked and still enables the search functionality

I just can't quite see how to do/integrate the other part

The thing you pass as the "ajax" value needs to be a function. It take a few arguments, as seen in the documentation, and when it's done it uses the callback function it received.

What code do you have trying to do that? What do you expect to happen when you view the table and what actually happens?

Hi @requinix

I tried to adjust 

		example.on( 'xhr', function ( e, settings, json ) {// check is the response is not null and show the table
			if (json != null) {
				$('#example').removeClass("hide-me","");
				jQuery(".search-results-header").html(data);
			}
		} );

I also tried adding

 d.search-results-header = $('#search-results-header').val();

Into the render part of the code

I'll be honest, I'm struggling to make sense of it, hence turning to this forum for assistance. I'd previously read the link you sent and struggled to make sense of it. I also Google'd for examples, hence basing my code on someone else's example and adapting to my requirements. Less than ideal I know but got my code working. A lot of examples I found were using GET whereas I needed POST.

Thanks

Not the xhr event. I said "ajax". As in what I linked to in the documentation. As in

			"ajax": {
				method		:"POST",			   
				url			: '<?php echo admin_url('admin-ajax.php');?>',
				data		: {action:action,tax:tax,id:id,},
			},

that.

I see what you're saying but I'm still at a loss, I can see the docs but I cannot fathom how to do what I need

"ajax": {
	"method" :"POST",			   
	"url" : '<?php echo admin_url('admin-ajax.php');?>',
	"data": function ( d ) {
      return $.extend( {action:action,tax:tax,id:id}, d, {
        "searchResultsHeader": $('.search-results-header').val()
      } );
	}
}

??

Seems like you're kinda just guessing.

Quote

As a function, making the Ajax call is left up to yourself allowing complete control of the Ajax request. Indeed, if desired, a method other than Ajax could be used to obtain the required data, such as Web storage or a Firebase database.

When the data has been obtained from the data source, the second parameter (callback here) should be called with a single parameter passed in - the data to use to draw the table.

If you make the "ajax" a function instead of an object, then you can do whatever you want. Like make your own AJAX request. When you do that, you'll get back the information that the DataTable wants as well as the header string thing. Put the header string thing into your header element thing, then use the "callback" to hand the table data off for processing.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.