Updating "tr" data in laravel - laravel

I'm facing difficulty in doing this task :
- I have a table that have an add delete , update buttons for every single row I've done the add and delete thing by adding data-attribute for each button according to the row's data Id. It works perfectly for deleting and inserting elements. Yet i can't find a way to update every single row so i need help !
Note: I'm updating my elements using Ajax.
Any strategy ? i can post a screenshot for my code/view cause it is a bit too long .
More explanation : when you click on the edit button $(this) and delete button hide , and check button appears . inputs are no longer hidden for this row so the user updates the data of this row then he checks it.
The data must update inside the database .
I'm stuck nowhere because every row has its own id and its own values and only one query must be run for every row ( which is the same query for all the rows ) . It's more likely having one form for the whole table that updates only the row that must be updated .
After you click on edit button
$(document).on('click', '.btn-edit-interview', function() {
var id = $(this).attr('data-interview-id');
var selector = ('' + '.tr' + id + '');
var selectordelt = ('' + '.' + id + '');
var selectorsave = ('' + '#save-'+id + '');
$(this).hide();
$(selectordelt).hide();
$(selectorsave).show();
$(selector).prop('disabled', false);
$(selector).addClass("form-control");
$(selector).css('border: 1px solid rgb(204, 204, 204);margin-top: 16px;');
});
I just need help in finding a way do make the update query for every single row .

//HTML
<tr data-unique="{!! $yourVariable->id !!}">
<td><input value="{!! $yourVariable->value !!}"></td>
<td><button data-update="{!! $yourVariable->id !!}">Update</button></td>
</tr>
//AJAX
$('button[data-update]').click(function() {
var itemID = $(this).attr('data-update');
//Will contain value of input in that tr only
var input = $('tr[data-unique="+itemID+"] input').val();
$.ajax({
url: '/update',
type: 'POST',
dataType: 'json',
data: {item: itemID, anotherValue: input},
success:function(data){
if(data['status'] == "success"){
alert("Updated");
}
}
});
return false;
});
//Controller
public function update(Request $req){
YourModel::where('id', $req->input('item'))->update(['column' => 'value']);
return response()->json(['status' => 'success']);
}
//Route
Route::post('/update', 'YourController#update');
Hope that help

Related

svelte-sapper each block list item selection for deletion - get the id

