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.
Related
Student.php -here i am getting list of students from a specific Institution in a tag
<?php
if(isset($_POST['c_id'])) { //input field value which contain Institution name
$val=$_POST['c_id'];
$sql="select RegistrationId from `students` where `Institution`='$val' ";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)){
$number=$row['RegistrationId'];
?>
<a href='<?php echo "index.php?StudentID=$number"; ?>' target="index" id="link">
//getting student id in the dynamic link
<?php echo "$number";
echo "<br/>";
}}
?>
<div id="index" name="index"> </div>
<div id="Documents"> </div>
<script>
$(document).on('change', 'a#link', function()
{
$.ajax({
url: 'Documents.php',
type: 'get',
success: function(html)
{
$('div#Documents').append(html);
}
});
});
</script>
In index.php - I am Getting students details based on $_GET['StudentID'] ('a' tag value)
<?php
$link=$_GET['StudentID'];
$sql = "select StudentName,Course,Age,Address from `students` where `RegistrationId`="."'".$link."'";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
echo $row['StudentName']."<br/>";
echo $row['Course']."<br/>";
echo $row['Age']."<br/>";
echo $row['Address']."<br/>";
}
?>
In Documents.php -I am getting documents related to the speific student selected in 'a' tag
$link=$_GET['StudentID'];
$qry = "select Image,Marksheet from `documents` where `RegistrationId`='$link'";
$result = mysql_query($qry) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$image = $row["Image"];
$image1 = $row["Marksheet"];
echo '<embed src='. $image.'>';
echo ' <object data='. $image1.'width="750" height="600">';
echo ' </object>';
}
On click of student id i am trying to get result from index.php to div()
and result from Documents.php to div()
(i.e)two target for one click in tag
My code only take me to the index.php file result in a new Window
Please Help me to solve this problem
(sorry if my question seems silly i am new to php)
Update:
$(document).on('click', 'a#link', function(e) {
e.preventDefault();
$.ajax({
url:"details.php",
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#index").html(resp);
alert(resp);
}
});
});
$(document).on('click', 'a#link', function(e) {
e.preventDefault();
$.ajax({
url:"index.php",
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#Documents").html(resp);
alert(resp);
}
});
});
From your question, it seems that you want to load the two results, one from index.php and one from Documents.php in two separate divs on the same page when the link is clicked.
But you're using a change event on the link, not a click event. The change event is not fired when the link is clicked, so JavaScript does not get executed and the page loads to the URL specified in the href attribute of the link. So first you need to change $(document).on('change') to $(document).on('click').
Furthermore, since you want two results to load - one from index.php and one from Documents.php, you'll need to create two ajax requests, one to index.php and the other for Documents.php. In the success function of each of the ajax requests, you can get the response and put it in the corresponding divs.
In addition to this, you'll also need to prevent the page from loading to the new page specified in href attribute when the link is clicked, otherwise the ajax requests fired on clicking the link will get lost in the page load. Thus, you need to add a e.preventDefault(); to your onclick event handler like this:
$(document).on('click', 'a#link', function(e) {
// Stop new page from loading
e.preventDefault();
// Two ajax requests for index.php and Documents.php
});
Update: You don't need to add two click handlers for each ajax request. Inside one click handler, you can put both the ajax requests.
Also your event handlers won't register if you're adding them before jQuery, or if you're adding them before the DOM has loaded. So move your code to bottom of the HTML page, just before the closing </body> tag.
$(document).on('click', 'a#link', function(e) {
e.preventDefault();
$.ajax({
url:"details.php",
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#index").html(resp);
alert(resp);
}
});
$.ajax({
url:"index.php",
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#Documents").html(resp);
alert(resp);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Link
You can change your <a> tag like below :
..
Then , in your jquery code do below changes :
$(document).on('click', 'a.link', function(e) {
var StudentID = $(this).attr("data-id") //get id
console.log(StudentID)
e.preventDefault();
$.ajax({
url: "details.php",
data: {
StudentID: StudentID
}, //pass same to ajax
type: 'POST',
success: function(response) {
//do something
call_next_page(StudentID);//next ajax call
}
});
});
function call_next_page(StudentID) {
$.ajax({
url: "index.php",
data: {
StudentID: StudentID
}, //pass same to ajax
type: 'POST',
success: function(response) {
//do something
}
});
}
And then at your backend page use $_POST['StudentID'] to get value of student id instead of $_GET['StudentID'];
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>
<? } ?>
i have made function where i can add a row after confirming. the problem is, after submit button, the tables dont reload and show error function alert.actually data success saved and i have to refresh the page so that the table can reload. here is my ajax jquery code:
function reloadPage()
{
window.location.reload()
}
function save()
{
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
if(save_method == 'add') {
url = "<?php echo site_url('activity/save')?>";
} else {
url = "<?php echo site_url('activity/update_activity')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form-input').serialize(),
dataType: "JSON",
success: function(data)
{
$('#myModal').modal('hide');
reloadPage();
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
<button id="btnSave" onclick="save()" class="btn green">
"fa fa-save"> save</button>
my controller:
public function save() {
$actype = $this->input->post('actype');
$activity_name = $this->input->post('activity_name');
$project = $this->input->post('project');
$portion = $this->input->post('portion');
$activity = $this->input->post('actid');
$data = array(
'activity_type_id'=>$actype,
'activity_name' =>$activity_name,
'project_id' =>$project,
'portion' =>$portion,
'activity_id' => $activity
);
$this->activity->insertactivity($data);
redirect("activity/input");
}
after i've clicked button save,alert('Error adding / update data'),but actually after reload page data has saved.
where is code error in my ajax code?
Force a reload from the server.
window.location.reload(true);
When you don't specify true the reload may be from the browser cache if available.
Also, in the controller, redirect("activity/input"); is not the appropriate response to an AJAX request. Try something like this instead.
$this->activity->insertactivity($data);
echo json_encode(array('result' => TRUE));
Your controller code could also be much more concise. Consider this
public function save()
{
$data = array(
'activity_type_id' => $this->input->post('actype'),
'activity_name' => $this->input->post('activity_name'),
'project_id' => $this->input->post('project'),
'portion' => $this->input->post('portion'),
'activity_id' => $this->input->post('actid')
);
//Assuming insertactivity returns TRUE if the insert works and FALSE if not
$results['result'] = $this->activity->insertactivity($data);
echo json_encode($results);
}
You can check the "result" in success function
success: function(data)
{
if(data.result === true)
{
$('#myModal').modal('hide');
reloadPage();
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
} else {
//do something to the DOM to tell about the problem
//which probably means you should add that to your controller's response.
}
},
<script type="text/javascript">
$(document).ready(function () {
$(".Categories").click(function () {
var catId = $(this).attr('id');
catId = String(catId);
jQuery.ajax({
url: "index.php",
data: { catId },
type: "POST",
success: function (data) {
$("#categoryField").html(data);
}
});
});
});
</script>
I need to pass my clicked button id to the same index.php page, without page refreshing and work with that id value.My code is wrong, because page is rendered second time.
Here is my php code:
<?php
$category=$user_home->runQuery("SELECT DISTINCT category FROM products");
$category->execute();
$categoryArray=$category->fetchAll(PDO::FETCH_ASSOC);
foreach($categoryArray as $listID){
?>
<input type="button" id="<?php echo $listID['category']?>" class="Categories" value="<?php echo $listID["category"]?>"/><br>
<?
}
?>
Call preventDefault method inside the button click event handler to prevent default button behaviour ("page is rendered second time"):
...
$(".Categories").click(function (e) {
e.preventDefault();
...
There is a syntax error in your code
$(document).ready(function () {
$(".Categories").click(function () {
var catId = $(this).attr('id');
catId = String(catId);
jQuery.ajax({
url: "index.php",
data: { catId: catId },
type: "POST",
success: function (data) {
$("#categoryField").html(data);
}
});
});
});
You have to pass data in valid literal object format. {"property_name": "property_value"}.
Change: data: { catId } to data: { "catId": catId }
For server side:
<?
if (isset($_POST['catId'])) {
/* YOUR CODE FOR CATEGORY */
$catId = intval($_POST['catId']);
echo 'SUCCESS';
exit(0);
}
// YOU OTHER PHP CODE
?>
I think I need to post my variable to another page and then return it.I dont know how to do it in same page.This variant with exit(0) is bad because all variables inside if statement after exit(0) will be deleted.
<?
if (isset($_POST['catId'])) {
/* YOUR CODE FOR CATEGORY */
$catId = intval($_POST['catId']);
echo 'SUCCESS';
exit(0);
}
// YOU OTHER PHP CODE
?>
I am trying to submit a form. In the form, I have a field calles sitename. If the user enters a sitename which is already in the database, it will show the message "That name is already in use" and give some suggestions. Up to this point, it works. But what I want, is to hide the submit button until the user enters a valid value to that field.
Here is my code:
form.php:
<script type="text/javascript">
$(document).ready(function(){
$("#sitename").keyup(function() {
var sitename = $('#sitename').val();
if(sitename=="")
{
$("#disp").html("");
}
else
{
$.ajax({
type: "POST",
url: "check_name.php",
data: "sitename="+ sitename ,
success: function(html){
$("#disp").html(html);
}
});
return false;
}
});
});
</script>
<div class="form-group col-sm-3 col-xs-12">
<button class="btn btn-1 btn-fill" type="submit" id="btn-signup" name="btn-signup">Submit</button>
</div>
check_name.php:
include('dbconnect.php');
if(isset($_POST['sitename']))
{
$sitename=mysql_real_escape_string($_POST['sitename']);
$query=mysql_query("select * from template_users where sitename='$sitename'");
$row=mysql_num_rows($query);
if($row==0)
{
/*echo "<span style='color:white;'>Available</span>";*/
}
else
{
$msg = $sitename.rand ( 1 , 10000 );
$msg1 = $sitename.rand ( 1 , 100 );
echo "<span style='color:antiquewhite;' ><b>Already exist please Use different Site Name such as<br/> $msg<br/>$msg1<br/><b/></span>";
}
}
Try this code,
<script type="text/javascript">
$(document).ready(function(){
$("#sitename").keyup(function() {
var sitename = $('#sitename').val();
if(sitename=="")
{
$("#disp").html("");
}
else
{
$.ajax({
type: "POST",
url: "check_name.php",
data: "sitename="+ sitename ,
success: function(html){
if(html != 'success')
{
$("#disp").html(html);
$("#btn-signup").hide();
}
else
{
$("#btn-signup").show();
}
},
});
return false;
}
});
});
</script>
<div class="form-group col-sm-3 col-xs-12">
<button class="btn btn-1 btn-fill" type="submit" id="btn-signup" name="btn-signup" style="display:none;">Submit</button>
</div>
And in your check_name.php
<?php
include('dbconnect.php');
if(isset($_POST['sitename']))
{
$sitename=mysql_real_escape_string($_POST['sitename']);
$query=mysql_query("select * from template_users where sitename='$sitename'");
$row=mysql_num_rows($query);
if($row==0)
{
echo "success";
}
else
{
$msg = $sitename.rand ( 1 , 10000 );
$msg1 = $sitename.rand ( 1 , 100 );
echo "<span style='color:antiquewhite;' ><b>Already exist please Use different Site Name such as<br/> $msg<br/>$msg1<br/><b/></span>";
}
die;
}
?>
You will need to keep track on the outcome of your PHP script.
Change your code to:
PHP
<?php
include('dbconnect.php');
if(isset($_POST['sitename']))
{
$sitename=mysql_real_escape_string($_POST['sitename']);
$query=mysql_query("select * from template_users where sitename='$sitename'");
$row=mysql_num_rows($query);
if($row==0)
{
echo json_encode([ "status" => 1, "html" => "<span style='color:white;'>Available</span>" ]);
}
else
{
$msg = $sitename.rand ( 1 , 10000 );
$msg1 = $sitename.rand ( 1 , 100 );
echo json_encode([ "status" => 0, "html" => "<span style='color:antiquewhite;' ><b>Already exist please Use different Site Name such as<br/> $msg<br/>$msg1<br/><b/></span>" ]);
}
}
?>
HTML
<script type="text/javascript">
$(document).ready(function () {
$("#btn-signup").hide();
$("#sitename").keyup(function () {
$("#btn-signup").hide();
var sitename = $('#sitename').val();
if (sitename == "")
{
$("#disp").html("");
}
else
{
$.ajax({
type: "POST",
url: "check_name.php",
data: "sitename=" + sitename,
dataType: "json",
success: function (result) {
if (result.status == 1) {
$("#btn-signup").show();
}
$("#disp").html(result.html);
}
});
return false;
}
});
});
</script>
<div class="form-group col-sm-3 col-xs-12">
<button class="btn btn-1 btn-fill" type="submit" id="btn-signup" name="btn-signup">Submit</button>
</div>
That is, hide the button on start, if a user enters something, hide the button and wait till the text is validated. If it is valid, show it. If the user changes the text, then the button will be hidden again.
Please note:
1) mysql_* functions are deprecated since version 5.5 and have been removed in version 7. This on its own is enough indication that you need to move on and use something more secure and actively supported.
2) mysql_real_escape_string and mysqli_real_escape_string are not safe since they don't reliably consider server encoding. If you want to be safe, use real prepared statements (i.e. prepared statements which are prepared on the MySQL server).
I would suggest you to use json to return the data like this:
{
"status": "success",
"html" : "<span style='color:antiquewhite;' ><b>Already exist please Use different Site Name such as<br/> $msg<br/>$msg1<br/><b/></span>"
}
and here's the javascript code:
$(document).ready(function()
{
/** Hide the button first */
$('button').hide();
$('#sitename').on('input', function()
{
var sitename = $('#sitename').val();
if(sitename == '')
{
$("#disp").html("");
}
else
{
$.ajax(
{
type : "POST",
dataType: "json"
url : "check_name.php",
data : "sitename=" + sitename ,
success : function(data)
{
/** When the data is invalid */
if(data.status === 'error')
{
$('button').hide();
$("#disp").html(data.html);
}
else
{
$('button').show();
/** Hide the html when the data is valid */
$("#disp").html('');
}
},
});
}
})
});
And your php code:
<?php
include('dbconnect.php');
header('Content-Type: application/json; charset=utf-8');
if(isset($_POST['sitename']))
{
$sitename = mysql_real_escape_string($_POST['sitename']);
$query = mysql_query("select * from template_users where sitename='$sitename'");
$row = mysql_num_rows($query);
if($row == 0)
{
echo json_encode(['status' => 'success',
'html' => "<span style='color:white;'>Available</span>"]);
}
else
{
$msg = $sitename.rand ( 1 , 10000 );
$msg1 = $sitename.rand ( 1 , 100 );
echo json_encode(['status' => 'error',
'html' => "<span style='color:antiquewhite;' ><b>Already exist please Use different Site Name such as<br/> $msg<br/>$msg1<br/><b/></span>"]);
}
}
?>
$.ajax({
type: "POST",
url: "check_name.php",
data: "sitename="+ sitename ,
success: function(html){
if(html !== "") {
$("#btn-signu").attr("disabled", true);
}
else {
$("#btn-signu").removeAttr("disabled");
}
$("#disp").html(html);
}
});
Check the html param in success callback function.
In form.php change Javascript to:
<script type="text/javascript">
$(document).ready(function(){
//get the button by its ID
var $button = $('#btn-signup');
$("#sitename").keyup(function() {
//hide the button always
$button.hide();
var sitename = $('#sitename').val();
if(sitename=="")
{
$("#disp").html("");
}
else
{
$.ajax({
type: "POST",
url: "check_name.php",
data: "sitename="+ sitename ,
success: function(html){
$("#disp").html(html);
if(!html.length){
//show the submit button if no error html
$button.show();
}
}
});
return false;
}
});
});
</script>
The Button should be initial hidden. If the field can be prefilled, you need to check if the value is not empty before hiding the button.
<div class="form-group col-sm-3 col-xs-12">
<button class="btn btn-1 btn-fill" type="submit" id="btn-signup" name="btn-signup" style="display:none">Submit</button>
</div>