Django data updation in the table - javascript

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 .

Related

Implementing Jquery ajax get request in laravel

Am more of an angular person so i do not really do well with jquery. I have a project i took over from someone and i have to implement a get request to my controller and append returned data to view. I know this is vague but i would appreciate any help.
<tbody>
#foreach($restaurant_meals as $meal)
<tr>
<td>
{{$meal->name}}
</td>
<td>
${{$meal->price}}
</td>
<td>
<i class="fa fa-plus-circle"></i>
</td>
</tr>
#endforeach
</tbody>
This is my view.
This is my ajax request.
<script type="text/javascript">
$(documnent).ready(function(){
$.ajax({
method: 'GET', // Type of response and matches what we said in the route
url: '/addtocartid' + id, // This is the url we gave in the route
data: {'id' : id}, // a JSON object to send back
success: function(response){ // What to do if we succeed
console.log(response);
}
});
});
Then my Controller would be
public function getaddtoCart(Request $request, $id)
{
$product = Product::find($id);
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$cart = new Cart($oldCart);
$cart->add($product, $product->id);
$request->session()->put('cart', $cart);
return redirect()->route('home');
}
Any help would be appreciated
Your problem is with the concatenation of the id in the URL. It is adding the extra numbers in the URL pattern.
$(documnent).ready(function(){
$.ajax({
method: 'GET', // Type of response and matches what we said in the route
url: '/addtocartid', // This is the url we gave in the route
data: {'id' : id}, // a JSON object to send back
success: function(response){ // What to do if we succeed
console.log(response);
}
});
});
Like /addtocartid1 instead of /addtocartid/1
Ideally that should be removed. You are already sending the parameters by data property

Append AJAX Output to HTML table

I have done my research and I can't seem to find the appropriate answer.
Here is the problem. First off, this question may be broad. And I am new to ajax. I am using laravel and I have just created a controller which handles two dates whereBetween to find the result set and ajax is handling the get request. I am having two issues.
First being, I have no idea on how to append to my existing table. The other issue is a bit complicated. Currently i am using carbons diffForHumans() to display the time taken.
Also using if else statements. Here is how my current table looks like (this is looped from controller for sample data. this is not ajax):
<table class="table">
<thead>
<tr>
<th>Room Number</th>
<th>Cleaned By</th>
<th>Total Time</th>
<th>Supervised</th>
<th>Issues</th>
<th>Cleaned</th>
<th>View</th>
</tr>
</thead>
<tbody>
#foreach($clean as $cleans)
<tr>
<td>{{$cleans->roomnumber}}</td>
<td>{{$cleans->users->name}}</td>
<td>{{$cleans->roomnumber}}</td>
#if($cleans->verified == 1)<td class="verified">Yes</td>#else()<td class="notverified">No</td>#endif
#if($cleans->img1 || $cleans->img1 || $cleans->img1 == !null)<td class="verified">Yes</td>#else()<td class="notverified">No Issues</td>#endif
<td>{{$cleans->created_at->diffForHumans()}}</td>
<td><i class="lnr lnr-eye"></i></td>
</tr>
#endforeach
</tbody>
</table>
As shown above, i have used with() in my controller to get the users name using user_id column. And the diffForHumans(). Also some if else statements.
Here is my AJAX so far:
$(function() {
$('.form').submit(function(event) {
// get the form data in value key pair using jquery serialize
var data = $(this).serialize();
// get the url we are posting to from the forms action attribute
//var url = $(this).attr('/admin/search');
// process the form
var search = $.ajax({
type: "POST", // define the type of HTTP verb we want to use (POST for our form)
url: "search", // the url where we want to POST
data: data, // the url where we want to POST, set in variable above
dataType: "json", // what type of data do we expect back from the server
encode : true
})
// using the done promise callback (success)
search.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});//submit function
});//doc ready end
So how can I append to the above table and still maintain those diffForHumans(), if else statements and most importantly the user name using user_id column (relation)?
Update (Controller):
public function search(Request $request){
$data = $request->only(['from', 'to']);
$data['to'] .= ' 23:59:59';
$output = Clean::whereBetween('created_at', $data)->get();
//return view('admin/search-test', compact('output'));
//return Response($output);
return Response::json(array($output));
}

