I am trying to delete a row from a table using jquery ajax. After couple of trying I cant figure out why my code (deleting part) is not working as I am new with ajax and javascript. Loading data with ajax from server works fine and the script has no console error. When I press delete, I see nothing on network tab. Here is my code:
routes.php
Route::delete('users/{id}','AjaxController#destroy');
AjaxController.php
public function destroy($id)
{
$user = User::findOrFail($id);
$user->delete();
}
view:
<table id="users" class="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Phone</th>
<th>Action</th>
</tr>
</thead>
<tbody id="abc">
</tbody>
</table>
script:
$(document).ready(function(){
var $tbody = $('#abc');
// getting data from server
$.ajax({
type : 'GET',
url : 'api/users',
success: function(users) {
$.each(users, function(i, user){
$tbody.append('<tr id="user_' + user.id + '"><td>'+user.name+'</td><td>'+user.phone+'</td><td><button type="button" class="btn btn-xs btn-danger" id="delete" value="'+user.id+'" name="button">Delete</button></td></tr>');
});
},
error: function(){
alert('error loading data');
}
});
// deleting data
$('#delete').on('click', function(e){
var user_id = $(this).val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
})
e.preventDefault();
var user = {
id : user_id
};
$.ajax({
type: 'DELETE',
url : '/user/'+user.id,
success : function(deleteUser)
{
$("#user_" + user_id).remove();
},
error : function()
{
alert('error deleting data');
}
});
}); // deleting block ends
});
});
The problem here is that you're using the same id over and over. However this issue is further compounded by the fact that you are dynamically inserting the content, but your event binding is only observing elements available at page load. Let's fix all of this. First, we need to do-away with the ID.
class="btn btn-xs btn-danger" id="delete" value="'+user.id+'"
Needs to be changed to
class="btn btn-xs btn-danger btn-delete" value="'+user.id+'"
Great. We've used btn-delete. This isn't specific to this particular user functionality. The way that CRUD works, you should be able to re-use this code for every single Model that you interact with through the CRUD Controller.
Now we need to delegate our event binding, and we'll also make the button more generic as discussed in the previous paragraph. For the sake of post length, I'll only show what you -should- have your javascript set up like.
$('table').on('click', '.btn-delete', function(e){
e.preventDefault();
var $btn = $(this),
$table = $btn.closest('table');
$.ajax({
url: $table.data('resource') . '/' . $btn.val(),
type: 'delete'
}).done(function(response){
console.log(response);
}).error(function(x,t,m){
console.warn(x,t,m);
});
});
The token can be moved to the top of the file, it does not need to be nested:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
Finally, we need to attach our data-resource property to our table:
<table ... data-resource="users"
Now you've got a reusable model and only need to attach a data-resource="model" property to your table, and a button with a class of btn-delete a value with the id of the entity.
Related
In my Laravel app, I add ajax query (which work after pressed button). I get the result in ajax, I see it on console (it's array).
But I need to send an answer from js to PHP for creating a table
This is code of input:
<input type="text" name="check" id="check">
This is code of button:
<button type="button" class="check-client btn btn-success">Find</button>
This is code of ajax (JS):
$(document).on("click", ".check-client", function () {
const data = $("#check").val();
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: 'POST',
data: {
'data': data
},
url: '/checkValues',
success: function (result) {
console.log(result);
const dataForTable = result;
}
});
});
For creating table I try to do this:
send response to php+html:
$(".testClass").append(result);
get this value:
<div class="testClass"></div>
and create a table, using foreach:
<div class="testClass"></div>
<table class="table table-bordered text-center">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Person</th>
<th scope="col">Cost</th>
</tr>
</thead>
<tbody>
#foreach($dataForTable as $item)
<tr>
<th scope="row">$item['id']</th>
<td>$item['person']</td>
<td>$item['cost']</td>
</tr>
#endforeach
</tbody>
</table>
So, it doesn't work. How to create a table from ajax response?
The problem is that you trying to run jQuery at the client side to uses the return of ajax request (dataForTable) at the server side, it's out of PHP context server. PHP works only server side, meanwhile jQuery is working on browser client, if you want to run javascript in the server side you have to search for other technology, like Node, look at node.js.
Wether you want to update a table on client side using ajax request you have to update a table iterate de variable (dataForTable) on client side, after the request, like this:
$.getJSON( "ajax/test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
There are many other examples like this above in jQuery.
Finally, you have to work at Client side wether you want to use jQuery, or work at server side using the PHP helpers.
I am trying to call a PHP script/file that will read data off of an HTML table. I want to press a button so that the PHP script/file will activate and read the data off of the HTML table into a database using MySQL.
My AJAX script is not activating the PHP file.
The HTML button code:
<button type="submit" class="btn btn-md btn-primary btn-block" id="save">Save Workout</button>
The AJAX code:
$(document).ready(function(){
$("#save").click(function(){
$.ajax({
type: 'POST',
url: 'addWorkoutTEST.php',
success: function() {
alert("hello");
}
});
});
});
The incomplete PHP code (does not contain DB code) - based off of https://brennanhm.ca/knowledgebase/2015/11/import-html-table-into-mysql-table/
<?php
require_once ('simple_html_dom.php');
$table = file_get_html('addWorkout.php');
$db = mysqli_connect('localhost', 'root', '', 'workoutLogger');
foreach($table ->find('tr') as $tr) {
$exercise = $tr->find('td', 0)->plaintext;
$weight = $tr->find('td', 1)->plaintext;
$sets = $tr->find('td', 2)->plaintext;
$reps = $tr->find('td', 3)->plaintext;
$exercise_c = mysqli_real_escape_string($db, $exercise);
$weight_c = mysqli_real_escape_string($db, $weight);
$sets_c = mysqli_real_escape_string($db, $sets);
$reps_c = mysqli_real_escape_string($db, $reps);
}
?>
I can't get a success message to pop up.
What I ended up doing was keeping the and wrapping the button around a form with the action "addWorkoutTEST.php", that did it perfectly.
<form action="addWorkoutTEST.php">
<button type="submit" class="btn btn-md btn-primary btn-block" name="save">Save Workout</button>
</form>
To prevent the default Form Submit action you just need to add in the event.preventDefault();
Something like this...
$(document).ready(function(){
$("#save").click(function(event){ // must include event here to match the object in the next line. It can be called anything.
event.preventDefault(); // Prevent Default Submit
$.ajax({
type: 'POST',
url: 'addWorkoutTEST.php',
success: function() {
alert("hello");
},
error: function (request, status, error) {
alert("ERROR: " + request.responseText);
}
});
});
});
If javascript is disabled for whatever reason, you need to decide what action to take. With what you have so far in your answer to your form with the added action, that would be the fallback in such a case. It's something you need to think out and decide upon.
I am using Django to enter some data into my database. After entering the data I want to edit it. Now, what I am trying is, the user should not go to any other page to change the data. So I have implemented a javascript method which edits the text on the front end.
How do I reflect the changes made by the user in the database?
The related code is given below:
<html>
{% csrf_token %}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<table id="table">
<tr>
<th>Name</th>
<th>Phone Number</th>
</tr>
{% for record in queryset %}
<tr>
<td onClick="clickable(this)"> {{record.first}} </td>
<td onClick="clickable(this)"> {{record.second}}</td>
</tr>
{%endfor%}
</table>
<script>
function clickable(ele)
{
var value = prompt("Enter the details");
if(value)
{
ele.id='edited'
ele.innerHTML = value;
//I want to send the request to my django view to edit the database here
//The data has been updated.
}
You should send a Ajax request to your server using jQuery you are using. with Ajax request request you should send your updated data .
Simple Ajax request can be .
$('#click_place').click(function() { // when click is placed
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the content here Ex. {'name': 'test', 'phone': '123'}
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // request url
success: function(response) { // on success..
// display your message
}
});
return false;
});
You can follow How to POST a django form with AJAX & jQuery .
http://coreymaynard.com/blog/performing-ajax-post-requests-in-django/ .
Edit :
You can simply call below function at any event .
function myajaxhit() {
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the content here Ex. {'name': 'test', 'phone': '123'}
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // request url
success: function(response) { // on success..
// display your message
}
});
}
just call myajaxhit() at any place . Please change it as per your requirement .
I am having a table in which data is being populated through the database.Now what i want is that as soon as i click on one of the row a alert message displays and the READSTATUS of that row become true in my database that is database gets updated .
Now my problem is where to write the code for updating the database as i dont want to move to a different page to do so.
Like my table is something like this :
<input type=hidden name="notifyidd" id="notifyidd" value="<%=messageid%>"/>
<tr bgcolor="#5D1B90" color="#FFFFFF" onmouseover="ChangeColor(this, true,false);" onmouseout="ChangeColor(this, false,false);" onclick="DoNav('shownotification.jsp?mid=<%=messageid%>');">
<td><input type="checkbox" name="" onclick="DoRemove(event);" width="20" class="select_all_mail" value=<%=messageid%>></td>
<td callspan="3" width="1000px"><%=messagesubject%> at <%=sendingtime%></td>
</tr>
and in onclick method of each row i had called the alert.But how to update the database now ?
function DoNav(theUrl)
{
var tt = document.myinbox.notifyidd.value;
alert(tt);
//document.location.href = theUrl;
}
As if i uncomment this line then it will move to next page.But i want to do it on same page only.Please help
EDIT :
I wrote a ajax code to do it.But it gives error.Please help
$(document).ready(function() {
$('#myrow').click(function ()
{
$.ajax({
type: "post",
url: "shownotification.jsp", //this is my servlet
data: {
notifyidd: $('#notifyidd').val()
},
success: function(msg){
if(msg == "success")
alert('Data updated.');
}
});
});
});
Here i assign myrow as id to my table row.Also i removed doNav function now
My error image clicked :
http://postimg.org/image/vix1vzvq5/
Though the error is resolved but this ajax call is not functioning.For test i make my shownotification.jsp as :
<body>
<% String notifyid = request.getParameter("notifyidd");%>
success
</body>
The error message says the server-side code is failing when looking for the attribute "groupid". The post you are sending has notifyidd instead. The server code has no way of knowing if this should map to groupid or not.
Try this. If it doesn't work, update us with the error.
$(document).ready(function() {
$('#myrow').click(function ()
{
$.ajax({
type: "post",
url: "shownotification.jsp", //this is my servlet
data: {
groupid: $('#notifyidd').val()
},
success: function(msg){
if(msg == "success")
alert('Data updated.');
}
});
});
});
I am trying to update a record list with ajax, represented on a table, where each record as an javascript delete link. If I preload the table, the RemoveLink works fine, but once the div "RecordListPartialView" is updated via ajax, It no longer works.
I checked with firebug that the generated html code is correct for each row. It looks like the browser isn't aware of the new code and so it doesn't trigger the javascript links.
Can someone please explain me what is going on?
(1) Here is the View code:
$(".RemoveLink").click(function () {
var _id = $(this).attr("data-id");
var recordToDelete = { id: _id };
var json = $.toJSON(recordToDelete);
$.ajax({
url: '/MortagePayment/RemoveMortageRecord',
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#RecordListPartialView").empty();
$("#RecordListPartialView").html(data.Message);
}
});
});
$(".AddLink").click(function () {
var _year = $("#NewRecord_year").val();
var _month = $("#NewRecord_month").val();
var _mortageValue = $("#NewRecord_mortageValue").val();
var newRecord = { year: _year, month: _month, mortageValue: _mortageValue };
var json = $.toJSON(newRecord);
$.ajax({
url: '/MortagePayment/AddMortageRecord',
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#RecordListPartialView").empty();
$("#RecordListPartialView").html(data.Message);
$("#NewRecord_year").val(0);
$("#NewRecord_month").val(0);
$("#NewRecord_mortageValue").val(0);
}
});
});
<div id="RecordListPartialView">
#Html.Partial("MortageRecordList", Model.MortageRecordList)
</div>
(2) the Partial View
<table id="mortageRecordListTable">
<tr>
<th colspan=4>Current reductions</th>
</tr>
<tr>
<th>Year</th>
<th>Month</th>
<th>Value</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr id="row-#item.mortageRecordId">
<td>
#item.year
</td>
<td>
#item.month
</td>
<td>
#item.mortageValue
</td>
<td>
<p class="RemoveLink" data-id="#item.mortageRecordId">Remove</p>
</td>
</tr>
}
</table>
(3) and the Controller:
[HttpPost]
public ActionResult AddMortageRecord(MortageRecord newRecord) {
var mortageRecordSet = MortageRecordSet.GetMortageSet(this.HttpContext);
if (ModelState.IsValid)
mortageRecordSet.AddMortageRecord(newRecord);
string partialViewHtml = RenderPartialViewToString("MortageRecordList", mortageRecordSet.GetMortageItems());
return Json(new { Success = true, Message = partialViewHtml });
}
[HttpPost]
public JsonResult RemoveMortageRecord(int id) {
var mortageRecordSet = MortageRecordSet.GetMortageSet(this.HttpContext);
mortageRecordSet.RemoveMortageRecord(id);
string partialViewHtml = RenderPartialViewToString("MortageRecordList", mortageRecordSet.GetMortageItems());
return Json(new { Sucess = true, Message = partialViewHtml });
}
If I understand you correctly.
If I preload the table, the RemoveLink works fine, but once the div
"RecordListPartialView" is updated via ajax, It no longer works.
Change your your .click event with .live
$(".RemoveLink").live("click",function(){
//any click event code comes here
});
I think you might need to call the click handler again in order to reattach it to the new DOM elements, since jQuery iterates through all the elements with the correct class when you actually call the $(".RemoveLink").click() and $(".AddLink").click() functions, not lazily whenever something is clicked.
OK, do you have a jquery event in a separate .js script file and have attached an event to an element inside a PartialView?
well! if yes, whenever the PartialView renders itself again (no matter what is the reason) all of it's bound events will be gone! then you should rebind them again after rendering the PartialView.
there are different approaches, for example:
In the Ajax.ActionLink (or any ajax call that makes the
PartialView re-render ) set OnSuccess to a jquery function that
rebinds PartialView's events.
Move all of your jquery event bindings codes from separate .js
script file to the inside of your PartialView's file (cstml). in
this case every time PartialView has been rendered, those events
will be bound again.