trouble in call a ajax file in jquery - php

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

Related

Set hidden input fields and submit data on same button click [duplicate]

I check two values with ajax. And if both are correct then i want to make a submit (post-back).
But the post-back doesn't work.
Here is the code:
$('form').submit(function () {
var correctCaptcha = false;
var correctWebcode = false;
$.ajax({
url: '/Competition/CheckForm',
type: "POST",
data: $(this).serialize(),
success: function (data) {
if (data == true) {
$('#recaptcha_response_field').removeClass("captchaError");
correctCaptcha = true;
}
else {
Recaptcha.reload();
$('#recaptcha_response_field').addClass("captchaError");
}
}
});
$.ajax({
// like the code above (for webcode)
});
if (correctCaptcha == true && correctWebcode == true) {
document.forms['form'].submit();
}
else { return false; }
});
Use Async:false
$.ajax({
url: '/Competition/CheckForm',
type: "POST",
async:false,
data: $(this).serialize(),
success: function (data) {
if (data == true) {
$('#recaptcha_response_field').removeClass("captchaError");
correctCaptcha = true;
}
else {
Recaptcha.reload();
$('#recaptcha_response_field').addClass("captchaError");
}
}
});
This will cause the infinite loop:
if (correctCaptcha == true && correctWebcode == true) {
document.forms['form'].submit();
}
So use use like this here
if (correctCaptcha == true && correctWebcode == true) {
return true;
}
else {return false;}
Since ajax is async in nature you cannot expect those variables to be set right away when ajax call. You can either set async to false or submit the form inside success handler. Try this.
$('form').submit(function () {
$.ajax({
url: '/Competition/CheckForm',
type: "POST",
data: $(this).serialize(),
success: function (data) {
if (data == true) {
$('#recaptcha_response_field').removeClass("captchaError");
$('form')
.unbind('submit')//we dont need any handler to execute now
.submit();
}
else {
Recaptcha.reload();
$('#recaptcha_response_field').addClass("captchaError");
}
}
});
$.ajax({
// like the code above
});
return false;//To prevent the form from being submitted.
});
By default, $.ajax works asynchronously, your way won't submit the form, you should submit the form in the callback function.

Ajax DELETE redirects even if prevented

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

Ajax function issue on return true and false in wordpress

I am validating a form with ajax and jquery in WordPress post comments textarea for regex. But there is an issue when i want to alert a error message with return false. Its working fine with invalid data and showing alert and is not submitting. But when i put valid data then form is not submit. May be issue with return false.
I tried making variable and store true & false and apply condition out the ajax success block but did not work for me.
Its working fine when i do it with core php, ajax, jquery but not working in WordPress .
Here is my ajax, jquery code.
require 'nmp_process.php';
add_action('wp_ajax_nmp_process_ajax', 'nmp_process_func');
add_action('wp_ajax_nopriv_nmp_process_ajax', 'nmp_process_func');
add_action('wp_head', 'no_markup');
function no_markup() {
?>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('form').submit(function (e) {
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: 'action=nmp_process_ajax&comment=' + comment,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
return false;
}
}
});
return false;
});
});
</script>
<?php
}
And i'm using wordpress wp_ajax hook.
And here is my php code.
<?php
function nmp_process_func (){
$comment = $_REQUEST['comment'];
preg_match_all("/(->|;|=|<|>|{|})/", $comment, $matches, PREG_SET_ORDER);
$count = 0;
foreach ($matches as $val) {
$count++;
}
echo $count;
wp_die();
}
?>
Thanks in advance.
Finally, I just figured it out by myself.
Just put async: false in ajax call. And now it is working fine. Plus create an empty variable and store Boolean values in it and then after ajax call return that variable.
Here is my previous code:
require 'nmp_process.php';
add_action('wp_ajax_nmp_process_ajax', 'nmp_process_func');
add_action('wp_ajax_nopriv_nmp_process_ajax', 'nmp_process_func');
add_action('wp_head', 'no_markup');
function no_markup() {
?>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('form').submit(function (e) {
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: 'action=nmp_process_ajax&comment=' + comment,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
return false;
}
}
});
return false;
});
});
</script>
<?php
}
And the issue that i resolved is,
New code
var returnval = false;
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
async: false, // Add this
data: 'action=nmp_process_ajax&comment=' + comment,
Why i use it
Async:False will hold the execution of rest code. Once you get response of ajax, only then, rest of the code will execute.
And Then simply store Boolean in variable like this ,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
returnval = false;
} else {
returnval = true;
}
}
});
// Prevent Default Submission Form
return returnval; });
That's it.
Thanks for the answers by the way.
Try doing a ajax call with a click event and if the fields are valid you submit the form:
jQuery(document).ready(function () {
jQuery("input[type=submit]").click(function (e) {
var form = $(this).closest('form');
e.preventDefault();
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: {'action':'nmp_process_ajax','comment':comment},
success: function (res) {
var count = parseInt(res);
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
} else {
form.submit();
}
}
});
});
});
note : you call need to call that function in php and return only the count!
Instead of submitting the form bind the submit button to a click event.
jQuery("input[type=submit]").on("click",function(){
//ajax call here
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: 'action=nmp_process_ajax&comment=' + comment,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
return false;
}else{
jQuery("form").submit();
}
}
});
return false;
})
Plus also its a good idea to put return type to you ajax request.
Let me know if this works.

