So I have a page with several modes drawn based on a php variable (view, edit, add). I have some jquery adding info to td tags, but it would always post to the ajax target php file (and block some links/behavior). So to fix it, I had to add a check to only show on view mode.
However, now the edit mode for some reason also shows view for the same variable I am checking and I can't change the class that does it. What I'd like to do is execute my code by default, except when any link is pressed (so it will always follow the link). How can I do that?
<script>
$(document).ready(function(e){
var msg ='<?php echo $mode; ?>';
if(msg == 'view'){
//get all appointment numbers
count=0;
appointment_nums = [];
$('.mgrid_table > tbody > tr').each(function() {
appointment_nums.push($(this).find('td').eq(3).find('label').html());
});
appointment_nums = appointment_nums.filter(function(n){ return n != undefined });
appointments = appointment_nums.length;
function ajax() {
return $.ajax({
type:"post",
url: "../testrequest.php",
data : {appointment_nums:appointment_nums},
dataType:'json',
});
};
ajax().done(function(result){
$('table:nth-of-type(2) > tbody > tr > td:nth-of-type(2)').each(function() {
if($(this).children().length < 1){
if (result[count] == false){
$(this).append('Schedule Appointment ');
}else{
$(this).append('<span>Waiting For Doctor to Schedule</span>');
}
}
count = count + 1 ;
});
});
}
});
</script>
Related
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>
I have an Invoice, when I want to edit I want to able to delete some rows, either that row is found in DB or is added but click Add button. so I have to delete this row base on this conditions
Delete Row if is found in DB
Delete/Remove row if you added a new one(no need to check in DB, because you add new one)
Below is My invoice which show rows has data from DB and one which has not data (added new)
so I have done to delete the row which is found in DB, and I want to apply the second condition as per my below code.
$(document).ready(function () {
$("body").on("click",".remove",function(e){
var last=$('#tdy tr').length;
if(last==1){
alert("you can not remove last row, Otherwise Delete The Order Number!");
}
//here i tried the second condition
else if(iddata=null){
$(this).parent().parent().remove();
}
else{
if(!confirm("Do you really want to delete this?")) {
return false;
}
e.preventDefault();
// var id = $(this).attr('data-id');
var id = $(this).data("id");
var token = $("meta[name='csrf-token']").attr("content");
var url = e.target;
$.ajax(
{
url: "Loading/"+id, //or you can use url: "company/"+id,
type: 'DELETE',
data: {
"id": id,
"_token": token,
},
success: function (response){
if ( data['success'] )
{
alert(data['success']);
location.reload();
}
}
});
return false;
}
});
how can i resolve this some can help me
Please change this
else if(iddata = null)
For this
else if(iddata === null) // or else if(!iddata)
Here you need to use the equality operator == or even better the identity operator === instead of assignment operator =
About reload the page when remove an item you can use
location.reload();
return false;
At the end of the function this because regardless of the type of deletion both operations end up refreshing the page
i use javascript to reload my table after i input some data, my table goes like this
BEFORE INPUT
AFTER INPUT
u can see that after i input some data the table reload its id instead of its name like on the image, how can i make a way for javascript to reload its name instead of id, below are my code
JS
//reload table data
function reloadTableDataBasedOnVal(result){
var table = tableProject.dataTable(),
oSettings = table.fnSettings();
table.fnClearTable(this);
var contents = result.content;
for(var i = 0 ; i < contents.length ; i++){
var project = contents[i];
var item=[project.cv_id,project.cv_name,project.cv_client_id,project.cn_invoice_method,project.cn_project_rate,project.cn_note,btn];
table.oApi._fnAddData(oSettings, item);
}
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
table.fnDraw();
}
function reloadTableData(){
$.ajax({
url : 'get-all-project',
type : 'GET',
dataType : 'json',
success: function(result,status){
if(status == successStatus){
reloadTableDataBasedOnVal(result);
}
},
errror: function(result,status){
errorNotification("Unknown error, Please contact your administrator!");
}
});
}
VIEW
#foreach($projects as $project)
<tr class="odd gradeX">
<td>{{$project->cv_id}}</td>
<td>{{$project->cv_name}}</td>
<td>{{$project->client['cv_name']}}</td>
<td>{{$project->invoice['cv_method']}}</td>
<td>{{$project->cn_project_rate}}</td>
<td>{{$project->cn_note}}</td>
</tr>
#endforeach
in the view i can do something like this <td>{{$project->client['cv_name']}}</td> since it was a simple php but in javascript i did something similar its show an error, the main code in JS is this line var item=[project.cv_id,project.cv_name,project.cv_client_id,project.cn_invoice_method,project.cn_project_rate,project.cn_note,btn]; that code is the one make the output when the tables reloaded
I have a form questionnaire with 12 divisions. The first div is display block and the others are display none. The div's are then shown and hidden with a tab function on click. The last div is a review of the form which is loaded by an ajax call. The code below is working fine up to the point where I want to add a button so user can go back and answer the unanswered questions
this code is working fine **
$(document).ready(function () {
var tab_pool = ["Q1", "Q2", "Q3", "Q4", "Q5", "Q6", "Q7", "Q8", "Q9", "Q10", "Q11", "Q12"];
var visible = $(".tab:visible").attr('class').split(" ")[1];
var curr_ind = $.inArray(visible, tab_pool);
$('.next').click(function () {
$("#processing").show();
$.ajax({
type: "POST",
url: "process.php",
data: $('.data').serialize() + "&data=" + data,
success: function (data, status, xhr) {
if (xhr.getResponseHeader("DB_SUCCESS") == 1) {
$("#processing").hide();
} else {
$("#processing").hide();
alert("Save failed");
return false;
}
}
});
// There are conditions here such as if this then
// curr_ind = curr_ind + whatever to move to next relevant question
if (curr_ind < 11) {
$(".tab:visible").delay(750).hide(0);
$("#processing").delay(750).hide(0);
curr_ind = curr_ind + 1;
$("." + tab_pool[curr_ind]).delay(750).show(0);
$(".finished").delay(750).hide(0);
$(".back").delay(750).show(0);
}
// if the user has reached the end then below we show the review of questionaire
if (curr_ind === 11) {
$("#processing").delay(750).hide(0);
$(".finished").delay(750).show(0);
$.ajax({
type: "POST",
url: 'review.php',
data: "username=" + username,
success: function (data, status, xhr) {
if (xhr.getResponseHeader("DB_SUCCESS") == 1) {
$("#review").show();
$('#review').html(data);
} else {
alert("Review not available");
return false;
}
}
});
}
});
// after the first question a back button is display for
// user to go back to previous question
$('.back').click(function () {
if (curr_ind > 0) {
$(".tab:visible").hide();
// There ar conditions here so user is brought back to
// the right div and not one that was skipped from conditions above
$("." + tab_pool[curr_ind]).show();
document.getElementById(tab_pool[curr_ind]).checked=false;
$(".finished").hide();
$(".next").show();
}
if (curr_ind === 0) {
$(".back").hide();
}
});
end working code **
// **** what I want here is a button for unanswered questions that will bring user
// back to that specific unaswered question
// I tried assigning a class and a numeric value to those buttons but
// for some reason I get a new blank page???
// I tried a few variations of the code below
function answerQ (value) {
var returnTo = value;
curr_ind = curr_ind - returnTo;
$(".tab:visible").hide();
$("." + tab_pool[curr_ind]).show();
document.getElementById(tab_pool[curr_ind]).checked=false;
$(".finished").hide();
$(".back").hide();
$(".next").show();
}
});
** a sample of the button to go back to unanswered question
ANSWER
The easiest is probably to set a cookie.
Another option is to set localStorage or sessionStorage (if you can count on them having a modern browser).
Some reading on the topic:
http://net.tutsplus.com/tutorials/html-css-techniques/quick-tip-learning-about-html5-local-storage/
http://www.sitepoint.com/html5-web-storage/
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage
You need to remember how many times they have viewed the form. You didn't mention PHP but you have that as a tag so I'll assume that is what you are using. You could create a session variable for storing how many times the user has viewed the page/form. (this psuedo-code was written late at night and not tested but you should be able to get the jist of it)
if (!isset($_SESSION['viewCnt']))
$_SESSION['viewCnt'] = 1;
else { //not the first time viewing the page/form, so increment counter and setup ajax
$_SESSION['viewCnt'] = $_SESSION['viewCnt']+1;
echo'
<script>
$(function() {
//do your ajax call here to fill div6
});
</script>
';
}
echo'
<div id="1" style="display:'.($_SESSION["viewCnt"] == 1 ? 'block' : 'none').';"></div>
<div id="2" style="display:none;"></div>
<div id="3" style="display:none;"></div>
<div id="4" style="display:none;"></div>
<div id="5" style="display:none;"></div>
<div id="6" style="display:'.($_SESSION["viewCnt"] == 1 ? 'none' : 'block').';"></div>
';
If you don't want to use session variable then you can use cookies or HTML5 web storage: http://www.w3schools.com/html/html5_webstorage.asp
NOTE: the session method will start over with each new sign in to the application and the cookie method will start over depending on its expiration date or when the user clears their temporary internet files
I have a collapsible part of my jQuery Mobile page that are generated from PHP output from a MS Sql databas and content render as I like it to so that part is ok.
in each section I create a form with 3 buttons and they are supposed to have unique Id:s.
All forms are also created to have a unique id created in runtime.
actions.php (renders out my elements into mobilepage i a DIV)
$counter=0; reset counter for ID:s
while (odbc_fetch_row($rs)){
// data output from Db to make like 10 collapsible with different data
$html = "";
$html = "<div data-role='collapsible-set' data-mini='true'>";
$html.="<div data-role='collapsible' data-mini='true'>";
$html.="<h3><span style=float:left;><img src='../_pic/$image' alt='$imageText' /> ".substr($Time,0,16)." $Area</span><span style='float:right;' class='ui-btn-up-c ui-btn-corner-all' cnt> $data </span></h3>";
$html.="<p>ID: $ID $Id $Status<br />$Status $Description)</p>";
$html.="<form method='post' action=''>";
$html.="<button value='action1' id='action1$counter' data-mini='true' type='Submit'>Take Action1</button>";
$html.="<button value='action2' id='action2$counter' data-mini='true' type='Submit'>Take Action1</button>";
$html.="<button value='action3' id='action3$counter' data-mini='true' type='Submit'>Take Action1</button>";
$html.="<input type='hidden' id='id$counter' name='id' value='$dataName' />";
$html.="</form>";
$html.="</div>";
$html.="</div>";
echo utf8_encode($html);
$counter++; //upcount to make Id:s unique
} //end While
Then I have this function that listens for a button that submit:
$(':submit').live('click', function() {
var button = $(this).val();
if (button == 'action1') {
$.ajax({
url: '../_php/Functions.php',
data: 'button=' + $(this).val()+'&id='+$('#id').val(),
async: true,
beforeSend: function() {
$.mobile.showPageLoadingMsg(true);
},
complete: function() {
$.mobile.hidePageLoadingMsg();
},
error: function (request,error) {
alert('error');
}
});
}
return false;
});
I cant seem to get another id than the first one since i need to make all ID:s unique in my forms and all I do now is to check: &id='+$('#id').val(). what I would like to have done is to link the button pressed-id number to my hidden field id-number so i get the right data out from it. As of now I only get the first form:s id evaluated...
If someone could point me in the right direction how to make that happen i´d be greatful.
functions.php (a switch statement is pre-testing for submit:ed action
function actions1(){
try {
if(isset($_GET['id'])){
do stuff with 'id'
}else{
do other stuff with 'id'
}
} catch(Exception $e) {
show error
}
}
If some part is unclear or if you feel I missed posting somepart - let me know. /thanks
Within event handlers this referes to the element
$(':submit').live('click', function(){
var id= this.id;
var button = $(this).val();
/* traverse within form to set hidden input, no need to worry about using ID's for them*/
$(this).closest('form').find('input[name=id]').val(id);
/* then in ajax */
data: 'button=' +button+'&id='+id,
})
Not full code....I left some of your code out for simplicity
You can use jQuery .attr() function to get an id or any other attribute value of an element.
$(':submit').live('click', function() {
var button = $(this).val();
var id = $(this).attr("id");
if (button == 'action1') {
$.ajax({
url: '../_php/Functions.php',
data: 'button=' + $(this).val()+'&id='+ id,
async: true,
beforeSend: function() {
$.mobile.showPageLoadingMsg(true);
},
complete: function() {
$.mobile.hidePageLoadingMsg();
},
error: function (request,error) {
alert('error');
}
});
}
return false;
});
The solution was to go by attributes name of my hidden input.
var id = $(this).closest("form").find(':hidden').val();