How to call php script with ajax? - javascript

I'm trying to create multiple tables where I can move table rows between the tables and have ajax call a php script that updates the DB with the new values, ie the new parent to the row.
It's only html and javascript now and I'm wondering how the ajax part should look like to call a php script that updates the DB? And also if I should make some changes to the javascript/html part?
HTML:
<table class="tables_ui" id="t_draggable1"><h4>Table 1</h4>
<tbody class="t_sortable">
<tr>
<th>Title</th>
<th>Status</th>
<th>Creation date</th>
</tr>
#foreach($tasks as $task)
<tr class="row1" data-id="{{ $task->id }}">
<td>{{ $task->title }}</td>
<td>{{ ($task->status == 1)? "Completed" : "Not Completed" }}</td>
<td>{{ date('d-m-Y h:m:s',strtotime($task->created_at)) }}</td>
</tr>
#endforeach
</tbody>
</table>
<table class="tables_ui" id="t_draggable2"><h4>Table 2</h4>
<tbody class="t_sortable">
<tr>
<th>Title</th>
<th>Status</th>
<th>Creation date</th>
</tr>
<!-- More <td> rows here ... -->
</tbody>
</table>
<!-- More tables here ... -->
Javascript:
<script>
$(document).ready(function() {
var $tabs = $('#t_draggable2')
$("tbody.t_sortable").sortable({
connectWith: ".t_sortable",
items: "> tr:not(:first)",
appendTo: $tabs,
helper:"clone",
zIndex: 999990
}).disableSelection();
var $tab_items = $(".nav-tabs > li", $tabs).droppable({
accept: ".t_sortable tr",
hoverClass: "ui-state-hover",
drop: function( event, ui ) { return false; }
});
});
</script>

