How to update database with jQuery without refreshing the page? - javascript

How do I send this display_false() function to the server with jQuery so that the database is updated without refreshing the page?
def display_false():
if display == "false":
main_id = self.request.get("main_id")
k = Main.get_by_id(int(main_id))
k.display = False
k.put()
display_false()
First I hide a table row with this jQuery (see my previous question):
$(document).ready(function() {
$("a.false").click(function(e) {
$(this).closest("tr.hide").hide("slow");
e.preventDefault();
});
and then I want to update the "display" property in the database to "false" with display_false()so that the item is not displayed.
And this is the html where the hide link is:
for item in e:
main_id = item.key().id()
...
<tr class="hide">
...
<a class="false" href="/useradminpage?main_id=%s&display=false"><span class="small">(hide)</span></a>
...
</td>
</tr>
...
Thanks!
Update
This is what I tried according to Paul's answer, but this is not working.
$(document).ready(function() {
//hide the row
$("a.false").click(function(e) {
$(this).closest("tr.hide").hide("slow");
e.preventDefault();
});
$("a.false").click(function() {
//ajax server call
$.ajax({
url: "/useradminpage?main_id=%s&display=false",
success: function(data) {
//do some stuff.
display_false()
alert('returned');
}
});
});
});
Update
I put alerts to see what is running as suggested by Paul. Alerts 1, 2 and 3 are running but 4 is not running:
$(document).ready(function() {
alert("1 - document ready is called")
$("a.false").click(function(e) {
$(this).closest("tr.hide").hide("slow");
e.preventDefault();
alert("2 - row is hidden")
});
$("a.false").click(function() {
//ajax server call
alert("3 - ajax server call")
$.ajax({
url: "/useradminpage?main_id=%s&display=false",
success: function(data) {
//do some stuff.
display_false()
alert(4 - "returned");
}
});
});
});
Update
This is the part of the code for that section of the table; I am trying to get the main_id and pass it to ajax call:
#-----------main table------------#
main_id = self.request.get("main_id")
self.response.out.write("""<table class="mytable">
<tr class="head">
<th width="80%">links</th><th>edit tags</th>
</tr>
""")
query = Main.all()
query.filter("owner", user)
query.filter("display", True)
query.order("-date")
cursor = self.request.get("cursor")
if cursor: query.with_cursor(cursor)
e = query.fetch(100)
cursor = query.cursor()
for item in e:
main_id = item.key().id()
self.response.out.write("""
<tr class="hide">
<td>%s<span class=small> (%s) </span><br />
<span class=small>%s</span>
<span class="small">(edit)</span>
<a class="false" href="/useradminpage?main_id=%s&display=false"><span class="small">(hide)</span></a>
<span class="small">(comments)</span></td>
<td>%s
</td>
</tr>
""" % tuple([item.url, item.title, urlparse(item.url).netloc,
f1.truncate_at_space(item.pitch), main_id, main_id, main_id,
item.url, main_id, (", ".join(item.tag_list)),
(", ".join(item.tag_list)),]))
self.response.out.write("""</tbody></table>""")
display = self.request.get("display")
def display_false():
if display == "false":
main_id = self.request.get("main_id")
k = Main.get_by_id(int(main_id))
k.display = False
k.put()
display_false()
Update after discussion with Paul to get the id number of the hidden row:
<script>
$(document).ready(function() {
alert("1 - document ready is called")
$("a.false").click(function(e) {
$(this).closest("tr.hide").hide("slow");
e.preventDefault();
alert("2 - row is hidden")
});
$("a.false").click(function() {
alert(this.attr("title"));
$.ajax({
url: "/useradminpage?main_id=%s&display=false",
success: function(data) {
display_false()
alert(4 - "returned");
}
});
});
});
</script>

You cannot update a server database with JQuery. All you can do is send a request that is handled by the server.
Use JQuery.Ajax or any spin-offs of that function to send the request. To your server it will look as a regular request.

You'll need an AJAX call, something like this after including your jQuery libraries.
$(document).ready(function() {
//false click action
$("a.false").click(function () {
//ajax server call
$.ajax({
url: '/useradminpage?main_id=%s&display=false',
success: function(data) {
//do some stuff.
alert('returned');
}
});
});
});

Related

Ajax update post request on click jQuery

I would like to click on a previous or next button and update the ajax post request. The parameter I want to change is the variable called "page". The URL of the request takes this variable to show the right page. When I click on a previous or next button I want to change the "page" variable value. Thanks.
$(document).ready(()=>{
var pageSize = "pageSize=10";
//want to change the page number on click
var page = "page=1"
var requestIndex = $.ajax({
type: 'POST',
url: `url`,
beforeSend: function(){
$("#loading").show();
},
complete: function(){
$("#loading").hide();
}
});
// console.log(request)
requestIndex.done((data)=>{
var done = JSON.parse(data)
// console.log(done)
done.forEach((result, index)=>{
// res.push(result)
var firstName = result.FirstName;
var lastName = result.LastName;
var modelYear = result.ModelYear;
var make = result.Make;
var model = result.Model;
var dealership = result.Dealership;
$('#test>tbody').append(`
<tr>
<td>${firstName} ${lastName}</td>
<td>${modelYear}</td>
<td>${make}</td>
<td>${model}</td>
<td>${dealership}</td>
</tr>
`)
})
var tr = $('table').find("tr");
var resultQuant =[]
resultQuant.push(tr)
var pages = []
//loop over each result and create pagination
resultQuant.forEach(function(res, index){
console.log(res.length);
if(res.length > 9){
$('#prev_page').append(`
Prev Page
`)
$('#next_page').append(`
Next Page
`)
}
})
});
requestIndex.fail(function(jqXHR, textStatus) {
console.log('failed')
});
})
Here is a working snippet for what I think you're looking for. I had to make some changes, some for aesthetics, and some for functionality. Here's the functional changes/updates:
Your whole ajax/refresh table script needed to be outsourced to a function so it could be called multiple times.
The page and pageSize variables are better left as numbers rather than queryString strings
I created a delegated event listener on your buttons. It's one listener that will handle either button. The listener callback finds out if its the next or previous button that was clicked, then calls the goToPage() function with the incremented onPage variable
The table is now cleared before each new data batch is written to it, as you'd expect a paginated result to be
The buttons should disable/enable according to the pagination, so I put in a script to test if we're at the first page or the last page to disable/enable them
I changed all your vars to lets because that's the way we initialize block variables nowadays
let onPage, pageSize = 10;
$(document).ready(() => {
goToPage(1)
$('body').on('click', '#next_page, #prev_page', function() {
inc = 1;
if ($(this).attr('id') === 'prev_page') inc = -1;
goToPage(onPage + inc);
})
})
function goToPage(page) {
let requestIndex = $.ajax({
type: 'POST',
url: `url`,
beforeSend: function() {
$("#loading").show();
},
complete: function() {
$("#loading").hide();
}
});
requestIndex.done((data) => {
onPage = page;
$('#test>tbody').html('');
JSON.parse(data).forEach((result, index) => {
$('#test>tbody').append(`
<tr>
<td>${result.FirstName} ${result.LastName}</td>
<td>${result.ModelYear}</td>
<td>${result.Make}</td>
<td>${result.Model}</td>
<td>${result.Dealership}</td>
</tr>
`)
})
if (onPage > 1) $('#prev_page').removeAttr('disabled');
else $('#prev_page').attr('disabled', true)
if (JSON.parse(data).length === pageSize) $('#next_page').removeAttr('disabled');
else $('#next_page').attr('disabled', true)
});
requestIndex.fail(function(jqXHR, textStatus) {
console.log('failed')
});
}
#loading {
display: none'
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='loading'>Loading...</div>
<table id='test'>
<tbody></tbody>
</table>
<button id='prev_page'>Prev Page</button>
<button id='next_page'>Next Page</button>

laravel update status to 0 or 1 when button is toggled in a single row using ajax

I'm relatively new to Laravel. I'm trying to update the 'is_active' column in mysql when the button is toggled without reloading the page. Each row of the table will have the button. I'm also trying to display a pop out message when button is toggled by having the same effect as bootstrap delete confirmation modal.
What i have up to until now is making the toggle button work, but when i tried to toggle the button, there is no changes made to the database. I'm thinking whether should i use a form for the checkbox
UPDATED
This is how my button looks like in html
#foreach($system_functions as $function)
<input type="hidden" id="id_input" value="{{$function->id}}" >
#if($function->group_id == 1)
<tr>
<td>{!! $function->name !!}</td>
<td><input class="toggle_status" type="checkbox" #if($function->is_active) checked #endif id="is_active" name="is_active" value="on" data-toggle="toggle"></td>
</tr>
#endif
#endforeach
I also have an update function in controller
public function update(Request $request, $id)
{
$function=SystemFunction::where('id',$id)->first();
if($request->get('is_active')==='on'){
$is_active=1;
} else{
$is_active=0;
}
$function->update([
'is_active' => $is_active
]);
return redirect('admin/system-functions')->with('status','SUCCESSFUL');
}
and i'm calling this in my route
Route::group(array('prefix' => 'admin', 'namespace' => 'Admin', 'middleware' => 'staff'), function () {
Route::post('/system-functions', 'SystemFunctionController#update')->name('system-functions');
}
and my js looks like this in my view
#section('script')
<script type="text/javascript">
$(document).ajaxStop(function () {
$('.toggle_status').on('click', function (e) {
var is_checked = false
if ($(this).is(':checked')) {
is_checked = true;
}
$.ajax({
type: 'POST',
url: '{{ route('admin.system-functions') }}', // use proper route to system-functions here
async: true,
data: {
is_checked: is_checked,
id: {{ $function->id }}
},
success: function (result) {
alert('Toggle successfull'); // use proper alert message here
e.stopImmediatePropagation();
return false;
}
});
});
});
</script>
#endsection
console error
console error
html
<tr>
<td>{!! $function->id !!}</td>
<td>{!! $function->name !!}</td>
<td><input class="togglefunction" type="checkbox" #if($function->is_active) checked #endif id="is_active" name="is_active" value="on" data-toggle="toggle" data-fid="{{$function->id}}"></td>
</tr>
Route
Route::post('/system-functions', 'SystemFunctionController#update')->name('update-system-function');
In Model
public function toggleIsActive()
{
$this->is_active= !$this->is_active;
return $this;
}
then use like
public function update(Request $request)
{
$function=SystemFunction::where('id',$request->id)->first();
$function->toggleIsActive()->save();
return redirect('admin/system-functions')->with('status','successful');
}
javascript :
$('.togglefunction').on('click',function(){
//send value by ajax to server
$.ajax({
url:'{{route('update-system-function')}}',
type:'GET',
data:"{id:$(this).data('fid')}"
}).done(function(response) {
//success
}).fail(function(error){
//failure
})
});
You will have to do ajax call on each click on a checkbox to update database record.
Your js code will be like this:
$('#somecheckbox').on('click',function(){
//check the checkbox status
var is_checked = false
if($(this).is(':checked')){
is_checked = true;
}
//send value by ajax to server
$.ajax({
url:'url_here',
type:'GET',
data:"{is_checked:is_checked}"
}).done(function(response) {
//success
}).fail(function(error){
//failure
})
});
I Like javascript code of #DejavuGuy's Answers to imporove backend code I would like to suggest you to use something like this:
public function update($value,$id)
{
$function=SystemFunction::where('id',$id)->first();
$function->is_active = !$function->is_active;
$function->save();
echo 'Successfully!'
}
Good luck
$(document).ready(function() {
$("#is_active").click(function() {
var checkBoxe = $("#is_active");
checkBoxe.prop("checked", !checkBoxe.prop("checked"));
});
var checkedValue = $('#is_active').val();
var id = $('#id_input').val();
var xhr = new XMLHttpRequest();
xhr.open("GET", '{{url('system-functions')}}'+'/'+checkedValue+'/'+id, true);
xhr.setRequestHeader('Content-Type', '');
xhr.send();
xhr.onload = function() {
alert(this.responseText);
}
});
and your route here...
Route::get('/system-functions/{value}/{id}', 'SystemFunctionController#update');
your server method here...
public function update($value,$id)
{
$function=SystemFunction::where('id',$id)->first();
if($value==='checked'){
$is_active=1;
} else{
$is_active=0;
}
$function->update([
'is_active' => $is_active
]);
echo 'Successfully!'
}

Using Jquery/SetTimeout to Update Div - Update Not Working

What I am Trying to Do:
I am trying to use settimeout to loop/run after a function is called to automatically update/refresh a div.
What Isn't Working:
To be clear settimeout is working, but the div is not automatically refreshing/updating when I enter new test data into the db. In other words, If I refresh the page, I see the new test data, but not if I let the update function run.
Code:
function update(a) {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "core/engine.php",
data: "q=data&account="+a,
dataType: "html", //expect html to be returned
success: function(response){
if(response=="nologin") {
alert("Sorry, but either your account is not activated or your login is incorrect!");
} else {
console.log("Queried Database...");
var j = $.parseJSON(response);
$.each(j, function (k, v) {
$("#login-box").hide();
//$("#trades").html(' ');
localStorage.setItem("wings_lastsignal", v.candel);
var lastsignal = localStorage.getItem("wings_lastsignal");
console.log(v.candel);
if(lastsignal == v.candel) {
console.log("No New Signals");
localStorage.getItem("wings_currentsignals");
if(v.signal == 'Buy') {
console.log("Current Buy Sent...");
$("#trades").append('<span id="'+v.candel+'" class="tradesignal"><span class="signalarrowup"></span>'+v.time+'<span style="color:#2DC14E;"> '+v.signal+'</span>   <button class="tsym" id="sym_'+v.epoch+'" onClick="var a = this.innerHTML; tsclick(a);" value="'+v.symbol+'">'+v.symbol+'</button>  '+v.price+'  '+v.timeframe+'</span>');
} else {
console.log("Current Sell Sent...");
$("#trades").append('<span id="'+v.candel+'" class="tradesignal"><span class="signalarrowdown"></span>'+v.time+'<span style="color:#fb5350;"> '+v.signal+'</span>   <button class="tsym" id="sym_'+v.epoch+'">'+v.symbol+'</button>  '+v.price+'  '+v.timeframe+'</span>');
}
} else {
playChing();
console.log("New Signal");
if(v.signal == 'Buy') {
console.log("Buy Sent...");
$("#trades").append('<span id="'+v.candel+'" class="tradesignal"><span class="signalarrowup"></span>'+v.time+'<span style="color:#2DC14E;"> '+v.signal+'</span>   <button class="tsym" id="sym_'+v.epoch+'" onClick="var a = this.innerHTML; tsclick(a);" value="'+v.symbol+'">'+v.symbol+'</button>  '+v.price+'  '+v.timeframe+'</span>');
} else {
console.log("Sell Sent...");
$("#trades").append('<span id="'+v.candel+'" class="tradesignal"><span class="signalarrowdown"></span>'+v.time+'<span style="color:#fb5350;"> '+v.signal+'</span>   <button class="tsym" id="sym_'+v.epoch+'">'+v.symbol+'</button>  '+v.price+'  '+v.timeframe+'</span>');
}
}
});
}
//alert(response);
//console.log(response);
}
}).then(function() { // on completion, restart
var a = localStorage.getItem("wingsaccnum");
//setTimeout(update, 10000);
setTimeout(function(){ update(a) }, 20000); // function refers to itself
console.log("Timeout");
});
}
This function is called when I a button is pressed, using this Jquery snippet:
$( "#rbuttonon" ).click(function() {
var acc = localStorage.getItem("wingsaccnum");
//refresh_box();
update(acc);
console.log('Interval set');
});
Other Notes:
To be clear, I don't mind if there is a way to always make sure this div is updated every xx amount of time, without the need to press any buttons. I believe the problem is in my code's logic, but I would greatly appreciate some assistance!

preventDefault is not working

I am trying to send an ajax request to complete a task when a link is clicked. For some reason the e.preventDefault is not working and I still get sent to the page. Is there something I am missing?
It is simply supposed to go to the page set the check-box to checked (or unchecked) then redirect. But again it just goes to the page. Any help would be great!
here is the main.js
$(function() {
$('.ajax-task-complete').on({
click: function(e) {
e.stopPropagation();
e.preventDefault();
var href = $(this).attr('href');
$('<div></div>').load(href+' form', function() {
// Set Form
var form = $(this).children('form');
// Set Checkbox
var cb = form.find('input[type="checkbox"]');
// Taggle Checkbox
cb.prop('checked', !cb.prop('checked'));
// Form Action URL
var url = form.attr('action');
// Set Data
var data = form.serialize();
$.ajax({
url: url,
data: data,
method: 'post',
dataType: 'json',
cache: false,
success: function(obj) {
var tic = $('#task-complete-' + obj.id + ' .ajax-task-complete');
},
complete: function() {
console.log('complete');
},
error: function(err) {
console.log(err);
}
});
});
}
});
});
here is the requested button
<td id="task-complete-{{ entity.id }}">
{% if entity.completed %}
<a class="check ajax-task-complete" href="{{ path('task_edit_complete', { 'id': entity.id }) }}">✔</a>
{% else %}
<a class="uncheck ajax-task-complete" href="{{ path('task_edit_complete', { 'id': entity.id }) }}">✔</a>
{% endif %}
</td>
This is your problem:
Uncaught ReferenceError: $ is not defined?
Read HERE from SO how you load your jQuery-plugin the right way.
you might need to stop bubbling depending on where the click event is occurring. Try adding this and see what happens.
e.stopPropagation();
**"$"**
is missing before (function() {
javascript pageload event should be like
$(function(){
//code here
});
or
function will be called by themself
(function(){
//code here
)}();
or
(function($){
//code here
})(jQuery)
You can check the fiddle here
Your scope is wrong, you are missing the () after (function)(). The function is never called :
(function() {
$('.ajax-task-complete').on({
click: function(e) {
e.stopPropagation();
e.preventDefault();
var href = $(this).attr('href');
$('<div></div>').load(href+' form', function() {
// Set Form
var form = $(this).children('form');
// Set Checkbox
var cb = form.find('input[type="checkbox"]');
// Taggle Checkbox
cb.prop('checked', !cb.prop('checked'));
// Form Action URL
var url = form.attr('action');
// Set Data
var data = form.serialize();
$.ajax({
url: url,
data: data,
method: 'post',
dataType: 'json',
cache: false,
success: function(obj) {
var tic = $('#task-complete-' + obj.id + ' .ajax-task-complete');
},
complete: function() {
console.log('complete');
},
error: function(err) {
console.log(err);
}
});
});
}
});
})(); //Add () here
But is the scope really needed here?
Maybe you meant a ready handler, then it should be like this :
$(function); //Missing '$'
Try placing the preventDefault event at the end of the function as below
$('.ajax-task-complete').on({
click: function(e) {
//
//your code here then,
e.preventDefault();
e.stopPropragation();
});
I can't test if it works or not, as I'm on mobile.

checkbox - checked or unchecked with jQuery and MySQL

I am currently creating a system where it has to be possible to check/uncheck a checkbox. Everytime it changes status I need jQuery to make an AJAX call to a page, that updates the database.
How can I do this?
For example you can do it like this:
First you have to look if the checkbox is checked:
$("#yourSelector").live("click", function(){
var id = parseInt($(this).val(), 10);
if($(this).is(":checked")) {
// checkbox is checked -> do something
} else {
// checkbox is not checked -> do something different
}
});
You can load specific content via Ajax:
$.ajax({
type: "POST",
dataType: "xml",
url: "path/to/file.php",
data: "function=loadContent&id=" + id,
success: function(xml) {
// success function is called when data came back
// for example: get your content and display it on your site
}
});
Which bit are you stuck on? You should probably have something like this...
$('#myCheckbox').click(function() {
var checked = $(this).is(':checked');
$.ajax({
type: "POST",
url: myUrl,
data: { checked : checked },
success: function(data) {
alert('it worked');
},
error: function() {
alert('it broke');
},
complete: function() {
alert('it completed');
}
});
});
Detect if checkbox is checked:
if ( $('#id').is(':checked') ) { }
This can be executed in a function that is triggered by "onchange" event.
function checkCheckboxState() {
if ( $('#id').is(':checked') ) {
// execute AJAX request here
}
}
Something like this probably?
$('.checkbox').click(function (){
var val = $(this).is(':checked');
$.load('url_here',{status:val});
});
<input type="checkbox" name="foo" value="bar" class="checkIt"/>
<script type="text/javascript">
$('.checkIt').bind('click', function() {
if($(this).is(":checked")) {
// checkbox is checked
} else {
// checkbox is not checked
}
});
</script>
You can now have more than one checkbox.

Categories

Resources