In view_candidates form in my application, I have a button with text REQUEST CONTACT INFO. When I click on the button, the text will be changed automatically to FINISH.
Now what happens: When I refresh the page the button text automatically changes to REQUEST CONTACT INFO.
To overcome this, I gave a status column in my database.
What I want:
Once user click on the button, the status should change from 0 to 1.
With status, I want to display my button text like: if status=0 button should be REQUEST CONTACT INFO, else it should be FINISH.
Button code:
<td>
<button type="button" id="button" class="btn btn-info" onclick="getConfirmation(id);">
<b>REQUEST CONTACT INFO</b>
</button>
</td>
SCRIPT:
<script>
function getConfirmation(id)
{
var retVal = confirm("your request is confiremed ?");
if(retVal)
{
$('#button').text('Finish');
$.ajax({
url: "Candidate/user_view_candidates/change_status",
type: "post",
data: id,
success: function (response)
{
//location.reload();
alert('success');
}
});
}
}
</script>
Controller code:
public function change_status()
{
$id = $this->input->post('candidate_id');
$status = $this->db->query("select status from candidates_details where id = candidate_id")->row()->status;
if($status==0)
{
$status = 1;
}
else
{
$status = 0;
}
$data=array('status'=>$status);
$this->db->where('candidate_id',$id);
$this->db->update('candidates_details',$data);
}
Can someone help me? Thanks in advance.
Check this:
View
<input type="hidden" name="candidate_id" value="<?php echo $candidate_id; ?>"/>//your candidate_id
<button type="button" id="button" class="btn btn-info" >
<b><?php $status == 0? 'REQUEST CONTACT INFO':'FINISHED';?></b>//your status value
</button>
<script src="<?php echo base_url(); ?>assets/plugins/jquery.min.js"></script>
js
$('#button').click(function() {
var candidate_id = $('input[name="candidate_id"]').val();
var url = 'your_cntroller_name/change_status/';
$.ajax({
url: your_base_url + url,
type: 'POST',
data: {'$candidate_id': $candidate_id},
dataType: 'JSON',
success: function(data) {
$('#button').text('FINISHED');
}
});
});
Controller
public function change_status() {
$candidate_id = $this->input->post('candidate_id');
$this->your_model->update_status($candidate_id);
echo true;
exit;
}
Model
public function update_status($candidate_id) {
//your query toupdate status
}
complete step by step solution is
step -1
in your view
<td><button type="button" id="button" class="btn btn-info" onclick="getConfirmation(row id);"><b>REQUEST CONTACT INFO</b></button></td>
getConfirmation(id){
$.ajax({
url: "url_to_your_controller/change_status",
type: "post",
data: id,
success: function (response) {
location.reload();
}
});
}
step -2
in your controller
change_status(){
$id = $this->input->post('id');
$status = $this->db->query("Your query")->row()->status;
if($status==1){
$status = 0;
} else {
$status = 1;
}
$data=array('status'=>$status);
$this->db->where('id','id');
$this->db->update('table_name',$data);
}
from your question I understand that you are displaying your record in a grid/ table and for each record in a row you have a button when you click on button it change the status of the record.
so the solution is simple onclick change the status using ajax call and in DB add a field status against each record which will be 0 by default and after onclick it'll be updated to 1
on page load you've to implement in your view a check
e.g
<?if(status==0){?>
<td><button type="button"><b>Working</b></button></td>
<? } else { ?>
<td><button type="button"><b>Finished</b></button></td>
<? } ?>
Related
I have 1 button that changes its atributtes everytime I click on it, it have 3 options, 0, 1 and 2.
If the button is in 0 and I click it one time it will change to value 1 in its html structure, thats working fine, but it will send to DB the value 0, if the button is in 0 but I click it twice, it html structure changes to 2, but it sends value 1 to DB.
HTML:
<td class="dt-body-center">
<?php if($deposito["subido"] == 0): ?>
<button class="btn btn-danger btn-xs btnSubido" idSubido="<?=$deposito["id"]?>" estadoSubido="0">Down</button>
<?php elseif($deposito["subido"] == 1):?>
<button class="btn btn-success btn-xs btnSubido" idSubido="<?=$deposito["id"]?>" estadoSubido="1">Up</button>
<?php elseif($deposito["subido"] == 2):?>
<button class="btn btn-primary btn-xs btnSubido" idSubido="<?=$deposito["id"]?>" estadoSubido="2">Ofc</button>
<?php endif;?>
</td>
Javascript:
$(".tablas").on("click", ".btnSubido", function(){
var idSubido = $(this).attr("idSubido");
var estadoSubido = $(this).attr("estadoSubido");
$.ajax({
url:'ajax/subido.ajax.php',
method:'POST',
data:{
estadoSubido: estadoSubido,
idSubido: idSubido
}
});
if(estadoSubido == 0){
$(this).removeClass('btn-danger');
$(this).addClass('btn-success');
$(this).html('Up');
$(this).attr('estadoSubido',1);
}else if(estadoSubido == 1){
$(this).addClass('btn-primary');
$(this).removeClass('btn-success');
$(this).html('Ofc');
$(this).attr('estadoSubido',2);
}else if(estadoSubido == 2){
$(this).addClass('btn-danger');
$(this).removeClass('btn-primary');
$(this).html('Down');
$(this).attr('estadoSubido',0);
}
});
PHP:
require_once '../includes/conexion.php';
$tabla = "depositos";
$item1 = "subido";
$valor1 = $_POST["estadoSubido"];
$item2 = "id";
$valor2 = $_POST["idSubido"];
$sql=" UPDATE $tabla SET $item1 = $valor1 WHERE $item2 = $valor2 ";
$query = false;
if($db->query($sql)===TRUE){
$query = true;
}
Looks like maybe you want to move your ajax request to the bottom of the click handlers, in order to have the html element attribute (estadoSubido) change before you execute the request.
$(".tablas").on("click", ".btnSubido", function () {
var idSubido = $(this).attr("idSubido");
var estadoSubido = $(this).attr("estadoSubido");
// {if else block}
// Get the new value, which your click handler changes it to.
estadoSubido = $(this).attr("estadoSubido");
$.ajax({
url: "ajax/subido.ajax.php",
method: "POST",
data: {
estadoSubido: estadoSubido,
idSubido: idSubido,
},
});
});
I need a ajax call to post data to the database and fetch the data from database and update in live. I have the following codes
HTML Form
<div class="hover_bkgr_fricc">
<span class="helper"></span>
<div>
<div class="popupCloseButton">×</div>
<p>
<form>
<input type="hidden" name="check_num" value="123" />
<p>Please provide more details</p>
<input type="text" name="reason" />
<a id="submit">Mark Reviewed</a>
</form>
</p>
</div>
</div>
<b id="review_result"></b>
<a class="trigger_popup_fricc">
<button> Mark Reviewed</button>
</a>
Javascript Block
$(document).ready(function() {
$(".trigger_popup_fricc").click(function() {
$('.hover_bkgr_fricc').show();
});
$('.popupCloseButton').click(function() {
$('.hover_bkgr_fricc').hide();
});
$('#submit').click(function() {
var check_num = $('input[name=check_num]').val();
var reason = $('input[name=reason]').val();
var form_data =
'check_num=' + check_num +
'&reason=' + reason;
$.ajax({
url: "loweslinkprocess.php",
type: "POST",
data: form_data,
success: function(html) {
//if process.php returned 1/true (send mail success)
if (html == 1) {
//hide the form
$('.hover_bkgr_fricc').fadeOut('slow');
$('#review_result').html(data);
} else alert('Sorry, unexpected error. Please try again later.');
}
});
});
And the php block
$link = mysqli_connect($HOST, $USER, $PWD, $DB_NAME);
$check_num = $_POST['check_num'];
$reason = mysqli_real_escape_string($link, $_POST['reason']);
$insert = mysqli_query($link, "INSERT INTO `vloer_paylink_reason` (`id`, `check_number`, `reason`) VALUES (DEFAULT, '$check_num', '$reason')");
$update = mysqli_query($link, "UPDATE vloer_paylink SET reviewed = 1 WHERE check_number ='$check_num'");
$get_check_data = mysqli_query($link, "SELECT reviewed FROM vloer_paylink WHERE check_number = '$check_num'");
$check_data = mysqli_fetch_array($get_check_data);
if($check_data['reviewed']==1){
echo "Reviewed done";
}
else {
echo "Not Reviewed done";
}
Data is inserting and updating to the database but after that not returning to html update. Its returning false (Sorry, unexpected error. Please try again later.)
Add .error : function(e){ console.log(e)} to your ajax call, to return the error.
The function will be:
$.ajax({
url: "loweslinkprocess.php",
type: "POST",
data: form_data,
success: function(data) {
if(data == "Reviewed done"){
// code goes here
}
},
error : function(e) { console.log(e)} // this will print error
});
You are sending Reviewed done or Not Reviewed done in the php code as a response. Change the javascript code like below.
$.ajax({
url: "loweslinkprocess.php",
type: "POST",
data: form_data,
success: function(response) {
//if process.php returned 1/true (send mail success)
if (response === "Reviewed done") {
//hide the form
$(".hover_bkgr_fricc").fadeOut("slow");
$("#review_result").html(response);
} else alert("Sorry, unexpected error. Please try again later.");
},
error: function(error) {
console.log(e);
} // To catch any network errors
});
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 want to also change my status message when I click on them. This is the image where I want to apply
As shown in image, the active status need to change to inactive when I click on it. I can do it with edit page but now I want to change status when I click on active on page load. this is my code ctp file
<td class="center">
<?php if($listings['status']=="1") { ?>
<span class="label label-success">Active</span>
<?php } else if($listings['status']=="0") {?>
<span class="label label-error">Inactive</span>
<?php } ?>
</td>
this is controller code
if ((!empty($this->request->data['action'])) && (!empty($this->request->data['ids'])))
{
$action=$this->request->data['action'];
$ids=$this->request->data['ids'];
switch($action)
{
case "active":
$this->request->data['status']="1";
foreach($ids as $id)
{
$this->Listing->id = $id;
$this->Listing->save($this->request->data);
}
$this->Session->setFlash(__('Active Successfully'),'default',array('class' => 'alert alert-success'), 'alert');
$this->redirect(array('controller'=>'Listing','action' => 'index'));
break;
case "inactive":
$this->request->data['status']="0";
foreach($ids as $id)
{
$this->Listing->id = $id;
$this->Listing->save($this->request->data);
}
$this->Session->setFlash(__('InActive Successfully!'),'default',array('class' => 'alert alert-success'), 'alert');
$this->redirect(array('controller'=>'Listing','action' => 'index'));
break;
Please help me and tell how to do that with ajax or jquery.
Try this:
HTML: <button type="button" class="active" data-id="2">Active/button>
//Note that data-id ...It's just an attribute I created, and the value "2" I //believe will be dynamic in your case -Probably that college ID in the DB
JAVASCRIPT (Jquery required)
<script>
$(document).on('click', 'button[data-id]', function(event) {
event.preventDefault();
var collegeID = $(this).attr('data-id');
$.ajax({
url: 'changeStatus',
type: 'POST',
dataType: 'json',
data: {id: collegeID},
success: function(data){
if (data['status'] == "success") {
$('button[data-id]').removeClass('active').addClass('inactive');
/*Class active and inactive should be in your CSS with color according to their names*/
};
}
});
});
</script>
CONTROLLER:
public function changeStatus(){
$this->autoRender = false;
if ($this->request->is('ajax')) {
$data = $this->request->data;
/*The id that was passed thru data-id attribute is here: */
//$data['id'] Use it to update your DB
//After successful update
$response = array('status' => 'success');
return json_encode($response);
}
}
Then Last but not the least, is your route:
Router::connect('/changeStatus', array('controller' => 'yourcontroller', 'action' => 'changeStatus'));
Hope that help.
Good luck
You can actually do as simple as this:
$("body").on("click", "#status", function(e) {
e.preventDefault();
var stat = find("span#span_id").val(); // get the status current value
$.get('./db_file', function(data) {
if (data.stat != stat)
$("#span_id").removeClass("label label-error").addClass("label label-success");
}, "json");
});
Something like that would work.
I have a function that generates 10 random and unique numbers between 1-20.
function contain($prevItems, $number) {
for ($k=0; $k<sizeof($prevItems); $k++) {
if ($prevItems[$k] == $number)
return true;
}
return false;
}
$num[0] = rand(1,20);
$prevItems[0] = $num[0];
for ($i=1; $i<=10; $i++) {
$num[$i] = rand(1,10);
while (contain($prevItems, $num[$i])) {
$num[$i] = rand (1,20);
}
$prevItems[$i] = $num[$i];
}
sort($num);
I then have a button that fetches the first number from the array and echoes a text from database based on the number.
<form action="koe.php" method="POST">
<input id="myform" type="submit" class="btn btn-primary" name="submit" value="new question">
</form
if(isset($_POST['submit'])) {
if($result = $my->query("SELECT * FROM questions ORDER BY OID DESC LIMIT 1")) {
if($result = $my->query('SELECT * FROM questions WHERE OID="'.$prevItems[0].'"')) {
while($t = $result->fetch_object()) {
echo '<h2>'.$t->text.'</h2>';
}
}
}
}
My problem is this: I want the button to echo the next value from the previously. Like I want to echo prevItems[1] and then prevItems[2] without the page refresh because at the moment every time I press the button, the page refreshes and the function makes new 10 numbers so they're not unique anymore.
I've tried to stop page refresh with javascript
var frm = $('#myform');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
I figured it can't work like this though but I'm not sure how to fix it.
To clarify: My problem is to go through array on a button click without page refresh. Everytime a button is pressed, the next number from array would show up. array[0] -> array[1] -> array[2] -> array[3]
I would change your php page to expect a post variable "num"
if(isset($_POST['num'])) {
if($result = $my->query("SELECT * FROM questions ORDER BY OID DESC LIMIT 1")) {
if($result = $my->query('SELECT * FROM questions WHERE OID="'.$_POST['num'].'"')) {
while($t = $result->fetch_object()) {
echo '<h2>'.$t->text.'</h2>';
}
}
}
}
//you probably want to google "mysql prevent injection" right after you get this working
Then in your ajax call you can pass in the "num"
$(function(){
$("mybutton").on("click", function() {
$.ajax({
type: "POST",
url: "myURL",
data: { num:myNums[0] },
success: function (data) {
$("#output").innerHTML += data;
myNums.splice(0,1); //take out the first num
}
});
});
});