For an $.ajax call in js you should pay attention to a couple of things regarding what you'd like to pass to the PHP file and what you'd want as a return (response). A simple $.ajax call for posting data down below:
var Example1 = "123";
var Example2 = "456";
$.ajax({
type: "POST",
data: {
Example1: example1,
Example2: example2
},
url: "config/post.php",
success: function(){
setTimeout(function(){// wait for 5 secs(2)
location.reload(); // then reload the page.(3)
}, 100);
}
})
In the example above the variables (var), "Example1" and "Example2" will be inserted inside the request as the data.
Within your url: you'll specify the post url to your php file.
In the PHP file you're then able to obtain the data by using the second data { Attributes in a $_REQUEST see the example below:
$example1 = $_REQUEST['example1'];
$example2 = $_REQUEST['example2'];
echo $example1 . $example2;
To check if your data is obtained you could use the console.log() function above your $.ajax call to be sure.
var Example1 = "123";
var Example2 = "456";
// Check for the values
console.log(Example1 + Example2)
$.ajax({
type: "POST",
data: {
Example1: example1,
Example2: example2
},
url: "config/post.php",
success: function(){
setTimeout(function(){// wait for 5 secs(2)
location.reload(); // then reload the page.(3)
}, 100);
}
})
I hope this helps and if you have any questions please ask them in the comments section! (:

Related

Bootstrap multi row selection from table data and post to Flask backend

What I want to do is to let my users select multiple rows in a table and them hit a button to send this data back. My JS script file looks has the following:
<script>
$(document).ready(function () {
// Setup - add a text input to each footer cell
$('#example tfoot th').each(function () {
var title = $(this).text();
$(this).html('<input type="text" placeholder="Search ' + title + '" />');
});
$('#example tbody').on('click', 'tr', function () {
$(this).toggleClass('selected');
});
$('#button').click(function () {
alert(table.rows('.selected').data().length + ' row(s) selected');
});
// DataTable
var table = $('#example').DataTable({
initComplete: function () {
// Apply the search
this.api()
.columns()
.every(function () {
var that = this;
$('input', this.footer()).on('keyup change clear', function () {
if (that.search() !== this.value) {
that.search(this.value).draw();
}
});
});
},
});
});
</script>
My HTML code is as follows:
<form action="/get1" method="POST" name = 'input'>
<button id="button">Row count</button>
<table id="example" class="table table-striped">
<thead>
<tr>
<th scope="col">Index</th>
<th scope="col">Col2</th>
<th scope="col">Col3</th>
<th scope="col">Col4</th>
</tr>
</thead>
<tbody>
{% for item in rows %}
<tr>
<td>{{item[0]}}</td>
<td>{{ item[1] }}</td>
<td>{{ item[2] }}</td>
<td>{{ item[3] }}</td>
</tr>
{% endfor %}
</tbody>
<tfoot>
<tr>
<th>Index</th>
<th>Col2</th>
<th>Col3</th>
<th>Col4</th>
</tr>
</tfoot>
</table>
</form>
I need some help with JS and HTML to POST values (such as row index) to the backend that the backend can read.
Let's assume you have added the following DataTables Select resources to the head of your web page:
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/select/1.4.0/css/select.dataTables.css"/>
<script type="text/javascript" src="https://cdn.datatables.net/select/1.4.0/js/dataTables.select.js"></script>
Then you can enable the extension by adding the following option to your DataTable:
select: true
Now you can experiment with selecting and de-selecting rows. You can use the CTRL and SHIFT keys to select multiple rows.
In your button click event you can now use the selected() function I mentioned in my comment - for example:
$('#button').click(function () {
selected_ids = [];
table.rows().every(function () {
if ( this.selected() ) {
selected_ids.push( this.data()[0] );
}
});
console.log( selected_ids );
});
This will capture an array of IDs from the selected rows.
Note how it uses very similar logic to the columns().every() function you already have - except it uses rows().every() to iterate over the rows in the DataTable - not only the visible rows in the current page, but also all rows in other DataTables pages (if there multiple pages of table data).
The next step is a completely different question: How to submit the IDs in that array to your Flask back end.
That has been covered elsewhere in various questions - for example: jQuery Ajax POST example with PHP. Yes, this mentions PHP, but the jQuery piece is independent of the server technology.
That question has 25 answers, and there are various other questions along similar lines, which should help you. If you get stuck you can ask a new question with the specific problem you are facing.
But, basically, instead of my console.log( selected_ids );, you would use a jquery Ajax call: $.ajax( { ... } ); to send the data to Flask.

How do i refresh or redraw table rows

Below is the classical issue which I am facing during my app development.
I have an array of JSONObjects in my spring controller that I have to iterate in the jsp;
Also another status attribute called JSONArrayStatus is set that suggests if JSON array is empty or not.
Using jquery if JSONArray is empty I will show noDataImageDiv otherwise will show tableDIV (Binding the data from JSONArray using JSTL)
The problem I am facing is as below.
1. Edit a row in the table and click on Update. At this time I make an Ajax Call say, "UpdatedUser", which will return all the records along with the updated records. I could use refresh however thats not a recommended user experience and hence a no no.
To reflect the updated users in the table, I use jquery as below
clearing table rows table.clear().draw()
Loop the result set as follows.
redraw code
function reDrawExternalContactUsers(externalUsers) {
table.clear().draw();
var row = "";
$.each(externalUsers, function (i, field) {
row = '<tr><td></td><td></td><td class="edit">edit</td></tr>';
$("#tableDIV").append(row);
});
}
afetr this redraw or refresh process
This function is NOT working
$(".edit").click(function(){
});
This function is working
$("#tableDIV .edit").click(function(){
});
Suggest a better way of refreshing table rows, if any.
<div id="tableDIV">
<table id="tableID">
<thead>
<tr>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
if data exist
loop{
<tr>
<td></td>
<td></td>
<td class="edit">edit</td>
</tr>
} // loops ends
if close
</tbody>
</table>
</div>
<div id="noDataImageDiv"> No data image</div>
html code :
<div id="tableDIV">
<table id="tableID">
<thead>
<tr>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
if data exist
loop{
<tr>
<td class="user-name"></td>
<td></td>
<td class="edit" data-user-id="">edit</td> //set user_id in attr data-user-id
</tr>
} // loops ends
if close
</tbody>
</table>
</div>
<div id="noDataImageDiv"> No data image</div>
jquery code :
you should use click event on document
$(document).on('click', '.edit', function () {
var btn = $(this);
var user_id = btn.attr("data-user-id"); //user_id of user will update
// extra user data
$.ajax({
method: "POST",
url: url,
data: {
'id': id,
// extra data to send
},
success: function (data) {
if (data.status) // successfully user updated
{
var user = data.user;
/* you can set user data like this */
btn.closest('tr').find('.user-name').html(user.name);
}
}
});
});

Add Link Column to DataTable After Ajax Call MVC

On my view page I have a table (from a partial view) and a form. I am using ajax to submit the form to my webapi controller.
On success I would like to add what was entered in the textbox to the first column, and links to Edit and Delete in the second column of a new row.
As of right now I am only working on the Edit link.
Here is my partial view table:
<table id="Table" class="table table-bordered">
<thead>
<tr>
<th class="col-md-6">
#Html.DisplayNameFor(model => model.Name)
</th>
<th></th>
</tr>
</thead>
#foreach (var item in Model)
{
<tr>
<td class="col-md-6">
#Html.DisplayFor(modelItem => item.Admin)
</td>
<td class="col-md-6">
#Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.ID })
</td>
</tr>
}
</table>
Here is my form jquery.ajax:
var table = $("#Table").DataTable({
"aoColumnDefs": [
{ "bSortable": false, "aTargets": [1] },
{ "bSearchable": false, "aTargets": [1] }
]
});
$("form").submit(function(e) {
e.preventDefault();
$.ajax({
url: infoGetUrl,
method: "post",
data: $("form").serialize()
}).success(function (data) {
var editLink = document.createElement('a');
editLink.href = "/controllerName/Edit/" + data.id;
editLink.text = "Edit";
table.row.add([
$("#Textbox").val(),
editLink
]).draw();
}).error(function(jqXHR, textStatus, errorThrown) {
console.log("error");
});
});
The problem is that when this renders I get this:
It is not clickable and renders like this:
<tr class="even" role="row">
<td class="sorting_1">John.Doe</td>
<td>http://localhost:61888/controllerName/Edit/15</td>
</tr>
As you can see, it is not rendered in an a tag, and I don't need the http://localhost:61888 part of the link.
How can I resolve this?
try creating link as:
var link = <a href='/controllerName/Edit/' + data.id>EDIT</a>
With pur JS:
var link = document.createElement('a');
link.textContent = 'Edit';
link.href = "/controllerName/Edit/" + data.id;
you just need to place this inside your td.
If you want to remove 'http://localhost:61888' you can just use replace to change your localhost by un empty string. Or split your string and just keep the second part

How to populate a Select2 element on open event through an AJAX call?

I have the following code in a Twig template:
<table class="table">
<thead>
<tr>
<th>License ID</th>
<th>Quote ID</th>
</tr>
</thead>
<tbody>
{% for key,value in data %}
<tr>
<td>{{ value.id }}</td>
<td>
<select class="form-control select2" data-placeholder="--Select One--"></select>
</td>
</tr>
{% endfor %}
</tbody>
</table>
The code above translate into one or more SELECT elements depending on the data coming from the backend.
Each of those will need to run a really BIG and slow query to get the data that should be there.
What I am thinking is to render them just empty (no values at all, just the initial placeholder) and when I open each of them then populate it's data so I run just one query at a time (thru AJAX).
I should also - although don't know if it's a good idea (you tell me) - on close destroy all the SELECT values.
Note: I should say the Select2 elements are contained in a jQuery UI dialog but this shouldn't be a problem.
This is how my code looks like:
addtoquoteDialog.dialog({
autoOpen: false,
modal: true,
width: 800,
height: 600,
resizable: false,
buttons: {
"Cancel": function () {
$(this).dialog('close');
},
"Add to Quote": function () {
$(this).dialog('close');
}
},
open: function (event, ui) {
var $select2selector = $('.select2');
$select2selector.select2();
$select2selector.on('select2:open', function (e) {
var id = $(this).data('id');
$select2selector.select2({
ajax: {
url: Routing.generate('quote_select_data', {id: id}),
dataType: 'json'
}
});
}).on('select2:closing', function (e) {
// Destroy the select values
});
}
});
But I am raising the Cannot read property 'query' of null famous error message and the AJAX call is not being triggered.
I've seen a lot of issues like this (this one for example) but none seems to be like mine so I am completely lost.
Can any tell me what I am missing in my code?
I am seeing this example but this happen when the SELECT get's initialized, I am right?
What is the right way to handle this?

Jquery Datatables - Make whole row a link

This maybe simple, but cant seem to figure it out. Using jquery datatables how can I make each row clickable to just link to a normal page? So if someone moused over any of the row the whole row will hightlight and be clickable and link to whatever url I would want it to link to when clicked.
I've use the fnDrawCallback parameter of the jQuery Datatables plugin to make it work. Here is my solution :
fnDrawCallback: function () {
$('#datatable tbody tr').click(function () {
// get position of the selected row
var position = table.fnGetPosition(this)
// value of the first column (can be hidden)
var id = table.fnGetData(position)[0]
// redirect
document.location.href = '?q=node/6?id=' + id
})
}
Hope this will help.
This did it for me using the row callback.
fnRowCallback: function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
responsiveHelper.createExpandIcon(nRow);
$(nRow).click(function() {
document.location.href = 'www.google.com';
});
},
$('#myTable').on( 'click', 'tbody tr', function () {
window.location.href = $(this).data('href');
});
where #myTable is the ID of the table, and you need put the href in the tr, like that:
<tr data-href="page.php?id=1">
<th>Student ID</th>
<th>Fullname</th>
<th>Email</th>
<th>Phone</th>
<th>Active</th>
</tr>
It's simple enough to do this with a vanilla <table>, but I don't see why this wouldn't work with a jQuery DataTables one either.
$('#myTableId').on('click', 'tbody > tr > td', function ()
{
// 'this' refers to the current <td>, if you need information out of it
window.open('http://example.com');
});
You'll probably want some hover event handling there as well, to give users visual feedback before they click a row.
You can also use the DataTables plugins api which allows you to create custom renderers.
Very cool: JS addon here
And using the fnDrawCallback
fnDrawCallback: function() {
this.rowlink();
},
You can do that to make row clickable :
<script type="text/javascript">
var oTable;
$(document).ready(function() {
oTable = $('#myTable').dataTable({
"ajax" : "getTable.json",
"fnInitComplete": function ( oSettings ) {
//On click in row, redirect to page Product of ID
$(oTable.fnGetNodes()).click( function () {
var iPos = oTable.fnGetPosition( this );
var aData = oSettings.aoData[ iPos ]._aData;
//redirect
document.location.href = "product?id=" + aData.id;
} );
},
"columns" : [ {
"data" : "id"
}, {
"data" : "date"
}, {
"data" : "status"
}]
});
});
</script>
<table id="myTable" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>#</th>
<th>Date</th>
<th>Status</th>
</tr>
</thead>
<tbody></tbody>
</table>
I think it will be like that
$('#invoice-table').dataTable({
"fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
var slug = $(nRow).data("slug");
$(nRow).attr("href", "/invoices/" + slug + "/");
$(nRow).css( 'cursor', 'pointer' );
$(nRow).click(function(){
window.location = $(this).attr('href');
return false;
});
}
});
And the table row like that
<tr class="invoice_row" data-slug="{{ invoice.slug }}">
<td>{{ invoice.ref }}</td>
<td>{{ invoice.campaign.name }}</td>
<td>{{ invoice.due_date|date:'d-m-Y' }}</td>
<td>{{ invoice.cost }}</td>
<td>
<span class="label label-danger">Suspended</span>
</td>
</tr>
This worked fine with me
**I have used a simple solution for this. Add onclick on tr and you are done. Tested with jquery datatable **
<tr onclick="link(<?php echo $id; ?>)">
function link(id){
location.href = '<?php echo $url ?>'+'/'+id;
}
Recently I had to deal with clicking a row in datatables.
$(document).ready(function() {
$("#datatable tbody tr").live( 'click',function() {
window.open('http://www.example.com');
} );
} );

Categories