Updating the database on click of a table row

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.');
}
});
});
});

How do I use AJAX to print out data inside a div?

I have two files. One file is named index.php and another file is named process.php.
I have a form that submits to process.php in index.php:
<form class="form" action="process.php" method="POST" name="checkaddress" id="checkaddress">
<table>
<tr class="element">
<td><label>Address</label></td>
<td class="input"><input type="text" name="address" /></td>
</tr>
</table>
<input type="submit" id="submit" value="Submit"/>
</form>
<div class="done"></div>
I also have a process in process.php to echo some data based off of the input. How would I be able to use AJAX to submit the form without leaving the page?
Is it something like:
$.ajax({
url: "process.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
$('.done').fadeIn('slow');
}
});
What page would I put the above code on if it was right?
Also, how do I change the above code to say what the process.php outputted? For example, if I echo "Hello" on process.php, how do I make it say it in the done div?
I have seen many responses regarding AJAX, but they all rely on data that is pre-made like APIs. I need to do a database query and fetch the data dependent on the address entered and print the data out.
You need to collect the data in the form so that you can submit them to the process page, and you need to run your code when submitting the form (and cancel the default form submission)
$('#checkaddress').on('submit', function(e){
// get formdata in a variable that is passed to the ajax request
var dataToPassToAjax = $(this).serialize();
$.ajax({
url: "process.php",
type: "GET",
data: dataToPassToAjax,
cache: false,
success: function (resultHtml) {
// add the returned data to the .done element
$('.done').html( resultHtml ).fadeIn('slow');
}
});
// cancel the default form submit
return false;
});
[update]
If you want to modify the data before submitting them, you will have to manually create the parameters to pass to the ajax
$('#checkaddress').on('submit', function(e){
// get formdata in a variable that is passed to the ajax request
var dataToPassToAjax = {};
var address = $('input[name="address"]', this).val();
// alter address here
address = 'something else';
dataToPassToAjax.address = address;
$.ajax({
url: "process.php",
type: "GET",
data: dataToPassToAjax,
cache: false,
success: function (resultHtml ) {
// add the returned data to the .done element
$('.done').html(resultHtml ).fadeIn('slow');
}
});
// cancel the default form submit
return false;
});
You could use the jQuery form plugin: http://jquery.malsup.com/form/
Let me know if you want example code.

How to reload elements on a page in JS

Hi All I have a an AJAX query as seen below:
function buttonCallback(obj){
var id = $(obj).attr('id');
$.ajax({
type: "POST",
url: "/project/main/passid",
data: { 'id': id },
success: function(msg){
$("#reloadtable").html("result reloaded successfully"); //? reload?
}
});
}
the query successfully runs - I was hoping to reload a table I have created in html after the query runs - I took some code from another post but it doesn't seem to run - my table body tag is:
<tbody class = "tablereload">
I am entirely new to JS so I apologise if this question is stupid or incorrect - but I am hoping to reload the body of the table after the query has run - is this possible? or refreshing the whole page - without redirect?
The page /project/main/passid should return html like (echo it if it is php page)
<tr>
<td>.....</td>
</tr>
And changes to you Ajax call:
function buttonCallback(obj){
var id = $(obj).attr('id');
$.ajax({
type: "POST",
url: "/project/main/passid",
data: { 'id': id },
success: function(msg){
$(".tablereload").html(msg); //? reload?
}
});
}
Your have a ID selector and in the html you have a class for the tbody.
You can put the Id for the tbody
<tbody id = "tablereload">
or change the script
$(".reloadtable").html("result reloaded successfully");

Categories