I'm developing a mobile app with phonegap and I have a form to register new users. In the broswer(chrome and firefox), the form works fine when correctly
filled, and show errors if something wrong. I have an alert('work!'); in the start of function to check if was called, in browsers the alert appears but in the app no. What can be?
Ps: I already have <access origin=""> to my website where's the php file of form is.
EDIT:
the form:
<form id="cadastro" method="post">
<input type="text" style="height:30px;margin-bottom:10px;margin-top:10px;font-size:18px" name="nome" id="textinput-2" placeholder="Nome" required>
<input type="text" style="height:30px;margin-bottom:10px;font-size:18px" name="email" id="textinput-1" placeholder="Email" required>
<div id="email_erro"></div>
<input type="password" style="height:30px;margin-bottom:10px;font-size:18px" name="senha" id="password" placeholder="Senha" autocomplete="off" required>
<input type="password" style="height:30px;margin-bottom:10px;font-size:18px" name="repetir_senha" id="re_password" placeholder="Repetir senha" autocomplete="off">
<div id="senha_erro"></div>
<fieldset data-role="controlgroup" style="margin-left:5%" data-type="horizontal" data-mini="true">
<input type="radio" name="sexo" id="radio-choice-c" value="m" checked="checked" required>
<label for="radio-choice-c">Masculino</label>
<input type="radio" name="sexo" id="radio-choice-d" value="f" required>
<label for="radio-choice-d">Feminino</label>
</fieldset>
<div style="margin-left:3.5%;margin-right:4%;">
<input type="checkbox" name="newsletter" id="checkbox-mini-0" value="1" data-mini="true">
<label for="checkbox-mini-0">Quero receber as ofertas e novidades</label>
<input type="checkbox" name="termo" id="checkbox-mini-1" data-mini="true" required>
<label for="checkbox-mini-1">Aceito os Termos de Uso e Política de privacidade</label>
<button type="submit" class="ui-btn ui-shadow ui-corner-all" id="termo" style="float:none;margin-left:2%">Criar conta</button>
</div>
</form>
the function:
<script>
alert('entrou no script');
$('#cadastro').submit(function(){
var valor = $('#cadastro').serialize();
$.ajax({
type: 'POST',
url: 'cadastro',
dataType: "json",
data: valor
}).success(function(response){
alert('retornou função');
if (response.sucesso) {
window.localStorage["email"] = response.dados.email;
window.localStorage["nome"] = response.dados.nome;
window.localStorage["sexo"] = response.dados.sexo;
window.localStorage["id"] = response.dados.id;
//window.localStorage["UID"] = data.uid;
window.location = "logado.html";
} else {
alert("Verifique seus dados");
$('#email_erro').html(response.erro_email);
$('#senha_erro').html(response.erro_repetir_senha);
//window.location("main.html");
}
});
return false;
});
</script>
I believe that your problem is because you are running your javascript before the phonegap framework has loaded. Try using the event listener below, and then place your javascript in the corresponding function.
document.addEventListener("deviceReady", deviceReady, false);
function deviceReady() {
// PhoneGap has loaded - your code goes here
}
Related
I have a form that opens in a modal.
And the submit is not working, it is not calling the action.
I have set the method post, and action is supposed to call a php file.
However, it isnt working at all.
Here is the code, and you can test it here:
http://mentores.in/comprar.html
Click in "comprar" to open the modal.
<section id="first-step" class="wc-billing-step">
<div class="woocommerce-billing-step-one">
<h4>
Dados do Participante
</h4>
<form id="contact-form" method="post" action="enviar_inscricao.php">
<input type="text" name="nome" placeholder="Nome do participante">
<input type="text" name="cpf" placeholder="CPF">
<input type="text" name="nasc" placeholder="Data de Nascimento" onkeyup="
var date = this.value;
if (date.match(/^\d{2}$/) !== null) {
this.value = date + '-';
} else if (date.match(/^\d{2}\-\d{2}$/) !== null) {
this.value = date + '-';
}" maxlength="10">
<input type="email" name="email" placeholder="E-mail">
<input type="text" name="celular" placeholder="Celular">
<input type="text" name="end" placeholder="Endereço">
<input type="text" name="cid" placeholder="Cidade">
<input type="text" name="esta" placeholder="Estado">
<input type="text" name="cep" placeholder="CEP">
<p>Caso seja menor de idade</p>
<input type="text" name="resp" placeholder="Nome do responsável">
<input type="text" name="tel" placeholder="Telefone">
<p>Caso o pagamento seja em nome de terceiro</p>
<input type="text" name="pagseg" placeholder="Nome do titular do cartão">
<!-- <input type="text" placeholder="Produtores"> -->
<select type="text" name="indi" value="" class="form-control" placeholder="Quem te indicou?">
<option value="Escolha">Escolha uma opção</option>
<option value="Marcelo Caldas">Marcelo Caldas</option>
<option value="Nenhum desses">Nenhum desses</option>
</select>
<input class="price-btn subm" type="submit" name="submit-form" value="Continuar" id="accept" />
</form>
</div>
</section>
I need that form to call the php page in the action.
You had defined an on click behaviour on price-btn to open the modal.
$('.price-btn').on('click', function(e) {
So you need to be more specific with your selectors because your Form hast the same selector.
Either use this url like: "/enviar_inscricao.php " (add a slash to the front),
or enter the full url.
When I submit a form using the attached code, instead of the message appearing in the div, the screen is refreshing itself and it is holding the completed form in the browser cache. I have obviously got it wrong somewhere and would be grateful if someone could point out my error. I have posted the relevant code, but if there is something I have missed, then please let me know.
In firebug, I can see the correct data that is being returned in the post tab.
I wasn't sure of the best place to post, so if this is incorrect, admin, please amend as you see fit. many thanks.
jquery code
//Begin function to submit report form
$(function(){
$(".frmreport").submit(function(){
var formdata = $(this).serialize();
$ajax({
type: "POST",
url: "../frm10010.php",
data: formdata,
dataType: "json",
success: function(msg){
$("#report_result").html("You have succesfully submitted your report. Thank you.");
}
});
return false;
});
});
// End function to submit report form
frm10010.php
<?php
$dept = mysql_real_escape_string($_POST['dept']);
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$position = mysql_real_escape_string($_POST['position']);
$feedback = mysql_real_escape_string($_POST['feedback']);
$form = array('dept'=>$dept, 'name'=>$name, 'email'=>$email, 'position'=>$position, 'feedback'=>$feedback);
$result = json_encode($form);
echo $result;
?>
html
<div id="report_result"></div>
<div id="formShow">
<form class=frmreport" method="post" class="webform">
<fieldset>
<legend><span class="subtitle">Submit Technical Report</span></legend>
<label for="dept">Department</label>
<input id="dept" name="dept" class="text" type="text" />
<label for="name">Full Name:</label>
<input id="name" name="name" class="text" type="text" />
<label for="email">Email address:</label>
<input id="email" name="email" class="text" type="text" />
<label for="position">Position:</label>
<input id="position" name="Position" class="text" type="text" />
<label for="feedback">Problem:</label>
<textarea name="feedback" cols="22" rows="5"></textarea>
</fieldset>
<input class="submit" type="submit" name="submit" value="Submit Report" />
<input class="cancel" type="reset" name="cancel" value="Clear Report" />
</form>
</div>
You have couple of errors here
$ajax({ should be $.ajax({
Second you have an error in the form class
<form class=frmreport" method="post" class="webform">
should be
<form class="frmreport" method="post" class="webform">
Don't use
$(".frmreport").submit(function(){
Instead use
$("#sub_btn").click(function(){
And in html
<input class="submit" type="submit" name="submit" value="Submit Report" />
Change it to
<input class="submit" id="sub_btn" type="button" name="submit" value="Submit Report" />
Another way to do it making submit handler false. But above solution will work here. There is also . is missing in ajax call.
I want upload a file with jquery ajax and php using forData() with this code:
var data = new FormData();
data.append('image',document.getElementById('uFile').files[0]);
data.append('tag','saveDocument');
data.append('data',$('#saveDocument').serializeArray());
$.ajax({
url: url,
type: 'post',
data: data,
cache: false,
contentType:false,
dataType: 'json',
processData: false,
success: function (data) {
setAlert("Documento guardado correctamente!",success);
}, error: function() {
setAlert("Ha ocurrido un error al guardar!",error);
}
});
return false;
This line contains all data of fields in my form:
data.append('data',$('#saveDocument').serializeArray());
But in PHP I can't access to that data and I want access to data of form to insert on a table, do you know what's the problem?
Html Form
<form id="saveDocument" enctype="multipart/form-data" method="post">
<p><i>Todos los campos son requeridos!</i></p>
<p>
<input id="uName" class="uName span5" name="uName" type="text" placeholder="Nombre completo" required/>
</p>
<p>
<input id="uEmail" class="uEmail span5" name="uEmail" type="email" placeholder="E-mail" required/>
</p>
<p>
<select id="uDept" class="uDept span5" name="uDept" type="text" required>
<option value="0">Seleccione departamento</option>
<option value="1">Dirección</option>
<option value="2">Recursos Humanos</option>
<option value="3">Oficina</option>
</select>
</p>
<p>
<input id="uIssue" class="uIssue span5" name="uIssue" type="text" placeholder="Asunto" required/>
</p>
<p>
<textarea id="uComment" class="uComment" name="uComment" placeholder="Comentario (Máximo 30 caracteres)" required></textarea>
</p>
<p>
<select id="uUrgency" class="uUrgency span5" name="uUrgency" type="text" required>
<option value="0">Seleccione urgencia</option>
<option value="1">Normal</option>
<option value="2">Alta</option>
<option value="3">Urgente</option>
</select>
</p>
<p>
<input id="uFile" class="uFile span5" name="uFile" type="file" required/>
<input id="nameFile" class="nameFile span5" name="nameFile" type="text" placeholder="Click para seleccionar el archivo" onClick="$('.uFile').click();"/>
</p>
<p>
<input class="btn btn-danger" type="reset" value="Limpiar"/>
<input id="sendFile" class="btn btn-primary" type="submit" value="Guardar"/>
</p>
The below image is taken from developers tool of chrome:
You can pretty easy. Take a look at these posts:
specially for images with demo
just all file type uploads with validation
I've got a registration form setup which works fine on all browsers...except Safari.
I thought it should be a problem that deals with Javascript, as it mostly is. But after I turned Javascript off in Safari, there's still no data being posted.
The form is live on:
http://tpgrf.nl/testserver/alpha/account/registreer/
I've added this text on top of the page, for testing, to make sure if data has been posted or not.
if($_SERVER['REQUEST_METHOD'] == 'POST'){
echo 'post';
}else{
echo 'niets gepost';
}
Any thoughts where to look for the answer?
EDIT: Here's the form (output HTML)
<form name="registerform" id="registerform" action="http://tpgrf.nl/testserver/alpha/account/registreer/" method="post">
<script type="text/javascript">
jQuery(document).ready(function($) {
//Since we want users to login with there email; there's no need to also register a username. Therefore the username field = email field
$("#user_login").live('change', function(){
$('#user_email').val($("#user_login").val());
});
//Display fields, depending on the selected role
$('#role').live('change', function(){
if($('#role').val() === 'docent'){
$('#messageRegisterDocent').show();
$('#pKlas').hide();
}else{
$('#messageRegisterDocent').hide();
$('#pKlas').show();
}
});
//The json call to automcplete School
var ajaxurl = 'http://tpgrf.nl/testserver/alpha/wp-admin/admin-ajax.php';
$("#school").autocomplete({
delay: 0,
minLength: 1,
source: function(req, response){
$.getJSON('http://tpgrf.nl/testserver/alpha/wp-admin/admin-ajax.php?callback=?&action=school_autocomplete', req, response);
},
select: function(event, ui){
$('#school').val(ui.item.label);
$('#school_id').val(ui.item.school_id);
}
});
});
</script>
<p>
<input type="hidden" name="user_email" id="user_email" class="input" value="" size="20" />
<p>
<label for="user_login">E-mail</label>
<input type="email" name="user_login" id="user_login" class="input" value="" size="20" />
</p>
<p>
<label>Voornaam</label>
<input id="first_name" type="text" size="25" value="" name="first_name" />
</p>
<p>
<label>Achternaam</label>
<input id="last_name" type="text" size="25" value="" name="last_name" />
</p>
<p>
<label>Ik ben...</label>
<select name="role" id="role">
<option value="">...selecteer</option>
<option value="leerling" >Leerling</option>
<option value="docent" >Docent</option>
</select>
<p class="message" id="messageRegisterDocent" style="display:none;"><strong>Let op:</strong> registreer met uw e-mailadres van de school waar u werkzaam bent. <br />Voor een aantal functies vindt namelijk handmatige autorisatie plaats; dit is niet mogelijk met een privé e-mailadres.</p>
</p>
<p>
<label>Mijn school</label>
<input type="text" id="school" class="autoComplete" size="25" value="" name="school" />
<input type="hidden" id="school_id" name="school_id" value="">
</p>
<p id="pKlas"style="display:none;">
<label>Mijn klas</label>
<input type="text" id="klas" size="25" value="" name="klas" />
</p>
<p id="reg_passmail">U zult een wachtwoord per e-mail ontvangen.</p>
<p class="submit">
<input type="submit" name="wp-submit" id="wp-submit" value="Registratie" />
of Ik heb al een account...
<input type="hidden" name="redirect_to" value="/testserver/alpha/account/login/?checkemail=registered" />
<input type="hidden" name="instance" value="" />
</p>
</form>
Your problem might be caused by the following line of code:
<input type="submit" name="wp-submit" id="wp-submit" value="Registratie" />
You wrap the submit button tag inside an 'a' tag which is pointing to an empty URL and causes a link to the current page only. It might be that Safari does not parse this wrapped button well, and instead prefers the A link over the submit button.
Unwrapping the 'input' tag and changing the code to:
<input type="submit" name="wp-submit" id="wp-submit" value="Registratie" />
might work.
In a facebook iframe page (not tab), I'd like to post data to an external API using cURL, but I would prefer if my form page didn't reload.
I'd like to have some jquery ajax happening ("submitting data" message on submission of the form and a success message on success of the curl_exec). I was thinking of creating a hidden iframe with a duplicate form and update values in that form on change events, but i don't know quite how I'd implement that exchange between PHP and jquery.
Is there a better way? Here's the code I'm working on:
UPDATED CODE TO RETURN FALSE --
Does not submit form data.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body class="fb_canvas-resizable <?php print $body_classes; ?>">
<?php echo $message; ?>
<div class="container">
<div class="header"></div>
<div class="wrapper">
<div class="content">
<div class="left">
<h1>Sign Up to Sign Off</h1>
<form name="signoff" action="curlsub.php" method="post">
<input id="api" type="hidden" name="API_KEY" value="key">
<div class="innerleft">
<input id="fname" type="text" name="fname" class="inputs" tabindex="1" /></br />
<label for="fname">First</label></br /></br /></br />
<input type="text" name="email" class="inputs" tabindex="3" /></br />
<label id="email" for="email">Email</label></br /></br /></br />
<label for="gender">Gender</label></br /></br />
<label for="gender">Age</label></br /></br /></br />
<label for="gender">Income</label></br /></br /></br />
</div>
<div class="innerright">
<input id="lname" type="text" name="lname" class="inputs" tabindex="2" /></br />
<label for="lname">Last</label></br /></br /></br />
<input id="password" type="password" name="password" class="inputs" tabindex="4" /></br />
<label for="email">Password</label></br /></br /></br />
<input type="radio" name="sex" value="male" selected="selected" tabindex="5" /> Male
<input type="radio" name="sex" value="female" tabindex="6" /> Female</br /></br />
<select name="age" tabindex="7" >
<option value=""></option>
<option value="baby">Baby</option>
<option value="teen">Teen</option>
<option value="young">Young</option>
<option value="old">Old</option>
</select><br /><br />
<select name="income" tabindex="8">
<option value=""></option>
<option value="none">None</option>
<option value="some">Some</option>
<option value="okay">Okay</option>
<option value="tons">Tons</option>
</select><br /><br />
<input id="zip" type="text" name="c5" class="zip" tabindex="9" /></br />
<label for="c5">Zip Code</label></br /></br />
<label for="mformat">Newsletter</label></br /></br />
<input type="checkbox" name="mformat" value="html" selected="selected" tabindex="10" /> HTML (iPhone, iPad, Droid)<br /><br />
<input type="checkbox" name="mformat" value="text" tabindex="11" /> TEXT (Best for Blackberry)
</div>
<div class="button"><input type="image" src="button.jpg" name="submit" value="yes"></div>
</form>
</div>
<div class="right">
<img src="logo.jpg" />
<p>Updating you on today and prepping you for tomorrow.</p>
www.url.com
</div>
<div class="clear">
</div>
<div class="logged clear">
<p>Logged in as Some Guy (not you?)</p>
</div>
</div></div>
<div class="footer"></div>
</div>
<script>
$(document).ready(function() {
//$('div.wrapper').fadeOut(0);
window.fbAsyncInit = function() {
FB.init({appId: 'app', status: true, cookie: true});
FB.Canvas.setSize();
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
});
$('#signoff').submit( function() {
var fname = $("input#fname").val();
var lname = $("input#fname").val();
var email = $("input#email").val();
var password = $("input#password").val();
var dataString = 'fname='+ fname + '&lame=' + lname + '&email=' + email + '&password=' + password;
// alert(dataString);
// return false;
$.ajax({
type: "POST",
url: "curlsub.php",
data: dataString,
success: function() {
//do some stuff
}
});
return false;
});
</script>
</body>
</html>
Currently this will successfully send the data to the external PHP API, but the iframe (or my whole file) reloads on submission (and displays "success" message).
What you want to do is issue an AJAX Post request on the submit event of your form. The success callback of that AJAX Post request should update your UI to alert the user that their post was sucessful.
$('#signoff').submit(
//Ajax post request here
//http://api.jquery.com/jQuery.post/
return false; //this stops your page from refreshing
);
Have you looked at http://api.jquery.com/jQuery.ajax/ or http://api.jquery.com/jQuery.post/
The following code should help you get started.
$.ajax({
type: 'POST',
url: url,
data: data,
success: success
dataType: dataType
});
Where
url is a string containing the URL to which the request is sent.
data is a map or string that is sent to the server with the request.
success is a callback function that is executed if the request succeeds. It should take three arguments: (data, textStatus, XMLHttpRequest)
dataType is the type of data expected from the server.