AJAX POST Form using return false still refreshes - ajax

I can't seem to see the issue here, this AJAX request should be pulling results from sx.php and displaying within the success, although it keeps submitting to itself???
s.php
<script type="text/javascript">
$(document).ready(function(){
$(".button").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "sx.php",
data: $(this).closest("form").serialize(),
cache: false,
success: function(data){
$('#status').html(data);
}
});
return false;
});
});
</script>
<form>
<input type="hidden" name="mid" value="<?php echo htmlspecialchars($result['id']); ?>" />
<h5><?php echo htmlspecialchars($result['title']); ?></h5>
<input type="submit" class="button" value="Go" />
</form>
Im going crazy here...!

Don't trigger the click of the button, but call the from submit event:
$('form').submit(function(){
return false
})

Related

Ajax call is being accidently triggered

I'm creating a login page and at the bottom of the pop-up form, there is another button that takes you to the registration page. The issue appears to be that when navigating to the new page it all sits under the original sign-in form which uses an ajax call to check if the user exists so when they try to submit the registration form it then calls that ajax call from the sign-in form.
Sign-in form
<div id="myForm">
<form onsubmit="return false;" id="loginForm">
<h1>Login</h1>
<label for="email"><b>Email</b></label>
<input type="email" id="email" placeholder="Enter Email" name="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" id="psw" placeholder="Enter Password" name="psw" required>
<div id="message" class="alert-danger"></div>
<br />
<button type="submit" id="submit" class="btn">Login</button>
<button type="button" class="btn cancel" onclick="closeForm();">Close</button>
</form>
<div class="d-inline">
<button class="btn-info">#Html.ActionLink("User Registration", "SignUp", "SignUp_SignIn")</button>
</div>
</div>
Then the ajax call is
$(document).ready(function () {
$("form").on('submit', function (event) {
var data = {
'email': $("#email").val(),
'psw': $("#psw").val()
};
$.ajax({
type: "POST",
url: 'SignUp_SignIn/CredentialCheck',
data: data,
success: function (result) {
if (result == true) {
$("#message").text("Login attempt was successful");
}
else {
$("#message").text("Email/Password didn't match any results");
}
},
error: function () {
alert("It failed");
}
});
return false;
});
});
After looking at the comments I realized that the reason that the login form was being called from the layout.cshtml so when the ajax call was being called it was grabbing all the form tags that existed on any page that was loaded up. After changing the ajax so it was calling a specific id for the login form instead of form it allowed for proper actions to take place.
An example of what I'm refusing to
$(document).ready(function () {
$("form").on('submit', function (event) {
$.ajax({
type: "POST",
url: url,
data: data,
success: function (result) {
//Do stuff
}
});
});
});
The above will try to redirect you on the submit of any form that is loaded up, but if we go through and change the way it accesses the form like below then it will only work if the one specific form is submitted.
$(document).ready(function () {
$("#loginForm").on('submit', function (event) {
$.ajax({
type: "POST",
url: url,
data: data,
success: function (result) {
//Do stuff
}
});
});
});

ajax form in CodeIgniter - sending generated form

I want to open a modal and get the content (the formular) form the controller. These steps work fine.
Now I have the formular inside the modal. How I can submit these formular and process it with the same controller function?
At the Moment I do the Ajax-Call in this way
$('.modaldisconnect').click(function(){
var modid = $(this).attr('modid');
$.ajax({
url: "<?php echo base_url() ?>admin/module/disconnect_form",
method: "POST",
data: {modid:modid},
// Callback function that is executed after data is successfully sent and received
success: function(data){
// Print the fetched data of the selected phone in the section called #phone_result
// within the Bootstrap modal
$('.modal-ajax-content').html(data);
// Display the Bootstrap modal
$('#disconnect_modal').modal('show');
},
error: function(error){
// Show error message
alert('error');
}
});
});
This is the form which will be generate from the controller by the call above
echo' <div class="modal-body">
<div id="modul_disc_infos">
<span class="module-headlines-title">'._l("modul_name").': <span id="disc_modulname">'._l('module_'.$result->folder.'_titel').'</span></span>
<span class="module-headlines-subtitle">'._l("modul_disconnect_deadline").': <span id="disc_enddate">'.$enddate.'</span></span>
</div>
<div id="modul_disc_check">
<div class="alert alert-danger" role="alert">'._l("modul_disconnect_disclaimer").'</div>
<hr>
<input type="checkbox" name="check_disclaimer" value="1"> '._l("modul_disconnect_disclaimer_check").'
<input type="hidden" name="modid" value="'.$this->input->post('modid').'">
<input type="hidden" name="formstep" value="1">
'.$errormsg.'
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">'._l('close').'</button>
<button type="button" class="btn btn-danger" id="submit_disconnect" >'._l('modul_disconnect_now').'</button>
</div>';
By the way - is there a better way to parse the values of the formular instead one by one like in my code "var modid = $(this).attr('modid');"?
I've solved that in this way that i do 2 different ajax call, starts with a click or submit on the form or a specific button. One call generate the form, one call handle the form. For me it works and its a little bit flexibel to use the same functions for different jobs.
//Formular for disconnection
$('.modaldisconnect').click(function(){
var modid = $(this).attr('modid');
$('#ajax_modal_title').html('<?php echo _l('modul_disconnect'); ?>');
$.ajax({
url: "<?php echo base_url() ?>admin/module/disconnect_form",
method: "POST",
data: {modid:modid},
// Callback function that is executed after data is successfully sent and recieved
success: function(data){
// Print the fetched data of the selected phone in the section called #phone_result
// within the Bootstrap modal
$('.modal-ajax-content').html(data);
// Display the Bootstrap modal
$('#ajax_modal').modal('show');
},
error: function(error){
// Show error message
alert('error');
}
});
});
//Handle the disconnection
$("#ajax_form").on("submit", function (event) {
event.preventDefault();
subform=$('input[name="subform"]').val();
$.ajax({
url: "<?php echo base_url() ?>admin/module/"+subform+"_form",
type: "POST",
data: $('#ajax_form').serialize(),
success: function(result){
$('.modal-ajax-content').html(result);
},
error: function(error){
// Show error message
alert('error');
}
});
});