Jquery: unable to show load the respective pages while checking or unchecking the checkbox

I have a check box. I want to call two different php pages based on the checkbox checked and uncheck status.
But the below code is only calling the checked php pages.
What could be the reason?
<script type="text/javascript">
$(function()
{
$('input[id^="test"]').on('click',function()
{
if ($('input[id^="test"]').checked)//when users click to on checkbox to check
{
$.ajax({
url: "updatestatus.php?id="+$(this).val()+"&status=1",
success: function(data){
alert('Successfully updated...');
}
});
}
else//when users uncheck the checkbox
{ $.ajax({
url: "updatestatus.php?id="+$(this).val()+"&status=2",
success: function(data){
alert("uncheckde...");
}
});
}
});
});
</script>
And in page
<?php //checkbox in a while loop
echo " <input type='checkbox' id='test' value='".$row['id']."'/> ";
?>
As requested:
Try using $('input[id^="test"]').is(':checked') as the conditional. You can also use $(this) to reference the specific checkbox that triggered the event. So, here's your code cleaned up a bit:
<script>
$(function() {
$('input[id^="test"]').on('click',function(e) {
if ($(this).is(':checked') {
$.ajax({
url: "updatestatus.php?id="+$(this).val()+"&status=1",
success: function(data){
alert('Successfully updated...');
}
});
}
else {
$.ajax({
url: "updatestatus.php?id="+$(this).val()+"&status=2",
success: function(data){
alert("uncheckde...");
}
});
}
});
});
</script>
One other change I would make would be to assign a class to your checkboxes, and target that instead of using the "starts with" selector (since not every browser supports it).
It's your check for checked or not that isn't working. Use the .is(':checked') method instead.
$(document).ready(function() {
$('input[name=cbx]').change(function() {
if ($(this).is(':checked')) {
alert('Checked');
} else {
alert('Not Checked');
}
});
});
Try like this
$(function()
{
$('input[id^="test"]').on('click',function()
{
if ($(this).attr("checked") == "checked")//when users click to on checkbox to check
{
$.ajax({
url: "updatestatus.php?id="+$(this).val()+"&status=1",
success: function(data){
alert('Successfully updated...');
}
});
}
else//when users uncheck the checkbox
{ $.ajax({
url: "updatestatus.php?id="+$(this).val()+"&status=2",
success: function(data){
alert("uncheckde...");
}
});
}
});
});

Keeping a window toggled open to display and view error messages AJAX, JQuery, PHP

I am having an issue trying to keep a cretin window toggled opened after AJAX retrieves data, to show a proper message to denote weather or not the user has logged in or not.
My Javascript is as follows:
function validLogin(){
var username=$('#username').val();
var password=$('#password').val();
var dataString = 'username='+ username + '&password='+ password;
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="images/loading.gif" width="32px" height="32px" />');
$.ajax({
type: "POST",
url: "login.php",
data: dataString,
cache: true,
success: function(result){
var result=trim(result);
$("#flash").hide();
if(result=='correct'){
$("fieldset#signin_menu").show(); // <-- This will not work!
}else{
$("#errorMessage").html(result);
}
}
After I get the informatoin the window should stay open; however, the page refreshes and the window closes. This is an onclick event once you press "Sign In". A window will pop down. Here is the code for that window popping down:
$(document).ready(function() {
$(".signin").click(function(e) {
e.preventDefault();
$("fieldset#signin_menu").toggle();
$(".signin").toggleClass("menu-open");
});
$("fieldset#signin_menu").mouseup(function() {
return false
});
$(document).mouseup(function(e) {
if($(e.target).parent("a.signin").length==0) {
$(".signin").removeClass("menu-open");
$("fieldset#signin_menu").hide();
}
});
Is there a better work around for this? Am I doing this wrong?
use this jquery instead
$(document).ready(function() {
$("fieldset#signin_menu").show(function() {
$(".signin").toggleClass("menu-open");
});
});
$("fieldset#signin_menu").mouseup(function() {
return false
});
$(document).mouseup(function(e) {
if($(e.target).parent("a.signin").length==0) {
$(".signin").removeClass("menu-open");
$("fieldset#signin_menu").hide();
}
});

Categories