I need the guidance of somebody to help me building the function Update Database when using AJAX. When I click the button Accept so an Ajax request will send to the server and server will execute UPDATE value of field post_status. At the start, field post_status has value is "pending", and after execute query UPDATE so the value will change to "accepted".
What's I should do next? Please help me.
Thank you so much for help.
The database of the Posts table:
post_id user_id title content DateTime post_status
1 1 Title 1 Content 1 Time pending
2 2 Title 2 Content 2 Time pending
3 3 Title 3 Content 3 Time pending
4 4 Title 4 Content 4 Time pending
5 5 Title 5 Content 5 Time pending
The View:
<table class="table table-bordered">
<thead class="thead-inverse">
<tr>
<th>Post ID</th>
<th>User ID</th>
<th>Name User</th>
<th>Title</th>
<th>Content</th>
<th>Datetime</th>
<th>Status</th>
<th>Accept</th>
</tr>
</thead>
<tbody>
#foreach ($posts as $row)
<tr id="{{ $row->post_id }}">
<td>{{$row->post_id}}</td>
<td>{{$row->user_id}}</td>
<th>{{$row->users->name}}</th>
<td>{{$row->post_title}}</td>
<td>{{$row->post_content}}</td>
<td>{{$row->post_datetime}}</td>
<td>{{$row->post_status}}</td> {{-- The status of post that I wanna change the value to "accepted" --}}
<td>
<button class="btn btn-success accept-btn" data-postID="{{$row->post_id}}">Accept</button>
</td>
</tr>
#endforeach
</tbody>
</table>
The code Javascript:
<script>
$(document).ready(function () {
$('.accept-btn').click(function(){
var postId = $(this).attr('data-postID');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "{{route('posts.list_post_ajax')}}",
data: { postId: postId },
dataType: 'JSON',
success :function(response) {
console.log(response);
},
});
})
});
</script>
The function list_post_ajax of Controller:
public function list_post_ajax(Request $request)
{
if(request()->ajax()){
$postId = $request->get('postId');
return response()->json(['success'=>$postId]);
// What's I should do next?
// Pls help me.
}
}
There are so many ways to do it. This one will work following your code. Use $myObject->save(); to save a new record or update a old one.
Change on view
<td id="td{{$row->post_id}}">{{$row->post_status}}</td>
On Controller
$postId = $request->get('postId');
$post = App\Post::find($postId);
$post->post_status= 'accepted';
$post->save();
return response()->json(['success'=>$postId,'message'=>'accepted']);
On JS
$.ajax({
type: "POST",
url: "{{route('posts.list_post_ajax')}}",
data: { postId: postId },
dataType: 'JSON',
success :function(response) {
console.log(response);
$('td'+postId).html(response.message);
},
});
Edit: I update my answer on Controller. You should take a look Eloquent Documentation
Related
I'm just trying to send the editable table row data to the controller onClick of the Save button, update that data in the database, and return success.
But I cannot display the data inside the controller function of laravel. Data inside saveMe function is coming as desired as shown in below screenshot but it is not going to the controller
<table id="customersTable" class="table table-bordered table-responsive-md table-striped text-center" style="border-style: solid; border-color:red">
#php
$customersData = Session::get('data');
$issues = Session::get('issues');
#endphp
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Contact</th>
<th>Address</th>
<th>Name</th>
</tr>
</thead>
<tbody id="bodyData">
#foreach ($customersData as $key => $data)
<form action="ajaxform">
<!-- This is our clonable table line -->
<tr>
<td>{{$key}}</td>
<td name="name" class="pt-3-half name" contenteditable="true"
value={{$data['name']}} data-id={{$key}}>
{{$data['name']}}
</td>
<td name="email" class="pt-3-half email" contenteditable="true"
value={{$data['name']}} data-id={{$key}}>
{{$data['email']}}
</td>
<td>
<div class="test">
<span class="table-save">
<button type="button" onclick="saveMe(this)" class=" btn btn-secondary btn-rounded btn-sm my-0 saveBtn">
Save
</button>
</span>
</div>
</td>
</tr>
</form>
#endforeach
</tbody>
</table>
JavaScript function
<script>
function saveMe(params) {
var tr = $(this).closest("tr"); //get the parent tr
var name = $(params).closest("tr").find(".name").text();
var email = $(params).closest("tr").find(".email").text();
console.log(name);
console.log(email);
$.ajax({
url: '/customers/saveSingleRecord',
type: 'GET',
data: {
_token:'{{ csrf_token() }}',
value: {
'name' : name,
'email' : email,
'contact' : contact,
'address' : address,
},
},
success: function(data){
alert("success");
}
});
}
Function inside the controller
class CustomersController extends Controller
{
public function saveSingleRecord(Request $request)
{
// $name = $_GET['name'];
$name = $request->name;
dd($name); // <------------------ Not showing anything
// return response()->json($name);
}
}
Route inside web.php
Route::post('/customers/saveSingleRecord/', [CustomersController::class, 'saveSingleRecord']);
In your ajax request you are passing your data inside value attribute so it's not showing. If you try $request->value['name'] then it will show you the name. If you want to get name directly in request object then pass as like below.
$.ajax({
url: '/customers/saveSingleRecord',
type: 'GET',
data: {
_token:'{{ csrf_token() }}',
'name' : name,
'email' : email,
'contact' : contact,
'address' : address,
},
success: function(data){
alert("success");
}
});
The correct way to send ajax is below
$.ajax({
url: '/customers/saveSingleRecord',
type: 'GET',
data: {
name : name,
email : email,
contact : contact,
address : address,
_token :'{{ csrf_token() }}',
},
success: function(data){
alert("success");
}
});
Basically you set key value pair within data.
So the situation is such:
I am using data-tables in my .cshtml file. I have managed to add records via a modal but the issue is when i want to populate a modal in order to edit the data from a row. I do not wish to fetch data from the row but instead do a Ajax request to fetch the data. Below shows the structure of my table
<table id="example" class="table table-striped table-bordered dt-responsive display nowrap" cellspacing="0">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
<th>Email</th>
<th>Status</th>
<th>Roles</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach (var user in Model.Users)
{
<tr>
<td>#user.FirstName</td>
<td>#user.LastName</td>
<td>#user.UserName</td>
<td>#user.Email</td>
<td>#user.status</td>
<td>
#{ if (user.Roles.Contains("SuperAdmin"))
{
<span class="badge badge-danger">SA</span> }
else if (user.Roles.Contains("Admin"))
{
<span class="badge badge-danger">ADMIN</span> }
else if (user.Roles.Contains("Moderator"))
{
<span class="badge badge-warning">MOD</span> }
else if (user.Roles.Contains("Basic"))
{
<span class="badge badge-success">BASIC</span> }
}
</td>
<td>
#{ if (user.Roles.Contains("SuperAdmin"))
{
<span class="badge badge-warning">Locked</span> }
else
{
<button class="btn btn-sm btn-dark details" id="useredit" data-id="#user.UserId">Edit</button>
<a class="btn btn-primary btn-sm" asp-area="Identity" asp-page="/Account/UserRoles" asp-route-userId="#user.UserId">Manage Roles</a> }
}
</td>
</tr>}
</tbody>
</table>
When i click on the edit button the follow code gets executed
$("button.details").on('click', function () {
console.log({ "id": $(this).attr("data-id") });
var userid = $(this).attr("data-id");
$.ajax({
type: "POST",
url: "/Identity/Account/Users?handler=UsersAsJson",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: { id:userid },
contentType: "json; charset=utf-8",
success: function (regions) {
console.log(regions)
},
failure: function (response) {
alert(response);
}
});
});
And this is the handler function below
public async Task<IActionResult> OnPostUsersAsJsonAsync(string? id)
{
System.Diagnostics.Debug.WriteLine("id passed",id);
return new JsonResult(id);
}
Can anyone tell me how do we pass the id from the ajax request into the handler function? cause at the moment its not posting to the OnPostUsersAsJsonAsync function.
Also note i have tried getJSON without any success.
For you do not have a form,be sure you have added token like below:
<button class="btn btn-sm btn-dark details" id="useredit" data-id="#user.UserId">Edit</button>
#Html.AntiForgeryToken()
Change your js like below:
#section Scripts
{
<script>
$("button.details").on('click', function () {
console.log({ "id": $(this).attr("data-id") });
var userid = $(this).attr("data-id");
$.ajax({
type: "POST",
url: "/Identity/Account/Users?handler=UsersAsJson",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: { id: userid },
//contentType: "json; charset=utf-8", //remove this line
success: function (regions) {
console.log(regions)
},
failure: function (response) {
alert(response);
}
});
});
</script>
}
Startup.cs:
services.AddRazorPages();
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN"); //be sure add this line
Result:
I started messing around with Vue.js earlier this week.
So far I created a list of MTG(a TCG) cards. The data comes from the database through an Ajax request. This all works like a charm.
What i want to do next is replace the string that contains the costs of a card e.g. something like '{1}{U}{G}' with images for the corresponding tag.
HTML:
<div v-for="(cards, key) in mainBoard" class="">
<table class="table">
<tr>
<th colspan="5">#{{ key }}</th>
</tr>
<tr>
<th>#</th>
<th>Name</th>
<th>ManaCost</th>
#if($deck->enableCommander())
<th>Commander</th>
#else
<th></th>
#endif
<th>Actions</th>
</tr>
<tr v-for="card in cards">
<td>#{{card.pivot.quantity}}</td>
<td>#{{card.name}}</td>s
<td v-html="replaceManaSymbols(card)"></td>
#if($deck->enableCommander())
<td>
<span v-if="card.pivot.commander" #click="preformMethod(card, 'removeCommander', $event)"><i class="fa fa-flag"></i></span>
<span v-else #click="preformMethod(card,'assignCommander', $event)"><i class="far fa-flag"></i></span>
</td>
#else
<td> </td>
#endif
<td>
<button #click="preformMethod(card,'removeCardFromDeck', $event)"><i class="fa fa-times-circle"></i></button>
<button #click="preformMethod(card,'plusCardInDeck', $event)"><i class="fa fa-plus-circle"></i></button>
<button #click="preformMethod(card,'minusCardInDeck', $event)"><i class="fa fa-minus-circle"></i></button>
</td>
</tr>
</table>
</div>
Vue.js
new Vue({
el: '#Itemlist',
data: {
mainBoard: [],
sideBoard: [],
},
methods:{
preformMethod(card, url){
var self = this;
var varData = {
slug: '{{ $deck->slug }}',
card: card.id,
board: card.pivot.mainboard
};
$.ajax({
url: '/vue/'+url,
data: varData,
method: 'GET',
success: function (data) {
self.mainBoard = data.mainBoard;
self.sideBoard = data.sideBoard;
},
error: function (error) {
console.log(error);
}
});
},
replaceManaSymbols(card){
var mc = card.manaCost;
var dump = mc.replace(/([}])/g, '},').split(',');
var html = '';
/**
* replace each tag with an image
*/
return html;
}
},
mounted(){
var self = this;
var varData = {
slug: '{{ $deck->slug }}'
};
$.ajax({
url: '/vue/getDeckList',
data: varData,
method: 'GET',
success: function (data) {
self.mainBoard = data.mainBoard;
self.sideBoard = data.sideBoard;
},
error: function (error) {
console.log(error);
}
});
}
})
I pass the card as a parameter to the replaceManaSymbols method. I can console.log the contents of mana without any issue. But as soon as a want to modify the string Vue throws the error TypeError: Cannot read property 'toLowerCase/split/replace' of null. I'm not really sure what's going wrong. Any idea's?
As a rule of thumb, you shouldn't use methods on the display side. Keep them for the update side - processing changes back into a store and such. Methods aren't reactive - they need to be called. You want your display to automatically reflect some underlying data, so you should use computed.
You should also avoid using v-html, because you end up with markup outside your templates, and that markup is static. It's not totally clear to me what will be in v-html, but you should try and keep markup in your template, and inject values using data, props or computed. Hope this helps!
If you want a div with some text that magically turns into an image tag, this could be a good use for <component :is>.
I create a page on which there is a table with a paginator. I post a request to specify the output of rows from the database for insertion into the table. However, the paginator remains old. How should I change it?
Get a request for a new page or insert all the HTML code that comes from the controller is not satisfied.
Code view:
<table class="table table-bordered text-center table-hover" id="table_list">
<thead>
<tr>
<th>id</th>
</tr>
<tr>
<td><input type="text" class="form-control" id="id_card" value=""></td>
</tr>
</thead>
<tbody>
#if($dats)
#foreach($dats as $data)
<tr>
<td><div class="help" data-id="{{ $data['id'] }}"> {{$data['id']}}</div></td>
</tr>
#endforeach
#endif
</tbody>
</table>
{{ $dats->links() }} // After completing the ajax, the link remains old and allows you to navigate through the old table
Js code in view:
$('#id_card').on('keyup', function(){ // search
value = $(this).val();
$.ajax({
type: 'POST',
url: '/home',
data: {
search: value,
code: 1,
_token: '{{csrf_token()}}'
},
success: function (data) {
$('#table_list').empty();
$('#table_list').append(data); // update table
//update paginator links
},
error: function(data){
console.log(data);
}
})
})
Code controller
public function search(Request $request){
$models= Model::where('table','LIKE','%'.$request->input('search').'%')->paginate(4);
$str = "";
foreach($models as $model){
$str .= '<tr>'.
'<td>'. $model["id"].'</td>'.
'</tr>';
}
print($str);
return;
}
In Laravel 5, you could do it by changing your controller to something like this.
public function search(Request $request){
$models= Model::where('table','LIKE','%'.$request->input('search').'%')->paginate(4);
$str = "";
foreach($models as $model){
$str .= '<tr>'.
'<td>'. $model["id"].'</td>'.
'</tr>';
}
return response()->json([
'rows' => $str,
'links' => $models->render()
], 200);
}
In your ajax response, render the links with $('ul.pagination').replaceWith(data.links);
eg.
$.ajax({
type: 'POST',
url: '/home',
data: {
search: value,
code: 1,
_token: '{{csrf_token()}}',
page: page
},
success: function (data) {
$('#table_list').empty();
$('#table_list').append(data.rows); // update table
$('ul.pagination').replaceWith(data.links); // update links
},
error: function(data){
console.log(data);
}
});
I am trying to get data to knockout from the database using Ajax. But I am not getting any data to my observableArray.
Here is the knockout js model:
self.alldata = ko.observableArray();
self.viewAllInvoice = function () {
$.ajax({
type: 'POST',
url: BASEURL + 'index.php/moneyexchange/learn_Ko/',
contentType: 'application/json; charset=utf-8'
})
.done(function(invoices) {
invoices.forEach(function(invoice) {
self.alldata.push(invoice);
});
})
.fail(function(xhr, status, error) {
alert(status);
})
.always(function(data){
});
};
self.viewAllInvoice();
And here is the html code I am trying to put my data in
<tbody data-bind="foreach: alldata">
<tr>
<td class="text-center"><span data-bind="text: $data.payment_amount "></span></td>
<td class="text-center"><span data-bind="text: $data.allocated_amount"></span></td>
</tr>
</tbody>
I did not create a viewmodel showing all the data from the database since I know what I need to show in the table. And for extra information, I am getting the data from a controller in codeigniter framework. Please do guide me in steps since I am totally new in all this.