I want to return false from $.ajax when success is complete:
$.ajax({
url: '' + $website_url + 'queries/voorraad_berekenen.php',
type: 'post',
data: {
aantal: $(this).parent('form').children('.quantity').val(),
item_number_1: $(this).parent('form').children('.item_number_1').val()
},
success: function(result) {
return false;
}
});
This doesn't work. Is there a work around?
From your post I guess that you call a function that contains the $.ajax() and try to return false to that function. but you can't do that such way, because AJAX is asynchronous.
It's better to call a function from the ajax success function like following:
$.ajax({
url: '' + $website_url + 'queries/voorraad_berekenen.php',
type: 'post',
data: {
aantal: $(this).parent('form').children('.quantity').val(),
item_number_1: $(this).parent('form').children('.item_number_1').val()
},
success: function(result) {
var returned = true;
if(some_condition_not_satisfied) {
returned = false;
} else {
}
// call a function
calledFromAjaxSuccess(returned);
}
});
function calledFromAjaxSuccess(result) {
if(result) {
alert('TRUE');
} else {
alert('FALSE');
}
}
Maybe you could try something like this (values 1 and 0 should be changed to the ones that you use):
success: function(result){
if(result === '1'){
// do something
}
else
return false;
}
just use asunc false it can work fine i have implemented like that only
just try it
$.ajax({
url: '' + $website_url + 'queries/voorraad_berekenen.php',
type: 'post',
data: {
aantal: $(this).parent('form').children('.quantity').val(),
item_number_1: $(this).parent('form').children('.item_number_1').val()
},
async: false, //=>>>>>>>>>>> here >>>>>>>>>>>
success: function(result) {
return false;
}
});
it is working fine try it once
<form action="yourpage" method="post" onsubmit="return matchpass();">
<div>
<label> Name</label>
<input type="text" name="name" id="name">
</div>
<div>
<label> Email ID</label>
<input type="email" name="email" id="email">
</div>
<div>
<label> Mobile No</label>
<input type="text" name="mob" maxlength="10" onkeyup="check_if_exists();" autocomplete="off" id="mob">
</div>
<div>
<button type="button" >Send</button>
</div>
<span id="err"></span>
<div>
<label> OTP</label>
<input type="password" name="otp" id="otp" maxlength="6" placeholder="****">
<span id="err2"></span>
</div>
<div>
<input type="reset" value="Reset" class="reset-btn">
<input type="submit" name="submit" id="submit" value="Submit" >
</div>
</form>
<input type="hidden" id="otpcheck"/>
<script>
function matchpass()
{
$.ajax({
type:"post",
url: "yourpage",
data:{ mobile:mob,otp:otp},
success:function(data)
{
if(data==1)
{
document.getElementById("otpcheck").value=1; //important
}else{
document.getElementById("err2").style.color = "red";
document.getElementById("err2").innerHTML = "invalid OTP Number ";
document.getElementById("otpcheck").value=0; //important
}
}
});
if(document.getElementById("otpcheck").value==0){
return false;
}
}
I face this problem. then i found the actual solution. use async : false, inside ajax call
function thisisavailavailusername(uname){
var dataString = 'username='+ uname.value;
var trueorfalse = false;
$.ajax({
type: "post",
url: "/BloodBook/checkavailableusername",
data: dataString,
cache: false,
async : false, //user this then everything ok
success: function(html){
if(html=="true"){
$('#validusername').html('Available');
trueorfalse = true;
}else{
$('#validusername').html('Not Available');
trueorfalse = false;
}
},
error: function() {
alert("Something Wrong...");
}
});
return trueorfalse;
}
Related
I have a form, whose values I am trying to post after serializing to a controller via ajax. Below is the form:
Form
<form method="post" id="frm_reg_student" class="stop-propagation registration-form">
<input type="hidden" name="register[user_type]" value="2">
<input type="hidden" name="register[status_id]" value="1">
<div class="stud_register_error"></div>
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<label for="input" class="control-label font-12 font-blue">First Name <span>*</span></label>
<input type="text" class="form-control" required="required" placeholder="Your First Name" name="register[first_name]">
</div>
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<label for="input" class="control-label font-12 font-blue">Last Name <span class="req">*</span></label>
<input type="text" class="form-control" required="required" placeholder="Your Last Name" name="register[last_name]">
</div>
</div>
</div>
</form>
js
$(".js-btn_reg_student").click(function(e){
e.preventDefault();
var serialData= $( "#frm_reg_student" ).serialize();
alert(serialData);
$.ajax ({
type: "POST",
url: '<?=base_url()?>index.php/register/signup/',
data: serialData,
success: function(result) {
alert(result);
output = JSON.parse(result);
if(result) {
if( 'success' == output.type ) {
location.href = output.location;
} else {
$('.stud_register_error').html(output.message);
}
}
}
});
});
Controller
public function signup(){
if($_SERVER["REQUEST_METHOD"]=="POST"){
print_r($_POST);
}
}
Here, $_POST comes out to be empty, it never goes inside the loop. If you see in the JS, I have included an alert with the serialized data, which even shows me the proper serialized data. I believe it is something wrong with the way I am posting it.
Any help!
Try on ajax
$(".js-btn_reg_student").click(function(e){
var formdata = $( "#frm_reg_student" ).serialize();
$.ajax({
type: "post",
url: "<?php echo base_url('register/signup');?>",
data: formdata,
dataType: 'json',
success: function(json) {
if (json[success]) {
alert(json['post']);
} else {
}
}
});
e.preventDefault();
});
And controller
public function signup() {
$data = array(
'success' => false,
'post' => ''
);
if ($this->input->server("REQUEST_METHOD") == 'POST')
{
$data['success'] = true;
$data['post'] = $_POST;
}
echo json_encode($data);
}
Try
$('#js-btn_reg_student').click(function () {
$.ajax ({
type: 'post',
url: '<?php echo base_url(); ?>index.php/test/signup/',
data: $('#frm_reg_student').serialize(),
dataType: 'json',
success: function(result) {
if(result.status == 'success')
{
alert(result.name);
}
else
{
alert(result.status);
}
}
});
});
And in Controller
public function signup ()
{
if($this->input->post())
{
$data = array('status' => 'success');
$data['name'] = $this->input->post('register[first_name]');
}
else
{
$data = array('status' => 'failed');
}
echo json_encode($data);
}
Try it and let me know if it works or not :)
Try to use below code.
$(".js-btn_reg_student").click(function(e){
e.preventDefault();
var serialData= $( "#frm_reg_student" ).serialize();
alert(serialData);
$.ajax ({
url: '<?=base_url()?>index.php/register/signup/',
method : 'POST',
data: serialData,
success: function(result) {
if(result) {
if( 'success' == output.type ) {
location.href = output.location;
} else {
$('.stud_register_error').html(output.message);
}
}
}
});
});
I think all the answers were correct in their own way. I figured out that it might be possible that it is not getting the DOM upon submit so I simply put it in document.ready and it worked!
Thanks
I'm trying to have this form submitted and it works. However, i can't get to show a "success" message after clicking submit button.
function signup() {
var postData={ "service" :$('input[name=service]').val(), "ent_id": $('input[name=ent_id]').val(), "name": $('input[name=name]').val(), "mail_address" : $('input[name=mail_address]').val(), "password": $('input[name=password]').val()};
postData = JSON.stringify(postData);
$.ajax({
url: 'http://domain.com/api?service=security&action=signup&request=' + postData,
type: 'GET',
});
return false;
}
Here's the form:
<form onsubmit="return signup()">
Name:<input type="text" name="name">
Email:<input type="text" name="mail_address">
Password: <input type="password" name="password" >
<input type="submit" name="submit" value="Submit">
<input type="hidden" name="service" value="wf" />
<input type="hidden" name="ent_id" value="null" />
</form>
Could someone here help me out with the codes?
This should do what you want it to do. All you need to do is use the success / error callbacks that come with jQuery.
function signup() {
var postData={
"service": $('input[name=service]').val(),
"ent_id": $('input[name=ent_id]').val(),
"name": $('input[name=name]').val(),
"mail_address" : $('input[name=mail_address]').val(),
"password": $('input[name=password]').val()
};
postData = JSON.stringify(postData);
$.ajax({
url: 'http://domain.com/api?service=security&action=signup&request=' + postData,
type: 'GET',
success: function() {
alert('successfully submitted');
},
error: function() {
alert('an error has occurred.');
}
});
return false;
}
$("form[name='myForm']").submit(function(e) {
var postData={ "service" :$('input[name=service]').val(), "ent_id": $('input[name=ent_id]').val(), "name": $('input[name=name]').val(), "mail_address" : $('input[name=mail_address]').val(), "password": $('input[name=password]').val()};
postData = JSON.stringify(postData);
$.ajax({
url: 'http://domain.com/api?service=security&action=signup&request=' + postData,
type: 'GET',
success: function(data){
//alert(data);
alert("success message");
}
});
return false;
}
<form id="myForm" name="myForm" accept-charset="utf-8">
I've been looking for so long to a solution other than data-ajax="false" because that didn't work for me.
Anyway, in my Phonegap app, when I use jquery mobile to submit a form, I need to run it through the regular on submit function in jquery to manipulate it some before it goes to the server.
I'm encrypting it for the first time on the phone before it goes to the DB to be more secure.
Anyway, before I needed to switch to the multi page method with JQM, I could submit a form and it would submit no problem.
But, when I changed only the HTML to be a multi page setup, all I get is a refresh to the login screen, the first page, regardless if I'm on that or registering.
Also, in testing, if I try to alert anything, inside the function or no, nothing appears, so that route of testing doesn't work for me.
The most important thing is for me to get the forms submitting.
One more thing, when I put the code in jsfiddle, everything, the alert and all, works perfectly.
So I don't know if it is phonegap or not.
JS Fiddle Link - http://jsfiddle.net/copilot0910/mVgLJ/
Code
HTML
<h1>Login</h1>
<label for="uname">Username:</label>
<input type="text" name="uname" id="uname" value="" autocomplete="off" autocapitalize="off" />
<label for="pword">Password:</label>
<input type="password" name="pword" id="pword" value="" />
<input type="submit" value="Login" name="login_submit_btn" id="login_submit_btn" />
</form>
Go Register
</div>
</div>
<div id="register" data-role="page">
<div data-role="content">
<form id="register_form">
<h1>Register</h1>
<label for="uname_reg">Wanted Username:</label>
<input type="text" name="uname_reg" id="uname_reg" value="" autocomplete="off" autocapitalize="off" />
<label for="pword_reg">Password:</label>
<input type="password" name="pword_reg" id="pword_reg" value="" />
<label for="email_reg">Email:</label>
<input type="email" name="email_reg" id="email_reg" value="" autocomplete="off" autocapitalize="off" />
<label for="fname_reg">First Name:</label>
<input type="text" name="fname_reg" id="fname_reg" value="" autocomplete="off" autocapitalize="off" />
<label for="lname_reg">Last Name:</label>
<input type="text" name="lname_reg" id="lname_reg" value="" autocomplete="off" autocapitalize="off" />
<input type="submit" value="Register" />
Go Login
You Accept our Terms
</form>
</div>
</div>
</div>
</body>
jQuery
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
$(document).ready(function () {
$("#login_form").submit(function () {
event.preventDefault();
alert("Login Alert");
$("#uname").blur();
$("#pword").blur();
$("#uname_reg").blur();
$("#pword_reg").blur();
$("#email_reg").blur();
$("#fname_reg").blur();
$("#lname_reg").blur();
var NoHashPwd = $("#pword").val();
var pwd = hex_sha512(NoHashPwd);
var usrname = $("#uname").val();
var loginData = {
"uname": usrname,
"p": pwd
};
$.ajax({
type: "POST",
url: "Not Telling",
data: loginData,
cache: false,
async: false,
dataType: "json",
success: function (resp) {
if (resp.msg === "good") {
doGeolocate();
} else {
alert(resp.msg);
}
$("#uname").val("");
$("#pword").val("");
$("#uname_reg").val("");
$("#pword_reg").val("");
$("#email_reg").val("");
$("#fname_reg").val("");
$("#lname_reg").val("");
return false;
}
});
});
$("#register_form").submit(function () {
event.preventDefault();
alert("Login Alert");
$("#uname").blur();
$("#pword").blur();
$("#uname_reg").blur();
$("#pword_reg").blur();
$("#email_reg").blur();
$("#fname_reg").blur();
$("#lname_reg").blur();
var NoHashPwd = $("#pword_reg").val();
var p = hex_sha512(NoHashPwd);
var uname = $("#uname_reg").val();
var fname = $("#fname_reg").val();
var lname = $("#lname_reg").val();
var email = $("#email_reg").val();
var regData = {
"uname": uname,
"p": p,
"fname": fname,
"lname": lname,
"email": email
};
$.ajax({
type: "POST",
url: "Not Telling",
data: regData,
cache: false,
async: false,
dataType: "json",
success: function (resp) {
if (resp.flag === "good") {
doGeolocate();
} else {
alert(resp.flag);
}
$("#uname").val("");
$("#pword").val("");
$("#uname_reg").val("");
$("#pword_reg").val("");
$("#email_reg").val("");
$("#fname_reg").val("");
$("#lname_reg").val("");
return false;
}
});
});
});
}
By the way, the extra deviceready function is for phonegap, so leave that be. Hasn't caused problems ever.
You are forgotting the RETURN FALSE; on your submit(); function.
You've placed it inside the Ajax callback, you need to put it on the end of your submit code, like this:
$("#login_form").submit(function () {
event.preventDefault();
alert("Login Alert");
$("#uname").blur();
$("#pword").blur();
$("#uname_reg").blur();
$("#pword_reg").blur();
$("#email_reg").blur();
$("#fname_reg").blur();
$("#lname_reg").blur();
var NoHashPwd = $("#pword").val();
var pwd = hex_sha512(NoHashPwd);
var usrname = $("#uname").val();
var loginData = {
"uname": usrname,
"p": pwd
};
$.ajax({
type: "POST",
url: "Not Telling",
data: loginData,
cache: false,
async: false,
dataType: "json",
success: function (resp) {
if (resp.msg === "good") {
doGeolocate();
} else {
alert(resp.msg);
}
$("#uname").val("");
$("#pword").val("");
$("#uname_reg").val("");
$("#pword_reg").val("");
$("#email_reg").val("");
$("#fname_reg").val("");
$("#lname_reg").val("");
return false;
}
});
return false; // avoid to execute the actual submit of the form.
});
There is nothing wrong with your code, the "deviceready" event only fires when the DEVICE is ready.
The alerts are working now. For testing use the following:
$(document).ready(function () {
"use strict";
onDeviceReady();
});
I took the liberty of error checking your code and making it Lint compliment.
Please find the full code bellow P.S Declare functions before you call them that's way "deviceready" call is at the end.
/*jslint browser: true*/
/*global $, jQuery, alert, hex_sha512 */
function onDeviceReady() {
"use strict";
$(document).ready(function () {
$("#login_form").submit(function () {
event.preventDefault();
alert("Login Alert");
$("#uname").blur();
$("#pword").blur();
$("#uname_reg").blur();
$("#pword_reg").blur();
$("#email_reg").blur();
$("#fname_reg").blur();
$("#lname_reg").blur();
var NoHashPwd = $("#pword").val(),
pwd = hex_sha512(NoHashPwd),
usrname = $("#uname").val(),
loginData = {
"uname": usrname,
"p": pwd
};
$.ajax({
type: "POST",
url: "Not Telling",
data: loginData,
cache: false,
async: false,
dataType: "json",
success: function (resp) {
if (resp.msg === "good") {
alert("good");
//doGeolocate();
} else {
alert(resp.msg);
}
$("#uname").val("");
$("#pword").val("");
$("#uname_reg").val("");
$("#pword_reg").val("");
$("#email_reg").val("");
$("#fname_reg").val("");
$("#lname_reg").val("");
return false;
}
});
});
$("#register_form").submit(function () {
event.preventDefault();
alert("Login Alert");
$("#uname").blur();
$("#pword").blur();
$("#uname_reg").blur();
$("#pword_reg").blur();
$("#email_reg").blur();
$("#fname_reg").blur();
$("#lname_reg").blur();
var NoHashPwd = $("#pword_reg").val(),
p = hex_sha512(NoHashPwd),
uname = $("#uname_reg").val(),
fname = $("#fname_reg").val(),
lname = $("#lname_reg").val(),
email = $("#email_reg").val(),
regData = {
"uname": uname,
"p": p,
"fname": fname,
"lname": lname,
"email": email
};
$.ajax({
type: "POST",
url: "Not Telling",
data: regData,
cache: false,
async: false,
dataType: "json",
success: function (resp) {
if (resp.flag === "good") {
//doGeolocate();
alert("success");
} else {
alert(resp.flag);
}
$("#uname").val("");
$("#pword").val("");
$("#uname_reg").val("");
$("#pword_reg").val("");
$("#email_reg").val("");
$("#fname_reg").val("");
$("#lname_reg").val("");
return false;
}
});
});
});
}
$(document).ready(function () {
"use strict";
onDeviceReady();
});
document.addEventListener("deviceready", onDeviceReady, false);
I'm having a problem with my code...
function retmsg isn't returning a value if javascript is implemented
<div id="pop">
Elunika
<div class="txt">Its the way to connect with your friends.</div>
<form action="login.php" method="post" id="login">
<input id="email" placeholder="E-mail" type="text" name="em" />
<input id="email" placeholder="Password" type="password" name="pwd"/>
<div class="txt1"><input type="checkbox" name="check" />Keep me logged in | Forgot Password ?</div>
<input id="loginButton" type="submit" value="Login" name="log" />
</form>
<span>Register</span>
<div id="error1"></div>
<div id="termdiv1"></div>
</div>
value returned from retmsg() function should display in div id="error"
login script...
if (isset($c))
{
$q = mysql_query("select * from registeration where email='$a' and password='$b'");
$r = mysql_num_rows($q);
if($r)
{
$_SESSION["Authenticated"] = 1;
$_SESSION['id'] = $a;
echo retmsg(1,"profile.php");
}
else
{
$_SESSION["Authenticated"] = 0;
die (retmsg(0,"Incorrect Information"));
}
}
function retmsg($status,$txt)
{
return '{"status":'.$status.',"txt":"'.$txt.'"}';
}
javascript code...
$(document).ready(function(){
$('#login').submit(function(e) {
att();
e.preventDefault();
});
$('#regForm').submit(function(e) {
register();
e.preventDefault();
});
});
function register()
{
hideshow('loading',1);
error(0);
$.ajax({
type: "POST",
url: "submit.php",
data: $('#regForm').serialize(),
dataType: "json",
success: function(msg){
if(parseInt(msg.status)==1)
{
window.location=msg.txt;
}
else if(parseInt(msg.status)==0)
{
error(1,msg.txt);
}
hideshow('loading',0);
}
});
}
function hideshow(el,act)
{
if(act) $('#'+el).css('visibility','visible');
else $('#'+el).css('visibility','hidden');
}
function error(act,txt)
{
hideshow('error',act);
if(txt) {
$('#error').html(txt);
$('#regpop').css('height','419px');
$('#termdiv').css('margin-top','10px');
}
if(!txt) {
$('#regpop').css('height','400px');
$('#termdiv').css('margin-top','-20px');
}
}
function att()
{
hideshow1('loading',1);
error1(0);
$.ajax({
type: "POST",
url: "login.php",
data: $('#login').serialize(),
dataType: "json",
success: function(retmsg){
if(parseInt(retmsg.status)==1)
{
window.location=retmsg.txt;
}
else if(parseInt(retmsg.status)==0)
{
error1(1,retmsg.txt);
}
hideshow1('loading',0);
}
});
}
function hideshow1(el,act)
{
if(act) $('#'+el).css('visibility','visible');
else $('#'+el).css('visibility','hidden');
}
function error1(act,txt)
{
hideshow1('error1',act);
if(txt) {
$('#error1').html(txt);
$('#pop').css('height','290px');
$('#termdiv1').css('margin-top','50px');
}
if(!txt) {
$('#pop').css('height','270px');
$('#termdiv1').css('margin-top','-35px');
}
}
in javascript code
retmsg should return txt parameter to the att function.....
att function is passing retmsg.txt value to the error1 function
part of the function error1 is working as retmsg.txt is not returning value...
rest of the javascript code is working fine...
rest of the code is same as of this...
only function names are different....
ANSWER *ANSWER* ANSWER
javascript code was all correct
made changes in the login script
$q = mysql_query("select * from registeration where email='$a' and password='$b'");
$r = mysql_num_rows($q);
if(!$r)
{
$_SESSION["Authenticated"] = 0;
die (retmsg(0,"Incorrect Information"));
}
else
{
$_SESSION["Authenticated"] = 1;
$_SESSION['id'] = $a;
echo retmsg(1,"profile.php");
}
function retmsg($status,$txt)
{
return json_encode(array('status' => $status, 'txt' => $txt));
}
I am trying to send a newsletter subscription request to Magento, but It returns null and nothing happens.
I've searched around and found very different URLs to post the request. And also grabbed the code from the file from base template.
In fact, maybe I am not sending the correct parameters or whatever.
This is the code in use:
<form method="post" id="newsletter-form">
<input type="hidden" class="url" value="<?php echo $this->getUrl('newsletter/subscriber/new') ?>">
<input id="newsletter" type="text" name="email" placeholder="RECEBA NOVIDADES" value="" class="input-text myFormInput" maxlength="128" autocomplete="off" style="width: 188px !important">
<button type="submit" id="ajax-newsletter-submit" title="CADASTRAR"
class="button myFormButton" style="margin-top:20px;margin-left: -107px !important;width: 103px">CADASTRAR</button>
</div>
</form>
Javascript:
var newsletterSubscriberFormDetail = new VarienForm('newsletter-form');
$j(function() {
$j("#ajax-newsletter-submit").click(function() {
var email =$j("#newsletter").val();
var url=$j(".url").val();
var dataString = 'email='+ email;
if(email=='') {
$j("#newsletter").focus();
} else {
var a = email;
var filter = /^[a-zA-Z0-9_.-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{1,4}$/;
if(filter.test(a)){
$j.ajax({
type: "POST",
url: url,
data: dataString,
success: function(){
alert('Assinatura realizada com sucesso!');
$j("#newsletter").val('');
}
});
} else {
$j("#newsletter").focus();
}
}
return false;
});
});
Try this code,
var val_form = new VarienForm('your form id');
jQuery("#your form id").submit(function(e)
{
if (val_form.validator && val_form.validator.validate())
{
var postData = jQuery(this).serializeArray();
var formURL = jQuery(this).attr("action");
jQuery.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
alert('success');
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('Failure');
}
});
this.reset(); //form field reset
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
}
});