I have a problem with ajax method. I have a form with two fields, email and password. When I use the label "a" with id = registroAction, I call the ajax method and jump somewhere else.
My code:
<form id="form-registro" class="margen-left-445 absoluto margen-top-40 azul-corporativo">
<p class="bg-success espaciointerior-10 mensaje_activacion" style="display:none"></p>
<p class="bg-danger espaciointerior-10 mensaje_activacion" style="display:none"></p>
<h3 style="text-align: center; color: #044E7C;">Registrate gratis</h3>
<div class="input-group">
<input type="text" id="email" class="input-generico margen-top-10 margen-bottom-5" placeholder="Email" aria-describedby="basic-addon2">
</div>
<div class="input-group">
<input type="password" id="password" class="input-generico margen-top-10 margen-bottom-5" placeholder="Contraseña" aria-describedby="basic-addon2">
</div>
<div class="input-group margen-bottom-20">
<input type="password" class="input-generico margen-top-10 margen-bottom-5" placeholder="Repita contraseña" aria-describedby="basic-addon2">
</div>
<a id="registroAction" class="btn boton-generico margen-left-38">Crear una cuenta gratis</a>
<a href="<?php echo base_url(); ?>" class="btn boton-generico">Cancelar</a>
</form>
Jquery:
<script type="text/javascript">
$(function() {
$("#registroAction").on("click", function(e){
$.ajax({
url: '<?php echo base_url(); ?>frontend/registro/registrarAction',
type: 'POST',
dataType: 'json',
data: {email: $('#email').val(), password: $('#password').val()},
success: function (response) {
if ( response.ok == 'ok' ){
// Establecemos la clase necesario para mostrar el mensaje
var classname = ( response.ok == 'ok' ) ? '.bg-success' : '.bg-danger';
// Ocultamos el resto de mensajes de activacion
$('.mensaje_activacion').hide().html('');
// Mostramos y rellenamos según si ha salido bien o mal
$('.mensaje_activacion' + classname).html(response.responseText).show().fadeOut( 3000 );
} else {
$(location).attr('href',response.url);
}
},
error: function(estado){
console.log(estado)
}
});
});
});
First, your tag should have an href attribute. You can use href="#". Regarding your issue, you need to tell the browser to ignore the default behavior (following links):
$("#registroAction").on("click", function(e) {
e.preventDefault();
....
}
This should work and prevent the weird behavior you are seeing!
This is because of same orgin policy or your url may have redirection in server side. Refer this How to call external url in jquery?