input(file) and input (text) send with one ajax

html
<body>
<form method="post" action="" id="dataForm" enctype="multipart/form-data">
<input type="text" id="textSelector"/>
<input type="file" id="fileSelector"/>
<button name="sub-comfirm" class="btn-selection-content" type="submit" id="sub-comfirm">Send</button>
</form>
</body>
js/ajax
var fileVar = null;// global var to store file info
$(document).ready(function(){
$('#dataForm').on('submit', function(e) {
e.preventDefault();
SendData();
});
$('#fileSelector').on('change',function(ev){
fileVar = null;
fileVar = new FormData();
$.each(ev.target.files, function(key, value)
{
fileVar.append(key, value);
});
});
});
function SendData(){
var formData = new FormData($("#dataForm")[0]);
// should i add the filerVar like this ?
// formData.append("Image", fileVar);
$.ajax({
type: "POST",
url: "checkinput.php",//you need to add this '?files part' to URL
data: formData,// use fileVar here now
cache: false,
processData: false,
// contentType: false,
success:function(data)
{
console.log(data);
console.log("success");
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log("failure");
}
});
}
php
print_r($_POST);
print_r($_FILES);
my intention is to send input(file) and input(text) in one ajax , i can get the input file value if i add ajax data with fileVar , but i cant get my input text value i have no idea why , can anyone tell me what i did wrong ?
var formData = new FormData($("#dataForm")[0]) is the way to get both to one ajax but i cant get any input text value.
anyone can teach me how to make this work ?
I think you need to specify input name attributes:
<body>
<form method="post" action="" id="dataForm" enctype="multipart/form-data">
<input type="text" id="textSelector" name="textSelector"/>
<input type="file" id="fileSelector" name="fileSelector"/>
<button name="sub-comfirm" class="btn-selection-content" type="submit" id="sub-comfirm">Send</button>
</form>
</body>
Hope that helps.

Post request on Mootools

I'm new to MooTools and trying to send Ajax request with form content to the url.
<form method="post" enctype="multipart/form-data" action="<?= $PHP_SELF; ?>" name="fn" id="fn">
<input name="user_name" id="user_name">
<input name="user_mail" id="user_name">
<input name="user_text" id="user_name">
<input type="file" name="attach">
<input id="button" type="button" value="Submit">
</form>
<script type="text/javascript">
$('button').addEvent('click', function(event) {
var req = new Request({
method: 'post',
url: 'url.php',
onSuccess: function(response) {
alert(response);
});
});
</script>
When I click on button, nothing happens. How right transferring data from form?
Your code looks good, you had a } missing but aside from that you just forgot to add a .send();
Like req.send();, and you can actually pass the data as a argument to that method.
Test that and check here about the .send() method.
Suggention to how your code could look like:
<script type="text/javascript">
var req = new Request({
method: 'post',
url: 'url.php',
onSuccess: function(response) {
alert(response);
} // < --- You actually missed this one
});
$('button').addEvent('click', function(event) {
req.send();
});
</script>

Sending AJAX request before submitting the form

Problem: I'm trying to send ajax reguest, and then submit the form.
Aproaches:
1. I solved the problem by putting
success: function() {
document.myform.submit();
}
But i think it's not the most elegant solution. Can you explain me why it works only if i put document.myform.submit(); in success? Is there any other way to solve this problem?
<div class="buttons">
<div class="right">
<form name="myform" onsubmit="javascript: startAjax(); return false;" action="https://example.com/payment.php" method="get">
<input type="hidden" name="merchantId" value="<?php echo $merchantIdKZM; ?>">
<input type="submit" value="<?php echo $button_confirm; ?>" id="button-confirm2" class="button" name="PayKZM" />
</form>
</div>
</div>
<script type="text/javascript">
function startAjax() {
console.log("dafaaaa");
$.ajax({
type: 'get',
url: 'index.php?route=payment/bank_transfer/confirm',
async: 'false',
success: function() {
// location = '<?php echo $continue; ?>';
}
});
} // Calls ajaxComplete() when finished
function ajaxComplete()
{
console.log("dafa");
document.myform.submit();
}
</script>
success's function is called upon the get request receiving a valid response as #harsh pointed out. Thus it will occur after the get request. I believe something similar to the following would do as you request though I haven't tested it:
<script type="text/javascript">
$(function () {
$("#form").on('submit', function () {
var $form = $(this);
$.ajax({
type: 'GET',
url: 'index.php?route=payment/bank_transfer/confirm',
data: $form.serialize(),
async: 'false',
success: function () {
$.ajax({
type: 'GET',
url: 'https://example.com/payment.php',
data: $form.serialize(),
});
}
});
});
});
</script>

Resources