Delete Field in Datatable with ajax in Codeiginiter without refreshing page - javascript

I want to delete some field in datatable using 'a' tag as a button. If that button is pressed, it will delete field in my database using ajax without refreshing page but if i click the button, it doesn't do anything. I am weak in JS or jQuery, I hope you guys will help me, thanks.
This is my JS
$('#delete-agenda').click(function(e) {
e.preventDefault();
var data = {};
data['id_itenerary'] = $(this).attr('value');
$.ajax({
url: 'http://localhost/pandansari/admin/single_trip/delete_agenda',
type: 'post',
data: data
});
});
This is my 'a' tag
<a id="delete-agenda" class="btn btn-sm btn-danger" value="<?php echo $agenda['id_itenerary'] ?>">Delete</a>
This is my controller function
public function delete_agenda() {
$id_itenerary = $this->input->post('id_itenerary');
$this->agenda_model->delete_agenda($id_itenerary);
}
This is my model function
public function delete_agenda($id_itenerary) {
$this->db->where('id_itenerary', $id_itenerary);
$this->db->delete('tb_itenerary');
}

Try this
HTML:
<a id="delete-agenda" href="#" class="btn btn-sm btn-danger" data-id="<?php echo $agenda['id_itenerary'] ?>">Delete</a>
JS:
$(document).ready(function() {
$('#delete-agenda').click(function(e){
e.preventDefault();
var id = $(this).attr('data-id');
$.ajax({
url: 'http://localhost/pandansari/admin/single_trip/delete_agenda',
type: 'post',
data: { 'id_itenerary' : id }
});
});
});
You will still have to remove the datatable entry from the table; otherwise the change will only be apparent on refresh/reload.

$('#delete-agenda').on('submit',function(e){
e.preventDefault();
//write your remaining code here
});

Related

Update view without page refresh in Ajax

I have the following code which runs when a button is clicked.
$.ajax({
type: "POST",
url: base_url+"/controller/method",
data: {val: value},
success: function(data){
data = jQuery.parseJSON(data);
if(data.status === true){
show_notify_message("Success",data.msg,'success');
} else {
show_notify_message("Error",data.msg,'error');
}
}
});
HTML Code:
<button class='btn btn-xs alert-success' onclick='method(1)'><font color='black'>Take</font></button>
Once the changes are made the entire page refreshes and the updated values are seen in the view.
How can I perform the same action without the entire page refreshing?
try it this way
HTML code
<button class='btn btn-xs alert-success' data-method='1'><font color='black'>Take</font></button>
JQuery script
$(document).ready(function(){
$("[data-method]").click(function(event){
event.preventDefault();
//value from the button
value=$(this).data("method");
// ajax call
});
});
if you use a <button> element, set it's type to "button" like this:
<button type="button">Click Me</button>
for some reason the default type is "submit"

changing the class of clicked button on ajax function success

