I have multiple rows generated into my page using PHP and MySQL, and I have a simple form that helps me to add more rows to database. What I want exactly is, that I have to add a row before a specific row with a specific id:
foreach($resInst as $installment){
$sum = $sum + $installment['payment'];
?>
<tr id="<?php echo $installment['infoid'] ?>"><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td>
<td><?php echo $counter--; ?></td>
<td><?php echo $installment['date_now'] ?></td>
<td><?php echo $installment['payment'] ?> $</td></tr>
</tr>
<?php } ?>
Here is the AJAX script:
$(document).on('click', '#add_payment', function()
{
var date_of_pay = $("#date_pay_now").val();
var pay_now = $("#pay_now").val();
//var id_pay = $(this).closest('tr').attr('id');
var id_pay = $("#select_to_pay").val();
var pid2 = '<?php echo $patient_id ?>';
console.log(pid2);
if(date_of_pay == "" || pay_now == "" || id_pay)
{
$("#date_pay_now").css('border-color', 'red');
$("#pay_now").css('border-color', 'red');
$("#select_to_pay").css('border-color', 'red');
}
if(date_of_pay != "" && pay_now != "" && id_pay != 0)
{
$.ajax
({
url: 'add_payment.php',
type: 'post',
data: {pid: pid2, date_o_pay: date_of_pay, pay_n: pay_now, id_of_proj: id_pay},
dataType: 'text',
success:function(result)
{
alert("Payment added!");
//Append here
},
error:function(result)
{
alert("Payment didn't added! Please Try again");
}
});
}
});
I mean that when I add information into database that have the same infoid I need to append this new line before the <tr> that have had the same $installment['infoid'].
The problem for me is how to put a condition inside jQuery that said:
if row of the id == id_pay ==> append before this line exactly
Like this:
success:function(result)
{
alert("Payment added!");
if($("tr").prop('id') == id_pay)
{
$(this).before("<tr><td>"+id_pay+"</td></tr>");
}
},
Something like this?
$('#'+id_pay).prev().after( put_your_inner_html_here )
Although, that might be interesting if your row was the first row ... but should still be ok since prev() would be the tbody
Related
I'm new here, i'm working with ajax and notify.js on my website.
Where there are a slight problem, which is i can't call my function using href with ajax and the notify.js won't pop up and delete the file
Let me show you my code
Views:
<tbody>
<?php foreach ($rows as $row) { ?>
<tr>
<td><?php echo $row ->description ?></td>
<td><?php echo $row->updated_at ?></td>
<td>Edit</td>
<td><a id="aDeleteOrderType" onclick="type_delete()" href="#.<?php echo $row->id ?>">Delete</a></td>
</tr>
<?php } ?>
Admin Footer
<script>
$("#aDeleteOrderType").click(function(e){
e.preventDefault();
$.ajax({
url: '<?php echo base_url().'admin/type_delete' ?>',
type: 'post',
data: {
},
success: function(msg)
{
if (msg == 'valid')
{
$.notify('Data Has Been Deleted', 'error')
}
}
});
});
Controller
public function type_delete($id)
{
$is_logged_in1 = $this->session->userdata('is_logged_in');
$type = $this->session->userdata('type');
if(!isset($is_logged_in1) || $is_logged_in1 != true)
{
$data['error'] = '';
$this->load->view('login-1', $data);
}
else
{
$this->load->model('listtipeorder_model');
$this->listtipeorder_model->delete_list_type($id);
echo 'valid';
}
}
Help me guys please:(
P.S sorry for my bad english though.
HTML:
Notice data-id, and attribute we will get soon.
<td><a id="aDeleteOrderType" href="#" data-id="<?php echo $row->id ?>">Delete</a></td>
JS:
Since you aren't using get or post to get the $id var in your php function and instead are passing it as a url param you have to do the same via jquery.
<script>
$(document).ready(function () {
$("#aDeleteOrderType").click(function (e) {
var id = $(this).attr('data-id');
e.preventDefault();
$.ajax({
url: '<?php echo base_url() . '/admin/type_delete/'; ?>' + id,
type: 'POST',
success: function (msg) {
if (msg == 'valid') {
// success would be better suited than 'error'
// might confuse some
$.notify('Item deleted', 'success');
} else {
$.notify('Error occurred', 'error');
}
}
});
});
});
</script>
PHP:
There isn't anything wrong with your PHP, but it can be improved.
function type_delete($id = null) {
$is_logged_in1 = $this->session->userdata('is_logged_in');
//$type = $this->session->userdata('type');
// isset not required with userdata as will return null if no data
if ($is_logged_in1 != true || is_null($id)) {
echo 'error';
// don't load a view
//$data['error'] = '';
//$this->load->view('login-1', $data);
} else {
$this->load->model('listtipeorder_model');
$this->listtipeorder_model->delete_list_type($id);
echo 'valid';
}
exit;
}
This question already has answers here:
How to prevent page refresh when <a> tag clicked?
(4 answers)
Closed 4 years ago.
When I clicked on book link he reloads the page and sorts the column.
Do I want to stop the reload using ajax,,, How?
this is my functions to this process.
this getBook function
public function getBooks($start = 0, $limit = 2, $order = "ASC")
{
$sql_start = $start * $limit;
$sql_limit = $limit;
$sql_order_by = $order;
$query = "SELECT Library.nameOfBook, userBook.book_id, userBook.user_id FROM loginUser JOIN userBook JOIN Library ON userBook.user_id = loginUser.id AND userBook.book_id = Library.id WHERE loginUser.username=:username ORDER BY Library.nameOfBook $sql_order_by LIMIT $sql_start, $sql_limit";
$statment = $this->db->prepare($query);
$statment->execute([
':username' => $this->username
]);
$result = $statment->fetchAll();
echo "<table id='myTable' border='1'>
<tr>
<th><a id='sorter' href='#'>Books</a></th>
<th>Action</th>
</tr>";
foreach($result as $row){
echo "<tr>";
echo "<td>" . $row['nameOfBook'] . "</td>";
echo "<td>" ."<input type='submit' id='delete".$row['book_id']."-".$row['user_id']."' onclick='deleteBook(this)' name='delete' value='Delete'>" . "</td>";
echo "</tr>";
}
echo "</table>";
echo "";
return count($result);
}
this jquery function
<script>
$(document).ready(function() {
$( "#sorter" ).click(function() {
var order_by_value = $('input[name="order_by"]').val();
if(order_by_value == "ASC"){
$('input[name="order_by"]').val("DESC");
}
else {
$('input[name="order_by"]').val("ASC");
}
$('input[name="current"]').trigger('click');
});
});
</script>
<script>
$(document).ready(function() {
$( "#sorter" ).click(function() {
var order_by_value = $('input[name="order_by"]').val();
$.ajax({
type: 'GET',
url: 'the url link ',
data: {
'order_by_value': order_by_value
},
success: function (res) {
if(res == "ASC"){
$('input[name="order_by"]').val("ASC");
}
else {
$('input[name="order_by"]').val("DSC");
}
$('input[name="current"]').trigger('click');
});
}
});
</script>
Firstly, never reload your page before you are sure that the ajax has completed its process.
Secondly, if you want to sort using JS run that code after you finish submitting the form or data in your case.
Here is how your ajax code with page reload on compeletion will look like
$.ajax({
type: 'GET',
url: 'your_page_link.php',//this will be url of your backend page
data: {
'name':name
'email':email
},// if you are using form then just use .serialize() to submit the form instead of preparing data like this use $("#form_id").serialize()
success: function (msg) {
resp = msg;
}
}).done(function(){
if(resp == your_expected_response){
window.location.href = "http://stackoverflow.com";
}else{
//your error handler
}
});
Hope this will be helpful, please feel free to ask if any clarification is required..
Cheers!!
So im trying to run a PHP script that sets a deleted field in the database to poplulate if you drag a certain text element to the droppable area.
At the moment i have this droppable area:
<div class="dropbin" id="dropbin" >
<span class="fa fa-trash-o noSelect hover-cursor" style="font-size: 20pt; line-height: 225px;"> </span>
</div>
and this draggable text:
<div id='dragme' data-toggle='modal' data-target='#editNoteNameModal' class='display-inline'>" . $data['NoteName'] . "</div>
The area im having an issue with is this:
$("#dropbin").droppable
({
accept: '#dragme',
hoverClass: "drag-enter",
drop: function(event)
{
var noteid = <?php if(isset($_POST['noteid'])){ echo $_POST['noteid'];} ?>;
var deletedby = <? if(isset($_SESSION['username'])){ echo $_SESSION['username'];} ?>
var data = {noteid1: noteid, deletedby1: deletedby};
if (confirm('Delete the note?')==true)
{
$('#dragme').hide();
debugger
$.ajax({
type: 'POST',
url: 'deleteNote.php',
datatype: 'json',
data: data,
success: function(result)
{
alert("Success");
}
});
window.location = "http://discovertheplanet.net/general_notes.php";
}
else
{
window.location = "http://discovertheplanet.net/general_notes.php";
}
}
});
EDIT: The line i get the error on is:
var noteid = <?php if(isset($_POST['noteid'])){ echo $_POST['noteid'];} ?>;
Im currently getting an "Unexpected token ;" and its stopping the droppable from working.
Just a side note, if i run it without the variables it hits everything apart from:
url: 'deleteNote.php',
Also inside deleteNote.php is this incase it helps:
<?php
include "connectionDetails.php";
?>
<?php
if (isset($_POST['noteid1'], $_POST['deletedby1']))
{
$noteid2 = $_POST['noteid1'];
$deletedby2 = $_POST['deletedby1'];
// echo "Hello...". $noteid;
$stmt = "UPDATE Notes SET Deleted = GETDATE() WHERE NoteID = (?)";
$params = array($noteid2);
$stmt = sqlsrv_query($conn, $stmt, $params);
if ($stmt === false)
{
die( print_r(sqlsrv_errors(), true));
}
}
else
{
echo "No Data";
}
?>
(I deliberatley don't have deletedby in the database just yet, ignore that)
Could anyone possibly help me to get this to work?
Try to add quotes in these lines and add php after <? in second line:
var noteid = "<?php if(isset($_POST['noteid'])){ echo $_POST['noteid'];} ?>";
var deletedby = "<?php if(isset($_SESSION['username'])){ echo $_SESSION['username'];} ?>";
OR
var noteid = "<?=isset($_POST['noteid']) ? $_POST['noteid'] : "" ?>";
var deletedby = "<?=isset($_SESSION['username']) ? $_SESSION['username'] : "" ?>";
I have a table which consists of data from MYSQL, and whenever I make changes in an element in table, my database will be updated by ajax.
This is my javascript code to send the data in editable row.
function saveToDatabase(editableObj,column,id) {
$(editableObj).css("background","#FFF url(images/loaderIcon.gif) no-repeat right");
$("#tabs-1").load(location.href + " #tabs-1");
$.ajax({
url: "saveedit.php",
type: "POST",
data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
success: function(data){
$(editableObj).css("background","#FDFDFD");
}
});
}
After the function above, saveedit.php will deal with updating the database and it's functional.
Then, this is my table in html and these table elements are editable.
<?php
$result = FUNCTION_TO_RETRIEVE_DATA_FROM_DB;
foreach($result as $k=>$v){
?>
<tr>
<td><?php echo $k+1; ?></td>
<td contenteditable="true" onBlur="saveToDatabase(this, 'memberID', '<?php echo $result[$k]["memberID"]; ?>')"><?php echo $result[$k]["memberID"]; ?></td>
<td contenteditable="true" onBlur="saveToDatabase(this, 'surname', '<?php echo $result[$k]["memberID"]; ?>')"><?php echo $result[$k]["surname"]; ?></td>
<td contenteditable="true" onBlur="saveToDatabase(this, 'forename', '<?php echo $result[$k]["memberID"]; ?>')"><?php echo $result[$k]["forename"]; ?></td>
<td contenteditable="true" onBlur="saveToDatabase(this, 'address', '<?php echo $result[$k]["memberID"]; ?>')"><?php echo $result[$k]["address"]; ?></td>
<td contenteditable="true" onBlur="saveToDatabase(this, 'gradeID', '<?php echo $result[$k]["memberID"]; ?>')"><?php echo $result[$k]["gradeID"]; ?></td>
</tr>
<?php
}
?>
This code is working, but the question I would like to ask is, how can I validate the data entered by the user into this element? For example, what if I would like to check the initial column, memberID, cannot be longer than 6 characters, or if it is required or not. What I am trying to do is to validate entered data before sending it using AJAX but now but I have no idea how validation can be done in the table element.
Before calling ajax validate your column by putting condition before it.
` function saveToDatabase(editableObj,column,id) {
$(editableObj).css("background","#FFF url(images/loaderIcon.gif) no-repeat right");
$("#tabs-1").load(location.href + " #tabs-1");
if(column == "memberID"){
if(editableObj.innerHTML.length > 6 ) {
alert("cannot be longer than 6 characters");
return false;
}else{
$.ajax({
url: "saveedit.php",
type: "POST",
data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
success: function(data){
$(editableObj).css("background","#FDFDFD");
}
});
}
}
}`
Before calling the saveToDatabase() function put the desired validation on the entered value like:
var newVal = editableObj.innerHTML;
// Your validation on newVal, if validation successful call the saveToDatabase() function
// Otherwise show an error message and do nothing
Check the passing parameter and only process ajax when your condition is satisfied.
function saveToDatabase(editableObj,column,id) {
//If(editableObj.length > 6) // Case of string Check your other condition.
if(editableObj.toString().length > 6) // in case it is not string.
{
alert(Condition fail);
}
else
{
// Your ajax call -------
}
}
Or :
Check your passing data before calling saveToDatabase function.
I have this small project to get multiple Alexa rank of each website.
I am trying to sort a table using jquery.tablesorter.js however it is not working, because I am sending ajax request for every URL then displaying it.
this is my jquery and ajax request :
<script>
$(document).ready(function(){
$('#btnurls').click(function(){
$('#loadingmessage').show();
var arrayOfLines = $('#websiteurls').val().split('\n');
$.each(arrayOfLines, function(index, item) {
$.ajax({
type: "POST",
url: "ajax_pages/ajax_alexa.php",
data: "textposted=" + item,
cache: false,
success: function(html){
$('#loadingmessage').hide();
for (var i = 1; i <= 1; i++) {
$("#content table").delay(1000)
.queue(function (nxt) {
$(this).append(html);
nxt();
});
}
$("#websiteurls").val("");
}
});
});
});
$("#textarea_reset").click(function(){
$("#websiteurls").val("");
});
});
</script>
alexa_rank.php
<?php $line = $_POST['textposted'];?>
<tr>
<td><?php if (!filter_var($line, FILTER_VALIDATE_URL) === false) {echo $line;} else {echo "$line";}?></td>
<td>
<?php
$xml = simplexml_load_file('http://data.alexa.com/data?cli=10&dat=snbamz&url='.$line);
$rank = isset($xml->SD[1]->POPULARITY)?$xml->SD[1]->POPULARITY->attributes()->TEXT:0;
$country_rank=isset($xml->SD[1]->COUNTRY)?$xml->SD[1]->COUNTRY->attributes()->RANK:0;
$country_name=isset($xml->SD[1]->COUNTRY)?$xml->SD[1]->COUNTRY->attributes()->NAME:0;
echo $rank;
?>
</td>
<td><?php echo $country_rank; ?></td>
<td><?php echo $country_name; ?></td>
</tr>
live test https://www.bulkalexarankchecker.com/
Based on the example AJAX provided with jQuery tablesorter you need to trigger the update event on the table when the data is updated. It would probably be something like:
$.each(arrayOfLines, function (index, item) {
$.ajax({
type: "POST",
url: "ajax_pages/ajax_alexa.php",
data: "textposted=" + item,
cache: false,
success: function (html) {
$('#loadingmessage').hide();
for (var i = 1; i <= 1; i++) {
$("#content table").delay(1000)
.queue(function (nxt) {
$(this).append(html);
$(this).trigger("update");
nxt();
});
}
$("#websiteurls").val("");
}
});
});
Ideally you'd wait until all the data is fetched but you've made no provision for such an event with the current code so this would probably work equally well.