I am trying to get data from database without reloading. So I did this
Code In PasteBin
after doing that this is the ajax part for click
function ed_action(p_authority_id, ed_value) {
$.ajax({
method: "POST",
url: "inc/ed_action.php",
data: 'p_authority_id='+ encodeURIComponent(p_authority_id) + '&ed_value='+ encodeURIComponent(ed_value),
success: function(data) {
if(data){
$("#show").html(data);
}
}
});
}
this is the ed_action.php file
$func = new functions();
if($_SERVER["REQUEST_METHOD"] == "POST"){
$ed_value = $_POST['ed_value'];
$p_authority_id = $_POST['p_authority_id'];
$user_data = array(
'ed_action' => $ed_value
);
$where_cond = array(
'where' => array('p_authority_id' => $p_authority_id),
'cross_check' => 'and',
'return_type' => 'single'
);
$table_name = 'p_authrity_user';
$update = $func->update($table_name, $user_data, $where_cond);
$ed_action_data = $func->select($table_name, $where_cond);
}
I successfully retrive the data by click. But Now I want when I click on the enable button it will show the disable button without reloading and when click on disable, it should be show the enable button. so what should I do?
Please can you help me?
As I mentioned in comments: In your success function of the ajax request you can just toggle the visibilty of the two buttons.
function ed_action(p_authority_id, ed_value) {
$.ajax({
method: "POST",
url: "inc/ed_action.php",
data: 'p_authority_id='+ encodeURIComponent(p_authority_id) + '&ed_value='+ encodeURIComponent(ed_value),
success: function(data) {
if(data){
$("#show").html(data);
toggleButtons();
}
}
});
}
function toggleButtons(){
var enableBtn = $('button.ed_action.ed_action_enable'); // add class ed_action_enable to button so you can get it here
var disableBtn = $('button.ed_action.ed_action_disable'); // add class ed_action_disable to button so you can get it here
enableBtn.toggle(); // toggles visibility of element
disableBtn.toggle(); // toggles visibility of element
/* shorter code for this:
$('button.ed_action.ed_action_enable').toggle;
$('button.ed_action.ed_action_disable').toggle;
*/
}
For this to work you would need to
1: output both buttons into the html (disable btn hidden)
2: add one more class to the buttons so you can get them easily with jquery
Related
Sorry I am a beginner with jQuery and Javascript. I want to be able to get the results into my modal from any form on the page that has class ajax. My code is below but not working correctly. Currently it opens the post result in a new page and not in the modal. Can anyone shed any light on my code?
Many thanks
$(document).ready(function() {
$('.ajax').click(function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('name').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
console.log(value);
// AJAX request
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
// Add response in Modal body
$('.modal-body').html(response);
// Display Modal
$('#aaModal').modal('show');
}
});
});
});
This probably happens because your browser submits the form by default. It doesnt know youre doing AJAX stuff. To prevent this, use preventDefault().
In addition to that, jQuery has a built in function for serializing (1 and 2) form data.
$(document).ready(function() {
$('form.ajax').click(function(event) {
event.preventDefault(); // prevents opening the form action url
var $form = $(this),
url = $form.attr('action'),
type = $form.attr('method'),
data = $form.serialize();
// console.log(value); // value doesnt exist outside of your loop btw
// AJAX request
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
// Add response in Modal body
$('.modal-body').html(response);
// Display Modal
$('#aaModal').modal('show');
}
});
});
});
Also, its not quite clear if you bind the click event handler to a form or a button, I guess the first one. You should change the handler to the following:
$(document).ready(function() {
$('form.ajax').on('submit', function(event) {
My goal is to have several buttons and when you hover one them a div will show up with the information belonging to the button the user is hovering on.
Each button is created from my database and each button has its own value.
The value of the button its the value I'm using in my SQL query to show the correct data belonging to the button.
My problem is I'm using javascript and AJAX to get the button value off the button when the user hovers on it, which means when the information div pops up, the value I caught using AJAX is not updated until the page is refreshed.
I'm far from being an expert and I'm sure I have made it much more complexed than needed:
1) I print out the buttons from my database:
while($row = mysqli_fetch_array($result)) {
echo ' <input type="text" id="submitfakta" name="submitted-btn" value="'.$row['Name'].'">
2) I then use Javascript and AJAX to get hold of the button value on hover:
<script>
$('#submitfakta').live('mouseover mouseout', function(e) {
if (e.type == 'mouseover') {
var idAttr = $(this).attr('value');
//alert($(this).attr('id'));
$.ajax({
type: "POST",
url: 'abu.php',
data: {idAttr : idAttr },
success: function(data)
{
return data;
}
});
}
});
</script>
3) the information div pops up using simply css by setting display:none and when I hover on a button the div is set to display:block
4) In abu.php I tried using SESSION to get the value of the button back to my page and using for the query:
$_SESSION["abu"] = $_POST["idAttr"];
But this is a poor solution because the session does not update right as you hover, but first after you refresh the page.
first Use Class
while($row = mysqli_fetch_array($result)) {
echo ' <input type="text" class="submitfakta" name="submitted-btn" value="'.$row['Name'].'">
and Then
$('.submitfakta').on('mouseover', function() {
var idAttr = $(this).attr('value');
//alert($(this).attr('id'));
$.ajax({
type: "POST",
url: 'abu.php',
data: {idAttr : idAttr },
success: function(data)
{
return data;
}
});
});
Hope This Will Works
I'm writing simple search engine in Lumen framework.
I have a list of status for example. The user can get one of status from the list and after click search button then in the page, I need to load data with chosen status.
One of the element is datepicker. And this datepicker work great when I refresh the page or go to the page by GET method. But I have a problem when I go on the page by POST method from my click "SEARCH". There is some code from my view where I get status from the list and pass to my controller action:
<script type="text/javascript">
jQuery(document).ready(function ($) {
var clientId = null;
var status = null;
$("[name='deadline']").datepicker(); //there I have this error comunicat
$('#clients').on('change', function () {
clientId = $(this).val();
});
$('#statuses').on('change', function () {
status = $(this).val();
});
$('#searchForPremium').on('click', function () {
$.ajax({
type: 'POST',
url: '/admin/clients/premium',
data: {client_id: clientId, status: status},
success: function (data) {
$('body').empty().html(data);
$('#clients').val(clientId);
$('#statuses').val(status);
}
});
})
});
</script>
And there is controlelr action:
public function clientsPremium()
{
$premiumTexts = NULL;
$premiumClients = \App\Text::getPremiumClients();
$premiumTexts = \App\Text::getPremiumTexts();
$statuses = \App\Text::getStatus();
if (Request::isMethod('get')) {
$premiumTexts = $premiumTexts->orderBy(DB::raw('ISNULL(deadline), deadline'), 'ASC');
$premiumTexts = $premiumTexts->get();
return view('admin.clients-premium', ['statuses' => $statuses, 'clients' => $premiumClients, 'texts' => $premiumTexts]);
}
if (Request::isMethod('post')) {
$clientID = Request::get('client_id');
$statusName = Request::get('status');
if ($clientID != NULL) {
$premiumTexts = $premiumTexts->where('text.client_id', $clientID);
}
if ($statusName != NULL) {
$premiumTexts = $premiumTexts->where('text.status', $statusName);
}
$premiumTexts = $premiumTexts->orderBy(DB::raw('ISNULL(deadline), deadline'), 'ASC');
$premiumTexts = $premiumTexts->get();
return response()->json(view('admin.clients-premium', ['statuses' => $statuses, 'clients' => $premiumClients, 'texts' => $premiumTexts])->render());
}
}
Then I have error "Uncaught TypeError: $(...).datepicker is not a function...". I cant understand how it is work and why I got this message. It appear only when I click to search button.
It is $('body').empty().html(data); or my controller action:
return response()->json(view('admin.clients-premium', ['copywriters' => $copywriters, 'statuses' => $statuses, 'positioners' => $positioners, 'clients' => $premiumClients, 'texts' => $premiumTexts, 'allowedTemplates' => $allowedTemplates, 'section' => 'clients.premium'])->render());
I tried to use $.noConflict(); but there is no effect for me. Can anyone look at my code and try to help me what should I change? I think my return "response()->json(view..." reload all page and get my jquery-ui multiple time. But I can wrong. Can anyone help me?
Reinitialize it after you change content from ajax response.
$.ajax({
type: 'POST',
url: '/admin/clients/premium',
data: {client_id: clientId, status: status},
success: function (data) {
$('body').empty().html(data);
$("[name='deadline']").datepicker();
$('#clients').val(clientId);
$('#statuses').val(status);
}
});
After ajax success destroy the datepicker and reinitialize it as below:
$('body').empty().html(data);
$("[name='deadline']").datepicker("destroy");
$("[name='deadline']").datepicker();
you clear entire body so may be possible you include js css in body so please add and remove this div instead of entire body and if you add dynamic datepicker to any text box please use
$("[name='deadline']").datepicker(); on ajax response .
I want to ask why my codeigniter when add data become error 500 internal server when the save proccess. I dont know anything about this problem please help me all.
This is ajax code in view
function save()
{
$('#btnSave').text('menyimpan...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
if(save_method == 'add') {
url = "<?php echo site_url('edulibs/ajax_add')?>";
} else {
url = "<?php echo site_url('edulibs/ajax_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
$('#modal_form').modal('hide');
reload_table();
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('Simpan'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('menambahkan / update data error');
$('#btnSave').text('Simpan'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
And this is my controller
public function ajax_add()
{
$this->_validate();
$data = array(
'nama' => $this->input->post('nama'),
'nim' => $this->input->post('nim'),
'pembimbing1' => $this->input->post('pembimbing1'),
'pembimbing2' => $this->input->post('pembimbing2'),
'subyek' => $this->input->post('subyek'),
'judul' => $this->input->post('judul'),
'tanggal' => $this->input->post('tanggal'),
'tautan' => $this->input->post('tautan'),
);
$insert = $this->edulibs->save($data);
echo json_encode(array("status" => TRUE));
}
In order to use site_url() load url helper in your controller first.like this..
$this->load->helper('url');
OR load helper in application/config/autoload.php
And in success function of your ajax use JSON.parse() to parse your json response into object.Like this
success: function(response)
{
var data = JSON.parse(response);//OR var data = eval(response);
if(data.status) //if success close modal and reload ajax table
{
//code here
}
else
{
//code here
}
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.
}
},