i have a several html buttons (not within a form).
When clicked they call a JavaScript function that after conformation, runs an ajax call.
This part all works OK, but i would then like to change the class of whichever button was clicked on success of the ajax call.
i have tried various methods seen on stackOverflow, but none of them seem to work...
can i please ask what am i doing wrong?
here is the simplified HTML (buttons)
<button class="btn btn-primary" onclick="primaryImage(4107,19372,'/abbie1.jpg'); return false;">
set as profile image
</button>
<button class="btn btn-primary" onclick="primaryImage(4107,19373,'/abbie2.jpg'); return false;">
set as profile image
</button>
<button class="btn btn-success" onclick="primaryImage(4107,19374,'/abbie3.jpg'); return false;" disabled="disabled">
profile image
</button>
Please note: the last button is already the active/success button, and i would also like to remove the class on success too (as only one should be active), but that is maybe my next stage....
here is the javaScript, (i have left in some of the methods i have tried, but commented them out)
function primaryImage(eid,pid)
{
if (confirm("Are you sure you wish to use this as your profile image?"))
{
$.ajax({
type: "POST",
async: false,
cache: false,
dataType: "json",
url: "ajax_photo.php",
data: "action=primary&eid="+eid+"&pid="+pid,
//context: this,
success: function(data){
if(data.result=='success')
{
alert('The image is now set as the profile image');
//$('button').click(function(){
// $(this).addClass('btn-success');
//});
//$('button').on(data.result=='success', function(e) {
// $(this).toggleClass("btn btn-success"); //you can list several class names
// e.preventDefault();
//});
//$(this).removeClass('btn-primary').addClass('btn-success');
}
else
{
alert('An error occurred when trying to set the image: ' + data.result);
}
}
});
}
}
I would be very grateful for any advice of what i am doing wrong
(as you can see, i am not too good with JS (yet))
Thanks!
Ford
As noted in your commented out code, you are binding the click event after click event has already been fired.
I would suggest you to pass a reference of the button that was clicked in the primaryImage() function itself as such:
<!-- In your HTML -->
<button class="btn btn-success" onclick="primaryImage(this, 4107,19374,'/abbie3.jpg'); return false;" disabled="disabled">
profile image
</button>
function primaryImage(button, eid,pid){
/** ... */
Then using that referenced button, you can add or remove CSS classes to the element, as well as the siblings of the element (using jQuery's siblings() method).
//your ajax call
success: function(data){
if(data.result=='success') //make sure this really is success
{
alert('The image is now set as the profile image');
$(button).removeClass('btn-primary').addClass('btn-success');
$(button).siblings('button').removeClass('btn-success').addClass('btn-primary');
}
}
As you don't use the jQuery .click() event, I think you need to pass the button in your function args.
So your button will look like
<button class="btn btn-primary" onclick="primaryImage(this, 4107,19373,'/abbie2.jpg'); return false;">
set as profile image
</button>
Then your function will be like
function primaryImage(el, eid,pid)
{
if (confirm("Are you sure you wish to use this as your profile image?"))
{
$.ajax({
type: "POST",
async: false,
cache: false,
dataType: "json",
url: "http://anzvirtuel.org",
data: "action=primary&eid="+eid+"&pid="+pid,
//context: this,
success: function(data){
if(data.result=='success')
{
$(el).addClass('btn-success');
alert('The image is now set as the profile image');
// keep doing whatever you want...
}
else
{
alert('An error occurred when trying to set the image: ' + data.result);
}
}
});
}
}
As I have not fully understood your commented JS I'll let you put the code you want, just remember that your button will be accessible in jQuery with $(el).
Hope it may helps you
You should pass the clicked element to the primaryImage() function, and use it on success to do whatever you like.
<button class="btn btn-primary" onclick="primaryImage(this, 4107,19372,'/abbie1.jpg'); return false;">set as profile image</button>
And in your JS
function primaryImage(element, eid,pid)
{
[...]
success: function(data){
if(data.result=='success')
{
$(element).addClass('btn-success');
}
else
{
alert('An error occurred when trying to set the image: ' + data.result);
}
}
[...]
}
You could use data-* attributes instead of onclick (MDN Documentation) and then access those throught jQuery, so your code is more clean and HTML / JS are separated.
Try this code, I've created three data attributes (data-eid, data-pid and data-image) for your params and also replaced your JS to make the whole stuff work with those data attributes. Those attributes can be accessed with following jQuery code - var eid = $(this).attr('data-eid'); as an example
This line of code removes the btn-primary class from the clicked button, adds a btn-success class to it and disables it, so it can't be toggled again.
pushedBtn.removeClass("btn-primary").addClass("btn-success").prop("disabled", true);
HTML
<button class="btn btn-primary" data-eid="4107" data-pid="19372" data-image="/abbie1.jpg">
profile image
</button>
<button class="btn btn-primary" data-eid="4107" data-pid="19373" data-image="/abbie2.jpg">
profile image
</button>
<button class="btn btn-primary" data-eid="4107" data-pid="19374" data-image="/abbie3.jpg">
profile image
</button>
JS
$(".btn").click(function (e) {
if (confirm("Are you sure you wish to use this as your profile image?")) {
var eid = $(this).attr('data-eid'); //like 4107
var pid = $(this).attr('data-pid'); //like 19372
var image = $(this).attr('data-image'); //like /abbie1.jpg
var pushedBtn = $(this);
$.ajax({
type: "POST",
async: false,
cache: false,
dataType: "json",
url: "ajax_photo.php",
data: "action=primary&eid=" + eid + "&pid=" + pid,
//context: this,
success: function (data) {
if (data.result == 'success') {
alert('The image is now set as the profile image');
pushedBtn.removeClass("btn-primary").addClass("btn-success").prop("disabled", true);
} else {
alert('An error occurred when trying to set the image: ' + data.result);
}
}
});
}
});

CKEditor - Using GetData()

I am struggling with implementing the following:
I have the a button which creates the CKE instance (outside the form):
<button type="submit" class="btn btn-default btn-sm" onclick="javascript: var editor81 = CKEDITOR.replace('divtext81')" value="Edit">Edit</button>
I then have a save button (outside the form):
<button type="submit" class="btn btn-default btn-sm" id="save81" value="Save">Save</button>
I then use the following javascript to post to a mySQL database:
$(document).ready(function (argument) {
$('.btn').click(function () {
id = $(this).attr('id').replace('save','');
$edit = CKEDITOR.instances.editor81.getData();
$cid = $('#cid' + id).val();
$action = $('#action' + id).val();
$eid = $('#eid' + id).val();
$.ajax({
url: 'include/editupdate.php',
type: 'post',
data: {
data: $edit,
cid: $cid,
eid: $eid,
action: $action
},
datatype: 'html',
success: function (rsp) {
alert(rsp);
}
});
});
});
The information posts fine to the database except it does not pick up any data from the editor instance, so that field is always blank. All of the other fields are OK. The suffix 81 is the record ID.
I also would like to know how to close the editor instance after posting to the database.
Many thanks

Yii2: call javascript function with a button

I want to call a javascript function from a button in php
this is the php code:
//the view
<?php
$form = yii\widgets\ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]);
?>
<?=
$form->field($msubs, 'id_subespecifica', ['options' => ['class' => 'col-md-12']])
->widget(Select2::classname(),[
'data' => ArrayHelper::map($vectorConsul,'sesp', 'sesp'),
'options' => ['id' => 'prueba'],
])
->label(false);
?>
<button class="btn btn-primary" onclick="myFunction()">Add New</button>
<?php
yii\widgets\ActiveForm::end();
?>
And this is the Javascript code:
//Javascript
function myFunction() {
$.ajax({
url:'partidaasociada/get-linea',
type:'POST',
dataType:'json',
data:{pruebaId:$('#prueba').val()}
// alert(pruebaId);
});
In the javascript function, i need to send the $('#prueba').val() to a php function in the controller:
//Controller
public function actionGetLinea($pruebaId)
{
$model = new PartidaAsociada();
log($pruebaId);
}
But i am getting some errors, i think the button is reloading the whole form and don't recognize the previous data y sent to the form.
Note: The 'alert()' in the javascript function is on commentary because it wont let me use, the form stay loading when i put the alert. thanks beforehand.
I think part of the problem is you aren't preventing the default action of a button click.
We can clean things up a bit too. Hit control+shift+i and choose the console tab to see console.log output.
HTML:
<button class="btn btn-primary _addNew">Add New</button>
Javascript:
$('._addNew').on('click', function(event){
event.preventDefault();
var data = {};
data.pruebaId = $('#prueba').val();
var success = function(data){
console.log("Success!", data);
}
var error = function(data){
console.log("Error!", data);
}
$.ajax({
url:'partidaasociada/get-linea',
type:'POST',
dataType:'json',
data:data
}, success, error);
});

combine jQuery click handler with php header on same button

I have a button that is now inside a little form:
<form name="picSubmit" method="post">
<button class="btn btn-block btn-default" id="upload"><?php echo $lrow[10]; ?> <span class="glyphicon glyphicon-forward"></span></button>
</form>
then my code on top of the page:
<script language="JavaScript" src="js/cameraUserScript.js"></script>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
header('Location: view-subscribe');
}
?>
This is some javascript/jQuery ajax code to send the content inside a <div> and a picture that i have taken to a php page where i use this content to get some data out of my database and to rename and save that picture into a folder
document.getElementById("upload").addEventListener("click", function(){
var dataUrl = canvas.toDataURL();
var idVal = $('.hiddenId').html();
$.ajax({
type: "POST",
url: "incl/camsave.php",
data: {
imgBase64: dataUrl,
idVal: idVal
}
}).done(function(msg) {
console.log('saved');
});
I added a click event on that submit button ID so that when i click this script has to run. It works in Chrome, but because in Chrome you allways have to click the trust button if you use mediahandling i want to use Mozilla but there it isn't working... Does it has something to do with the combination of the submit button and the click event?
Thanks for the help!
I'm not sure why you're mixing vanilla JS and jQuery here, but you can likely solve this by changing your code to this -
$('#upload').click(function() { // you can use jQuery here too
var dataUrl = canvas.toDataURL();
var idVal = $('.hiddenId').html();
$.ajax({
type: "POST",
url: "incl/camsave.php",
data: {
imgBase64: dataUrl,
idVal: idVal
}
}).done(function(msg) {
console.log('saved');
});
});

Categories

Resources