Handling empty action in $.ajax function - php

I want to load evrything in my website inside a div, so i created a function to handle form submissions to make the action loads in the same div, however the problem is some forms don't have action action="" as the script is in the same page, so when i submit the form nothing happen inisde the div, so how i can handle this in my function?
$(document).ready(function() {
$('#mydiv').delegate('form', 'submit', function() { // catch the form's submit events inside the div
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(response) { // on success..
//$('#mydiv').html(response); // update the DIV
$('#mydiv').fadeOut('slow',function() {
$('#collabsoft').html(response).fadeIn('slow');
});
// return false;
}
});

You can use a ternary if statement:
url: $(this).attr('action') == '' ? window.location : $(this).attr('action')

Related

jQuery preventDefault() not working inside AJAX call

So, I am doing a check when a user inputs an email to see if the email exists or not.
$('form.recover-form#check-form').on('submit', function(e){
var form = $(this),
input = $('.check-recover-email'),
span = $('.recover-error'),
email = input.val();
span.text('');
e.preventDefault();
$.ajax({
url: 'ajax/check-email',
async: 'false',
cache: 'false',
type: 'POST',
data: {email: email},
success: function(response) {
if ( response == 'no' ) {
span.text('email does not exist');
} else if ( response == 'ok' ) {
form.submit();
}
}
});
});
The php code
if ( Input::isPost('email') ) {
$email = Input::post('email');
$check = $dbh->prepare(" SELECT * FROM users WHERE email = :email ");
$check->execute(array( 'email' => $email ));
echo ( $check->rowCount() == 1 ) ? 'ok' : 'no' ;
}
This way as soon as I submit the form it submits and the e.PreventDefault() inside the AJAX call is not working. If I put e.PreventDefault() before the AJAX call however, the form does not submit and the error appears if the email does not exists ( this is what I want to achieve ).
I can't understand where the problem is, hope you can help.
Thank you.
EIDT: This is the updated code
The problem is that you don't call preventDefault during the handling of the event. Instead, during the handling of the event, you start an ajax call (which is asynchronous), and then let the event continue. The ajax call completes later, which is too late to prevent the event's default — it's already happened.
Move the e.preventDefault() directly into the event handler, outside the ajax success handler.
$('.recover-form').on('submit', function(e){
var form = $(this),
input = $('.check-recover-email'),
span = $('.recover-error'),
email = input.val();
span.text('');
e.preventDefault(); // <=================== Here
$.ajax({
url: 'ajax/check-email',
async: 'false',
cache: 'false',
type: 'POST',
data: form.serialize(),
success: function(response){
if ( response == 0 ) {
// ============================ Not here, this would be too late
span.text('email does not exist');
}
}
});
});
In a comment, you've said:
Yes, it works for the validation, but I want to submit the form if ajax returns a positive response. I only do a check with AJAX, if it fails stop the submit, if it succeed continue the submit.
You can't hold up the original form submission waiting for the result of an asynchronous ajax call. What you do instead is cancel the original form submission, do the ajax, and then if the result is okay, re-submit the form using the submit method on the raw DOM form element. That method doesn't re-trigger submit event handlers.
Example: Live copy
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<meta charset=utf-8 />
<title>Delaying form submit during ajax</title>
</head>
<body>
<form action="http://www.google.com/search" method="GET">
<input type="text" name="q" value="kittens">
<input type="submit" value="Submit">
</form>
<script>
(function() {
$("form").submit(function(e) {
var rawFormElement = this; // Remember the DOM element for the form
// Stop form submission
display("Got form submit event, simulating ajax");
e.preventDefault();
// Simulate ajax check of data
setTimeout(function() {
// (This is the 'success' callback for the ajax)
display("Ajax call complete, pretending result is good and submitting");
// All okay, go ahead and submit the form
rawFormElement.submit(); // Doesn't trigger 'submit' handler
}, 1500);
});
function display(msg) {
$("<p>").html(String(msg)).appendTo(document.body);
}
})();
</script>
</body>
</html>
You can't prevent the default action from a success handler of ajax request because of the asynchronous nature of it.
Instead by default prevent the form submission, then in the success handler if it is valid then call the submit again.
$('.recover-form').on('submit', function (e) {
var form = $(this),
input = $('.check-recover-email'),
span = $('.recover-error'),
email = input.val();
span.text('');
//prevent the submit
e.preventDefault();
$.ajax({
url: 'ajax/check-email',
async: 'false',
cache: 'false',
type: 'POST',
data: form.serialize(),
success: function (response) {
if (response == 0) {
span.text('email does not exist');
} else {
//submit if valie
form[0].submit()
}
}
});
});
First, you're options are incorrect. cache and async require boolean values, not strings.
async: false,
cache: false,
Secondly, instead of submitting the form after the ajax request you're instead triggering the event. Try this instead.
form.get(0).submit();
It returns the form node rather than a jquery object, allowing you to submit it directly rather than triggering an event (otherwise you would have an infinite loop.)
You don't really need async: false or cache: false in this case.
You need to do the following:
$('.recover-form').on('submit', function(e){
e.preventDefault();
var form = $(this),
input = $('.check-recover-email'),
span = $('.recover-error'),
email = input.val();
span.text('');
$.ajax({
url: 'ajax/check-email',
async: 'false',
cache: 'false',
type: 'POST',
data: form.serialize(),
success: function(response){
if ( response == 0 ) {
span.text('email does not exist');
}
}
});
});
Notice how I've moved the e.preventDefault() to the beginning. This is because you were calling it when the ajax request responds which might happen 100s of milliseconds or even seconds after the form has been submitted
This happens because success function passed for jQuery.ajax() is executed assyncly, then it will be executed after event handler function is finish.
You should put the e.preventDefault() out of ajax function. and everything will work.
Better you can try something like this ,
<form name="myForm" onsubmit="return submitObj.validateAndSubmit();"> <!-- your form -->
<!-- your AJAX -->
var submitObj = {
validateAndSubmit : function()
{
var form = $('.recover-form'),
input = $('.check-recover-email'),
span = $('.recover-error'),
email = input.val();
span.text('');
$.ajax({
url: 'ajax/check-email',
async: 'false',
cache: 'false',
type: 'POST',
data: form.serialize(),
success: function(response){
if ( response == 0 ) {
return false;
}
else{
return true;
}
}
});
}
};

JQuery $(window).load doesnt fadeOut() my div when other JQuery code to submit form is called

I have this jquery on every page:
$(window).load(function(){
// PAGE IS FULLY LOADED
// FADE OUT YOUR OVERLAYING DIV
$('#overlay').fadeOut();
});
which fades out a div when the page is fully loaded.
On all pages i have a form and this Jquery code:
<script type="text/javascript">
$(document).ready(function() {
$("#message").hide();
$("#please_wait_box").hide();
$("#reviewtickets").submit(function(e) {
$("#message").hide();
$("#please_wait_box").show();
e.preventDefault();
dataString = $("#reviewtickets").serialize();
$.ajax({
type: "POST",
url: "reviewtickets_go.php",
cache: false,
data: dataString,
success: function(res) {
$("#please_wait_box").hide();
$("#message").html(res);
$('#message').fadeIn('slow');
if (res.indexOf("success") != -1) {
window.location.href = res.substr(8);
}
}
});
});
});
</script>
so it basically calls another page to submit the form without moving away from the page.
When the forms are submitted, the page is called to save the data in the above jquery code but my jquery load function doesnt fade out because it cannot see that the page has fully loaded
how can i stop the loading function if the form submit code is used?
the div had an id and class both of overlay
the jquery needed to be the class and not the id as the css was on the class
call it inside the success callback of ajax . success function callback is called when the ajax request is successfully made and datas are returned from the server.
success: function(res){
$("#please_wait_box").hide();
$("#message").html(res);
$('#message').fadeIn('slow');
$('#overlay').fadeOut(); //<---here
if (res.indexOf("success") != -1) {
window.location.href = res.substr(8);
}
}

Ajax call with target div in another page

I don't know if what i'm asking is possible,but of course should match my needs
This is my ajax call
function submitForm1() {
var form1 = document.myform1;
var dataString1 = $(form1).serialize();
$.ajax({
type:'POST',
url:'db_query.php',
cache: false,
data: dataString1,
success: function(data){
$('#query_database').html(data);
}
});
return false;
}
The target div is on another page. So when I submit the form I should be redirected to www.mysite.com/response and then get the ajax request executed in #query_database.
I wanted to add window.location.href = "response.html" but this just redirect me after the call has been executed.
Any way to do that?

HTML : Enable Multiple Submission without refreshing

I want to enhance my tool's page where as soon use click a button. Request goes to server and depending upon return type (fail/pass) i change color of button. No Refresh/page reload
Page has multiple buttons : some what like below.
Name 9-11 - 11-2 2-5
Resource1 - Button - Button - Button
Resource2 - Button - Button - Button
Resource1 - Button - Button - Button
I am a c++ programmer so you might feel i asked a simple question
Here's a sample of jQuery Ajax posting a Form. Personally, I'm unfamiliar with PHP but Ajax is the same no matter what. You just need to post to something that can return Success = true or false. This POST happens asynchronously so you don't get a page refresh unless you do something specific in the success: section.
$("document").ready(function () {
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: yourUrlHere,
dataType: "json",
cache: false,
type: 'POST',
data: $(this).serialize(),
success: function (result) {
if(result.Success) {
// do nothing
}
}
});
}
return false;
});
});
Of course you don't have to be doing a POST either, it could be a GET
type: 'GET',
And if you don't need to pass any data just leave data: section out. But if you want to specify the data you can with data: { paramName: yourValue },
The cache: false, line can be left out if you want to cache the page. Seeing as how you aren't going to show any changes you can remove that line. jQuery appends a unique value to the Url so as to keep it from caching. Specifying type: "json", or whatever your specific type is, is always a good idea but not necessary.
Try using the $.post or $.get functions in jquery
$.post("url",$("#myform").serialize());
Adding a callback function as Fabrício Matté suggested
$.post("url",$("#myform").serialize(),function(data){alert(data);$("#myform").hide()//?Do something with the returned data here});
Here you go. You will find an example of a form, a button a the necessary ajax processing php page. Try it out and let us know how it goes:
<form action="" method="post" name="my_form" id="my_form">
<input type="submit" name="my_button" id="my_button" value="Submit">
</form>
<script type="text/javascript">
$("document").ready(function () {
$('#my_form').submit(function () {
$.ajax({
url: "ajaxpage.php",
dataType: "json",
type: "POST",
data: $(this).serialize(),
success: function (result)
{
//THere was an error
if(result.error)
{
//So apply 'red' color to button
$("#my_button").addClass('red');
}
else
{
//there was no error. So apply 'green' color
$("#my_button").addClass('green');
}
}
});
return false;
});
});
</script>
<?php
//ajaxpage.php
//Do your processing here
if ( $processed )
{
$error = false;
}
else
{
$error = true;
}
print json_encode(array('error' => $error));
die();
?>

Get only part of the message and reload only one div

this is an ajax method that inserts the data into a db and should supposedly display the new content.
<script type = "text/javascript">
$(document).ready(function() {
$('#submit').live('click', function(eve) {
eve.preventDefault() ;
var form_data = {
title: $('#title').val()
};
$.ajax({
url: "http://localhost/ci/index.php/chat/comment",
type: 'POST',
data: form_data,
success: function(msg) {
alert(msg);
}
});
});
});
</script>
However in my /chat/comment, i am loading the view again, i.e, user submits a comment, load the view again and the comment should be there. My response from server is the view's HTML. However the view comes with all the divs and there are many of them. I need to retrieve only part of the div, say, #commentspace from the ajax on success.
Look at the jQuery $.load() function?
Example
Inside "firstpage.html"
$('#content').load('secondpage.html #content');

Categories