I'm trying to delete row from database with DELETE method and using AJAX in my Laravel 5.2 project. Everything is working, picture is deleted from server and the row is deleted from database but after deleting it redirects to JSON response.
My controller's action:
public function deletePhoto(Photo $photo)
{
if ($photo->delete()) {
unlink('files/' . $photo->filename);
unlink('files/thumbs/' . $photo->filename);
return response()->json(['result' => 0]);
}
return response()->json(['result' => 1]);
}
It works this way while adding photos (it adds but doesn't redirect).
Here is my ajax code:
$('#deleteForm').submit(function(e) {
var currentElement = $(this);
var formUrl = $(this).attr('action');
$.ajax({
type: 'POST',
url: formUrl,
data: {_method: 'delete', _token: '{{ csrf_token() }}'},
success: function(data) {
if (data.result == 0) {
currentElement.parent().fadeOut(400, function() {
$(this).remove();
});
} else {
alert('Wystąpił błąd podczas usuwania zdjęcia! Proszę spróbować ponownie!');
}
}
});
return false;
});
I tried many changes (from laracast and stackoverflow) with method, token and data but nothing worked.
How do I solve this problem?
Add a prevent default to your submit event. The page is redirecting because you're initiating a submit event.
e.preventDefault();
Change submit event to:
$("#form-submit-button").click(function(e){
});
try this:
$('#deleteForm').submit(function(e) {
e.preventDefault()
var currentElement = $(this);
var formUrl = $(this).attr('action');
$.ajax({
type: 'POST',
url: formUrl,
data: {_method: 'delete', _token: '{{ csrf_token() }}'},
success: function(data) {
if (data.result == 0) {
currentElement.parent().fadeOut(400, function() {
$(this).remove();
});
} else {
alert('Wystąpił błąd podczas usuwania zdjęcia! Proszę spróbować ponownie!');
}
}
});
return false;
});
you need to add preventDefault to prevent the page from redirecting
check from console if there is errors in javascript code to work the e.preventDefault
Related
I´m traying to do logging in my web with ajax. But i need generated google key when i do click in login, and before to do login. I have this function:
$('#main-login-form').on('submit', function(e){
renewKeyRecaptcha();
//e.preventDefault();
let key = $("#recaptchaResponse").val();
console.log(key);
if(key != null || key != ""){
var $this = $(this);
$(this).find('input').removeClass('is-invalid');
$(this).find('.error').html('');
var data = $this.serializeArray();
data.push({name: 'currentName', value: config.url.currentName});
$.ajax({
type: $this.attr('method'),
url: $this.attr('action'),
data: data,
dataType: $this.data('type'),
success: function (response) {
if(response.success) {
$(location).attr('href', response.redirect);
}
console.log(response);
},
error: function (jqXHR) {
var response = JSON.parse(jqXHR.responseText);
if (response.errors.password) {
$($this).find('input[name="password"]').addClass('is-invalid');
$($this).find('.password-error').html(response.errors.password);
} else if (response.errors.email) {
$($this).find('input[name="email"]').addClass('is-invalid');
$($this).find('.email-error').html(response.errors.email);
} else if (response.errors.gRecaptchaResponse) {
$($this).find('input[name="g-recaptcha-response"]').addClass('is-invalid');
$($this).find('.g-recaptcha-response-error').html(response.errors.gRecaptchaResponse);
}
}
});
}
});
this function call to renewKeyRecaptcha(); that generated key, but i need to do click login twice and before i´m login... i need to do once click in login and generate key and login... But i can´t. I don´t know if i´m doing well or i would do to another way.
My function that generate key:
function renewKeyRecaptcha(){
// add key google to input
var key = config.url.recaptchaGoogle;
grecaptcha.ready(function() {
grecaptcha.execute(key, {action: 'login'}).then(function(token) {
$("#recaptchaResponse").val(token);
$("#recaptchaResponseRegister").val(token);
});
});
}
this function run ok.
Thanks for help.
I resolve my question with:
$("#submitLogin").on("click", function(e){
renewKeyRecaptcha();
e.preventDefault();
setTimeout(function(){
$(this).find('input').removeClass('is-invalid');
$(this).find('.error').html('');
$this = $('#main-login-form');
var data = $this.serializeArray();
data.push({name: 'currentName', value: config.url.currentName});
$.ajax({
type: $this.attr('method'),
url: $this.attr('action'),
data: data,
dataType: $this.data('type'),
success: function (response) {
if(response.success) {
$(location).attr('href', response.redirect);
}
console.log(response);
},
error: function (jqXHR) {
var response = JSON.parse(jqXHR.responseText);
if (response.errors.password) {
$($this).find('input[name="password"]').addClass('is-invalid');
$($this).find('.password-error').html(response.errors.password);
} else if (response.errors.email) {
$($this).find('input[name="email"]').addClass('is-invalid');
$($this).find('.email-error').html(response.errors.email);
} else if (response.errors.gRecaptchaResponse) {
$($this).find('input[name="g-recaptcha-response"]').addClass('is-invalid');
$($this).find('.g-recaptcha-response-error').html(response.errors.gRecaptchaResponse);
}
}
});
}, 3000);
So, i have a following ajax code and controller code, my problem is i want to insert comment withouth refreshing the page and not redirecting to another page, and it seems that whenever i hit btnCommentSubmit it is redirecting me to my controller page, how to prevent that?
Ps. The insertion is working
//AJAX CODE
$('#btnComment').click(function(e){
var comment_identifier = $(this).data("value");
var comment_by = $(this).data("id");
$('#formAddComment').attr('action', '<?php echo base_url() ?>Discussion/addComment/'+comment_identifier+"/"+comment_by);
});
$('#btnCommentSubmit').click(function(){
var url = $('#formAddComment').attr('action');
var addCommentTxt = $('#addCommentTxt').val();
$.ajax({
type: 'post',
url: url,
data: {addCommentTxt:addCommentTxt},
success: function(){
alert('success');
},
error: function(){
console.log(data);
alert('Could not add data');
}
});
});
});
//Controller code
public function addComment(){
$cIden = $this->uri->segment(3);
$cBy = $this->uri->segment(4);
$data = array(
"comment_identifier" => $cIden,
"comment_by" => preg_replace('/[^a-zA-Z-]/', ' ', $cBy),
"comment" => $this->input->post('addCommentTxt'),
"comment_at" => time()
);
if ($this->Crud_model->insert('comments',$data)) {
return true;
}else{
return false;
}
}
Add e.preventDefault() in the beginning of your function:
$('#btnCommentSubmit').click(function(e){
e.preventDefault();
...
}
You may want to use jQuery form plugin. It submit form to our controller without any page refresh/redirect. I use it all the time.
https://jquery-form.github.io/form/
Example usage:
$('#form').ajaxForm({
beforeSubmit: function() {
//just optional confirmation
if (!confirm('Are you sure want to submit this comment?')) return false;
show_loading();
},
success: function(status) {
hide_loading();
if (status == true) {
alert('success');
} else {
alert('Could not add data');
}
}
});
You can use javascript:void(0); like href="javascript:void(0);"
Hello overflowers!
I can't seem to manage to send my ajax data over to my php page correctly, it has worked perfectly fine before but now it is not working.
I'm getting the correct data via console.log but on my php page i'm getting Undefined index error.
Jquery
var task_takers_pre = [];
var task_takers = [];
var i = 1;
$(".new-task-takers ul.select_takers li").on('click', function(){
$(this).each(function(){
$(this).toggleClass("active");
if($(this).find('.fa').length > 0){
$(this).find('.fa').remove();
i -= 1;
var removeItem = $(this).data("id");
task_takers_pre.remove(removeItem);
console.log(task_takers_pre);
}else{
$('<i class="fa fa-check" aria-hidden="true"></i>').insertBefore($(this).find("div"));
i += 1;
task_takers_pre[i] = $(this).data("id");
console.log(task_takers_pre);
}
$.each(task_takers_pre, function (index, value) {
if ($.inArray(value, task_takers) == -1) {
task_takers.push(index, value);
}
});
});
});
$("#new-task").on('submit', function(){
console.log(task_takers_pre);
$.ajax({
type: 'POST',
url: '',
cache: false,
data: {task_takers_pre : task_takers_pre },
success: function(data) {
//console.log(data)
}
});
});
PHP
if(isset($_POST['task_submit'])){
$task_takers = $_POST['task_takers_pre'][0];
var_dump($task_takers);
}
EDIT
jQuery
var task_takers_pre = [];
var task_takers = [];
var i = 1;
$(".new-task-takers ul.select_takers li").on('click', function(){
$(this).each(function(){
$(this).toggleClass("active");
if($(this).find('.fa').length > 0){
$(this).find('.fa').remove();
i -= 1;
var removeItem = $(this).data("id");
task_takers_pre.remove(removeItem);
console.log(task_takers_pre);
}else{
$('<i class="fa fa-check" aria-hidden="true"></i>').insertBefore($(this).find("div"));
i += 1;
task_takers_pre[i] = $(this).data("id");
console.log(task_takers_pre);
}
$.each(task_takers_pre, function (index, value) {
if ($.inArray(value, task_takers) == -1) {
task_takers.push(index, value);
}
});
});
});
$(".assign").on('click', function(){
console.log(task_takers_pre);
$.ajax({
type: 'POST',
url: './core/includes/new_task.php',
cache: false,
data: {task_takers_pre : task_takers_pre},
success: function(data) {
//console.log(data)
}
});
$.ajax({
type: 'POST',
url: '',
cache: false,
data: {'task_takers_pre' : task_takers_pre},
success: function(data) {
//console.log(data)
}
});
});
PHP
if(isset($_POST['task_takers_pre'][0])){
$task_takers = $_POST['task_takers_pre'][0]; // Just for testing
var_dump($task_takers); // Just for testing
}
if(isset($_POST['task_takers_pre'])){
$task_takers2 = $_POST['task_takers_pre']; // Just for testing
var_dump($task_takers2); // Just for testing
}
What you are attempting to do is use the same PHP code to handle the Button Press from the Form AND the AJAX Call. Don't!
(note: This answer is Only based upon the code that has been provided and what is trying to achieved with this code.)
So your current PHP is, which I am guessing is what you call when you click the submit button... In that case $_POST['task_takers_pre'] will not exist as you are generating that from the JS and sending it in the AJAX Call.
Write a separate AJAX Call.
You need to create a separate file to handle your AJAX calls and have it perform what duties it needs to perform.
// This is just for testing my AJAX Call
public function ajax_post(){
if(isset($_POST['task_takers_pre'])){
$task_takers = $_POST['task_takers_pre'][0]; // Just for testing
var_dump($task_takers); // Just for testing
die();
}
else {
// Illegal access/entry do something...
echo 'Error - I had better check what I am posting.';
die();
}
}
If you juse want to send some data in the AJAX Call when you click the submit button,you could return false to prevent form submission in the submit event.
$("#new-task").on("submit", function(){
$.ajax({
type: "POST",
url: "",
cache: false,
data: {task_submit:1, task_takers_pre: task_takers_pre},
success: function(data){
console.log(data);
}
});
return false;
});
This below coding is working in chrome browser but not in mozilla. How to solve this problem in mozilla firefox.
$(document).ready(function() {
$("#del_enquiry").click(function() {
var enquiry = new Array();
$('input[name="del_enq"]:checked').each(function() {
enquiry.push(this.value);
});
if(confirm("Do you want to delete the Records"))
{
var delid="deleteid="+enquiry;
$.ajax({
url: "delete_enquiry.php",
type: "POST",
data: delid,
cache: false,
success: function(data) {
if(data==1) {
alert("Record Deleted Successfully");
} else {
alert("Record not Deleted");
}
}
});
}
});
});
You can use onsubmit atttribue of form tag function before submitting the form.
Inside my function write your confirm box conditions.
if(confirm("Do you want to delete?"))
{
return true;
}
So I'm creating this form validator with PHP and jQuery.
The PHP code will check through the form and then return an array with fields that contain errors. Example: {"email":1,"password":1}
But now I have concerns regarding if no errors were to be found. The problem here is that I've included "return false" in the end of the code to prevent page redirection. I've read that this is bad code practice but not found another way that works as intended.
The second problem is how to pass the o-array into the $('input').each function. Right now it will say that all forms are valid since nothing was passed. If I use $.post instead of $.ajax this scope problem doesn't appear for some reason.
jQuery:
$(function() {
$('#register').submit(function() {
var url = $(this).attr('action');
var data = $(this).serialize();
$.ajax({
type: 'GET',
url: url,
data: data,
success: function(o) {
console.log(o);
$('input').each(function() {
var msgId = o[$(this).attr('name')];
console.log(o[$(this).attr('name')]);
if (msgId > 0) {
$('#listError').css('visibility', 'visible');
$('#listError').append('<li>' + $(this).nextAll('span.msg').eq(msgId - 1).text() + '</li>');
$(this).addClass('invalid');
} else if (msgId != 0) {
$(this).addClass('valid');
}
$('#listError').append('</ul>');
})
}
}, 'json');
return false;
});
});
Fist, why are you submitting a form when you really don't want to?! Use a button instead and make the AJAX request from its click handler.
$('#registerButton').click(function() {
var form = $('#register')
var data = form.serialize();
$.ajax(...);
});
"The second problem is how to pass the o-array into the $('input').each"
What is the problem here? If you have an each() inside a success callback, you can use the data parameter that is passed to the callback (or o in your case) in that each().
Try this
$(function() {
$('#submit_button_id').click(function() {
var url = $(this).attr('action');
var data = $(this).serialize();
var ret = true;
$.ajax({
type: 'GET',
url: url,
async: false,
data: data,
success: function(o) {
console.log(o);
$('input').each(function() {
var msgId = o[$(this).attr('name')];
console.log(o[$(this).attr('name')]);
if (msgId > 0)
ret = false;
$('#listError').css('visibility', 'visible');
$('#listError').append('<li>' + $(this).nextAll('span.msg').eq(msgId - 1).text() + '</li>');
$(this).addClass('invalid');
} else if (msgId != 0) {
$(this).addClass('valid');
}
$('#listError').append('</ul>');
})
}
}, 'json');
if(ret==true){
$('#register').submit();
}
});
});