I have a list of orders stored in a db. I use each block to display all orders with a delete button. When I click the delete button, I need to get the id of the CLICKED list item so I can look that order in the db and delete it. I don't know how to get the id of the CLICKED list item and pass it to handledelete function. How do I do that in svelte/sapper?
My code for the page that display all orders :
<script>
let orderz =[]
function handlesave() {
//save all the order data to db...
} // handlesave
function handleDelete () {
fetch('order', {
method: 'POST',
credentials : 'include',
headers: {
'Accept': 'application/json',
'Content-type' : 'application/json'
},
body: JSON.stringify({
// order id to send it to server to delete it from the db
})
}).then(response => response.json())
.then(responseJson => {
console.log("xxxxxxx:", responseJson.orderdetails )
})
.catch(error => console.log(error));
}
</script>
<form on:submit|preventDefault={handlesave}>
<button type="submit">Place Order</button>
</form>
<ul>
{#each orderz as order}
<li >
<p >{order.vendorid} - {order.vendorname} - {order.item}
- {order.price}</p>
<button on:click|once={handleDelete}>Delete</button>
</li>
{/each}
</ul>
You can tell the delete function which id was clicked by simply passing it in as an argument to the function:
function handleDelete(id) {
// Delete logic here
}
<button on:click="{() => handleDelete(id)}">Delete</button>
!! Note that you should not call handleDelete directly in your markup as this will execute the function immediately upon rendering (and thus effectively delete your entry as soon as it appears on screen)
Just add variable to your delete-function:
function handleDelete (id){
... use id to delete item in database...
}
Then add order id also to your on:click:
EDIT: on:click function call fixed as mentioned in other answer
<button on:click|once={()=>handleDelete(order.id)}>Delete</button>
There are other ways to do this, but this is the simplest one.
You don’t need once modifier, if you delete the item.
You will probably need a key with each-loop in order to keep list correctly updated after delete (key = thing.id in following example)
{#each things as thing (thing.id)}
<Thing current={thing.color}/>
{/each}
https://svelte.dev/tutorial/keyed-each-blocks

Like System with AJAX and Laravel

I'm trying to get it so people can like a post on a button click which will upload a row to the likes table and then if they press the button again it will delete the record and unlike the post. The problem i am having is that i have rehashed a tutorial which included a boolean for a like and dislike, i do not have the boolean and have tried to reconfigure the code to accommodate that. The problem i'm having is that after i've sorted out the unauthorized errors the button now appears to be dead and doesn't do anything. I presume this mean that their is an issue with the laravel code for this. Can anyone see why the button isnt responding and point me in the direction of how i like(post) to database, check for a like and delete if the button is pressed and the row exists?
Here is what i have so far:
Table:
likes: id, post_id, user_id, timestamps()
HTML:
<a class="btn btn-not-liked like">Liked?</a>
AJAX JS:
var postId = 0;
var token = '{{ Session::token() }}';
var urlLiKes = '{{ route('likes') }}';
$('.like').on('click', function(event){
event.preventDefault();
postId = event.target.parentNode.parentNode.dataset['postid'];
var isVisit = event.target.previousElementSibling == null;
$.ajax({
method: 'POST',
url: urlLikes,
data: {isLikes: isLikes, postId: postId, _token: token}
})
.done(function() {
});
});
PHP:
$post_id = $request['postId'];
$is_visit = $request['isLike'] === 'true';
$post = Post::find($post_id);
if (!$post) {
return null;
}
$liked = Auth::user()->likes()->where('post_id', $post_id)->first();
if($liked == $is_like){
$liked->delete();
return null;
}
else{
$liked = new Like();
}
$liked->user_id = Auth::user();
$liked->post_id = $post->id;
$liked->save();
return null;
}
Please help to find the issue in this code or point me in the direction of a like system without the boolean and just a simple like(post)/unlike(delete) with Laravel and AJAX.
I think the problem is that you are performing a Boolean / Object compassion.
I suggest rewriting your if condition in:
if( !is_null($liked)){...}

Yii CgridView bulk delete

In many of my Models' CgridViews I have a bulk delete function: a chechboxColumn and a delete button which deletes all the checked users. For that I am using ajax in the admin and a new action in the controller.
All this works fine until I add pagination to th gridview, which is not saving the checked rows in the previous pages.
I tried to use
'enableHistory'=true,
but it did nothing (and from what I'v read I'm not the only one :mellow: ) , so I downloaded this extension: selgridview
The extension works - when I move through the pages , the checked rows stay checked BUT , my bulk delete function is seeing only the checked rows of the page I'm in right now.
this is the ajax I'm using:
<?php
Yii::app()->clientScript->registerScript('delete','
$("#butt").click(function(){
var checked=$("#person-grid").yiiGridView("getChecked","person-grid_c11");
var count=checked.length;
if(count>0 && confirm(" are you sure you want to delete "+count+" people ? "))
{
$.ajax({
data:{checked:checked},
url:"'.CHtml::normalizeUrl(array('person/remove')).'",
success:function(data){$("#person-grid").yiiGridView("update",{});},
});
}
});
');
?>
Now , maybe thats a silly question but I know little about javascript.
I'm not even sure that the problem is in the ajax . . . .
Help would be much appreciated :rolleyes:
I am using selgridview extension.
Here is my code for deleting the selected users
//delete multiple users at once
$('#delete_selected_items_button').on('click', function () {
var selected = $("#users-grid").selGridView("getAllSelection");
//if nothing's selected
if ( ! selected.length)
{
alert('Please select minimum one user to be deleted');
return false;
}
//confirmed?
if ( ! confirm('Are you sure to delete ' + selected.length + ' users?')) return false;
var multipledeleteUrl = "<?php echo Yii::app()->baseUrl;?>/users/multipledelete";
$.ajax({
type: "POST",
url: multipledeleteUrl,
data: {selectedUsers : selected},
success: (function (e){
//just to make sure we delete the last selected items
$("#users-grid").selGridView("clearAllSelection");
//we refresh the CCGridView after success deletion
$.fn.yiiGridView.update("users-grid");
}),
error: (function (e) {
alert("Can not delete selected users");
})
});
})
On UsersController, actionMultipleDelete() do something like this
if (Yii::app()->request->isAjaxRequest)
{
$selectedUsers = Yii::app()->request->getPost('selectedUsers');
//iterate through all ids
foreach ($selectedUsers as $id)
{
//delete the user here...
}
}
I don't know about this plugin and how it saves what checkboxes are
checked, but you can look into that and then send that information
to your controller.
Alternatively you can save which models should be
deleted in a session. On a checkbox click() (check if the check box is checked
or unchecked) event call your controller with ajax to save the
model's id in your session. then when the user clicks delete you can
retrieve this data from the session.

Populating a dropdown based on the selection of another dropdown using Jquery in Codeigniter

I am using Codeigntier and I have the following dropdown in my view file which populates a list of subjects.
<?php echo form_dropdown('subject1', $dropdown_subjects,'',
'class="required" id="subject1"'); ?>
Now when any one selects any value from the dropdown above, I want to send the value to my controller using jquery and query in the following table( SELECT teacherid from table3 WHERE subjectid=$subjectid) to get the teacherid so that I can populate the teacherid list in another dropdown select. If any user changes his selection from the first dropdown I want to get the values of the second dropdown changed also
Table Name: table3
subjectid teacherid
1 1001
2 1003
So the bottom line is I want to populate a dropdown based on another dropdown. I have found couple of tutorials on this topic but I couldn't really understand those(I know I am stupid).
Would you please kindly show me how my view and controller should look like if I want to achieve this?
Thanks :)
EDit
Hi, this is how my controller and view file looks like :
My Controller
$id= $this->input->post('subject_id'); //receiving the ajax post from view
$this->db->select('teachername,teacherid');
$this->db->from('subject_teacher');
$this->db->join('teacher', 'teacher.teacherid = subject_teacher.teacherid');
$this->db->where('subjectid',$id);
$records = $this->db->get('');
$data=array();
$data[''] = 'Select';
foreach ($records->result() as $row)
{
$data[$row->teacherid] = $row->teachername;
}
return ($data); // I need help here... How to send the data as json?
My view:
<script>
$(function(){
$("#subject").change(function(){
$.ajax({
url: "<?echo base_url();?>mycontroller/function",
data: {subject_id: $(this).val()},
type: "post",
success: function(msg){
$("#teacher").html(); // I need help here...how do I get the value from controller and append to my another dropdown named teacher?
})
})
}); // function ends here
</script>
<?php echo form_dropdown('subject1', $dropdown_subjects,'',
'class="required" id="subject1"'); ?>
<select name="teacher" id="teacher">
<option value="">Select</option>
</select>
Please make the necessary changes in my View and Controller for me.
Thanks in Advance :)
You can do this by using jquery ajax. First you post subject_id to ajax page, ajax page will return the list of teacher in combo box and then the result is populated in the first page.
$("#subject").change(function(){
$.ajax({
url: "your-ajax-page-url",
data: {subject_id: $(this).val()},
type: "post",
success: function(msg){
$("#teacher").html();
})
})
This is the edited controller
$id= $this->input->post('subject_id'); //receiving the ajax post from view
$this->db->select('teachername,teacherid');
$this->db->from('subject_teacher');
$this->db->join('teacher', 'teacher.teacherid = subject_teacher.teacherid');
$this->db->where('subjectid',$id);
$records = $this->db->get('');
$output = null;
foreach ($records->result() as $row)
{
$output .= "<option value='".$row->teacherid."'>".$row->teachername."</option>";
}
echo $output; // HTML example
you may do it like this :
you will have to create a function inside your controller which will populate the data but instead of outputting your view you will have to put it inside a var like this
$outout = $this->load->view('myselect_output',$data,TRUE);
and then in your main view you will have to manipulate the DOM with jquery or any other js library ..

How to refresh content after ajax update?

I have an admin page for a WordPress plugin that, thanks to the stackoverflow community, I've learned how to add ajax calls to all of the functions that add/delete/update questions and answers for the plugin to access.
To help visualize it:
The next step is to refresh the content after a successful ajax call. Of course I don't want to just re-load the page and I assume refreshing the entire page might cause the answer divs to collapse, which would be undesirable. So refreshing only the related content is best.
The list of questions is generated with the following call to the database:
<?php
$qresult = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "ccd_ex_questions ORDER BY sort ASC");
$qcount = $wpdb->num_rows;
foreach( $qresult as $key => $qrow ) {
?>
<div id="question<?php echo $qrow->id; ?>" class="display-questions">
<form id="update-question-<?php echo $qrow->id; ?>" action="" method="post">
//question form and content
</form> {snip...}
and the answers are done similar and within the loop generating the list of questions:
<?php
$aresult = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "ccd_ex_answers WHERE question_id = " . $qrow->id . " ORDER BY sort ASC");
foreach( $aresult as $key => $arow ) {
?>
<form id="update-answer-<?php echo $arow->question_id."-".$arow->id; ?>" action="" method="post">
//answer form and content
</form> {snip...}
The following is one of the jQuery functions using an ajax call to update content:
//Add New Answer
jQuery(document).ready(function($) {
$('.asubmitbutton').live("click", function(){
var thisasubmit = $(this).data('asubmit');
$(thisasubmit).submit(function(){
// Get the proper instance of the form fields for the variables
var answer = $(this).find('.answer').val();
var sort = $(this).find('.sort').val();
var correct = $(this).find('.correct').val();
var question_id = $(this).find('.question_id').val();
$.ajax({
type: 'POST',
url: ajaxurl,
data: {
action: 'ccd_ex_insert_answer',
answer: answer,
sort: sort,
correct: correct,
question_id: question_id
},
success: function(data, textStatus, XMLHttpRequest){
console.log(data);
console.log(answer);
console.log(sort);
console.log(correct);
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
return false;
});
});
});
And while we're at it, here's the php function handling this ajax call:
//Add an answer
function ccd_ex_insert_answer() {
global $wpdb;
$wpdb->insert( $wpdb->prefix . 'ccd_ex_answers', array(
'answer' => $_POST['answer'],
'sort' => (int)$_POST['sort'],
'correct' => (bool)$_POST['correct'],
'question_id' => (int)$_POST['question_id']
)
);
}
add_action( 'wp_ajax_ccd_ex_insert_answer', 'ccd_ex_insert_answer' );
As is, everything works except that changes don't show until the next page re-load.
I presume that I need to add the functions to refresh the data into the success: handler, but I couldn't find an example that spoke to updating the content that is pulled from the database.
So my question is: How to refresh only the updated content after ajax call and, if possible, maintain the visibility of expanded divs?
Any help would be greatly appreciated! Note: I am barely an intermediate jQuery user and this is my first ajax attempt, so it's better to assume I know nothing if it prevents something important from shooting over my head. ;)
UPDATE: I think I am making progress, but still missing something. Problem with the proposed solution is that .html(data) was returning '0'. By removing the line: url: ajaxurl, from the ajax call, what is returned now is the entire page content. What I really need to be returned is just the updated content.
First, you want to do a POST to a page/url that will return only the updated content for a certain element (say, with id="id"). For example, you do a call
$.ajax({url:"http://example.com/newcontent.php", ...});
and the PHP page simply returns
<?php echo "thisisnewcontent"; ?>
You can then update the html of any DOM element with
$("css_selector").html(newContent); // newContent will contain "thisisnewcontent"
You should do this update in the ajax success function, where 'data' represents the data that you received from the server.
$.ajax({ ..., success: function(data, textStatus, XMLHttpRequest) {
$("#id").html(data);
});
You can read more about ajax() and html() here http://api.jquery.com/jQuery.ajax and here
http://api.jquery.com/html/
Good luck!

Resources