Update view without page refresh in Ajax - javascript

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"

Related

jquery function is being called more than once on single click

I am having more than one button with same class name and different id. but when I click on button, it's called for more than one everytime. for information about code in action, please see the video : https://nimb.ws/3RMoNP
Here is my code
$(document).on("click", ".delete_attachment_confirmation", function(e){
e.preventDefault();
var attachment_id = $(this).data('attachmentid');
$('#delete_attachment_confirmation_'+attachment_id).attr("disabled", true);
$('#delete_attachment_confirmation_'+attachment_id).text("Deleting file");
$.ajax({
url: "<?php echo base_url('attachment/delete_attachment/')?>"+$(this).data('attachmentid'),
type: "GET",
dataType: "text",
success: function(data){
$("#row_"+attachment_id).remove();
$("#attachment_message_body").text(data);
$('#delete_attachment_'+attachment_id).modal('hide');
// attachment message
$('#attachment_message').modal('show');
// modal issue removal trick
$('.modal-backdrop').removeClass('modal-backdrop');
}
});
});
<button class="btn btn-danger delete_attachment_confirmation" id="delete_attachment_confirmation_<?=$row->id?>" data-attachmentid="<?=$row->id?>" ><?php echo $this->lang->line('btn_modal_delete');?>
updated button code
<button class="btn btn-danger delete_attachment_confirmation" id="delete_attachment_confirmation_<?=$row->id?>" data-attachmentid="<?=$row->id?>" ><?php echo $this->lang->line('btn_modal_delete');?>
Highlighted part is showing us that ajax function is being called more than once.
There is nothing in above JS code that is causing it run twice, just that button does not have closing tag and multiple buttons without closing tags and having same class may be the reason, i just ran your code in codepan and it is running fine.
<button class="btn btn-danger delete_attachment_confirmation" id="delete_attachment_confirmation_<?=$row->id?>" data-attachmentid="<?=$row->id?>" ><?php echo $this->lang->line('btn_modal_delete');?></button>
https://codepen.io/balramsinghindia/pen/OJLzjbo
I have used solution provided in this question.
Ajax, prevent multiple request on click
$(".classNamw").unbind().click(function() {
//Your stuff
})

JavaScript - post request to Symfony

I wrote a function to sent a simple request trough Controller via JavaScript in my Symfony project. My alert is triggered when I refresh the page and it should be triggered when I am clicking the Submit button.
What I am doing wrong?
Button:
<button type="button" id="request" data-path="{{ admin.generateObjectUrl('change_status', object) }}" class="btn btn-primary">Submit</button>
My JS code:
var path = $("#request").attr("data-path");
$.ajax({
type: "POST",
url: path,
data: {id : 'aaa'},
"success":function(data){
alert('ok');
}
});
and Controller:
$data = $request->request->get('request');
return new Response($data);
You have to set the onclick property in your button and wrap your JS code in a function that will be called by this onclick

Delete Field in Datatable with ajax in Codeiginiter without refreshing page

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
});

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);
}
}
});
}
});

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