passing form value into php without submitting the form - php

I am building a step by step form. At the first step, people enter their email. Then after they clicked next step, it gets the security question from database.
Here is the problem, is it possible to get data from database without submitting the from? I found people used AJAX. I am new to it. like i have the first step code here:
<div>
step 1
<input type='text' name='email' id='email' maxlength="50" />
nextstepbutton goes here
</div>
and this is step 2 code:
<div>
step 2
<label><?php echo getSecurityQuestion($emailvalue) ?></label>
</div>
How can I pass the value of 'email' into $emailvalue?

give your next button an id. Then say if you're using jquery you could do something along the lines of
$('#next-button').click(function () {
$.get('filename.php', { action: 'get_security_question', email: $('#email').val() }, function (data) {
$('#security_question').val(data['message']);
});
});
over in your php something like
if ($_GET['action'] === 'get_security_question') return "Here's your question for {$_GET['email']}.";
That is very vague and just a general outline but should give you an idea of how it kinda works.

Well you can do it without a form but you would have to use AJAX eg:
<input type="text" name="email" id="email" maxLength="50" />
<input type="button" value="Send" onClick="submitEmail()" />
You would need a JS function like:
function submitEmail(){
var emailAdd = document.getElementByID("email").value ;
// here you would hook into whatever ajax httprequest method you prefer
}

Related

JQuery: event.preventDefault() isn't preventing a refresh

I've been building a mail form that is supposed to pass the information into a php document that handles sanitization and mailing, but I didn't want it to refresh so i decided to use JQuery and AJAX. I'm fairly new to JQuery and haven't used any AJAX before so I am a bit of a rookie when it comes to this...
Even though I have the .submit(function(e){e.preventDefault();}); it still submits the ordinary way and gives an error when it can't find film_mail in the PHP. Which means that it isn't stopping the submit and isn't passing the code to the PHP.
I've tested with alerts and the JQuery works in to the if() but after that some thing goes wrong.
Here is the code that causes the issue (some of the classes and ids are in swedish but that shouldn't cause an error...)
HTML
<div id="film" class="hidden" >
<form id="film_form" action="formular-send.php" method="post">
<input id="film_mail" type="text" name="mail" placeholder="Mail adress">
<input id="film_nr" type="number" name="nr" min="1">
<input id="film_antal" type="number" name="antal" min="1">
<input id="film_namn" type="text" name="namn" placeholder="Namn">
<input id="film_adress" type="text" name="adress" placeholder="Adress">
<input id="film_ort" type="text" name="ort" placeholder="Ort">
<input id="film_postnr" type="text" name="postnr" placeholder="Postnummer">
<textarea id="film_medelande" name="medelande" placeholder="Medelande"></textarea>
<button id="film_submit" type="submit" name="submit">Skicka</button>
<div class="error-mesage" ></div>
</form>
</div>
JQuery
$(document).ready(() => {
var emne = $('#emneid').val();
if (emne == 'film') {
$('#film_form').submit(function(e) {
e.preventDefault();
var mail = $('#film_mail').val();
var nr = $('#film_nr').val();
var antal = $('#film_antal').val();
var namn = $('#film_namn').val();
var adress = $('#film_adress').val();
var ort = $('#film_ort').val();
var postnr = $('#film_postnr').val();
var medelande = $('#film_medelande').val();
var submit = $('#film_submit').val();
$.post('formular-send.php', {
film_mail: mail,
film_nr: nr,
film_antal: antal,
film_namn: namn,
film_adress: adress,
film_ort: ort,
film_postnr: postnr,
film_medelande: medelande,
film_submit: submit,
emne: emne
});
// I heard that .load() had been removed in 3.0 so i tried to use $.post() because I thougt that might work but it sadly didn't...
// but I kept the .load() incase it'd be useful
/*$('#film_form').load('formular-send.php', {
film_mail: mail,
film_nr: nr,
film_antal: antal,
film_namn: namn,
film_adress: adress,
film_ort: ort,
film_postnr: postnr,
film_medelande: medelande,
film_submit: submit,
emne: emne
});*/
});
} else {
}
})
PHP
<?php
$filmmail = $_POST['film_mail'];
?>
If there is anything else that is needed i'd be happy to post it to.
I think $('#emneid').val() returns something different than 'film' and your listener is never attached.
Can you please double check the returned value of $('#emneid').val();
In addition of other comments, I think you need to add the correct name for you button or your PHP form will not work.
<?php
$filmmail = $_POST['film_mail']; //for the moment your need to put $_POST['mail'] because your button is named mail instead of film_mail
?>
Please also take care in production / later use, don't use directly $_POST or your code will be vulnerable from some SQL injection and so on. Take a look at htmlspecialchars function.
Edit :
I think you can just use HTML form and php to post your data, without posting it via JS/Jquery. If you want to have some data validation before sending it, you can just call an event before submit like described in this post : (Validate form before submit jquery)
I think you maybe have a problem with your selector to trigger the function, I don't know the submit function but maybe try with on('submit') or at least it will work with on('click').
$(document).on('click', '#film_submit button[type=submit]', function(e) {
var isValid = $(e.target).parents('form').isValid();
if(!isValid) {
e.preventDefault(); //prevent the default action
}
});
<button> does not have attribute type, but <input> has, try change <button> to <input>
UPD
Where is the tag with id of #emneid?
Try this. Please replace your HTML with my HTML code.
<div id="film" class="hidden" >
<form id="film_form" action="formular-send.php" method="post">
<input id="film_mail" type="text" name="film_mail" placeholder="Mail adress">
<input id="film_nr" type="number" name="film_nr" min="1">
<input id="film_antal" type="number" name="film_antal" min="1">
<input id="film_namn" type="text" name="film_namn" placeholder="Namn">
<input id="film_adress" type="text" name="film_adress" placeholder="Adress">
<input id="film_ort" type="text" name="ort" placeholder="Ort">
<input id="film_postnr" type="text" name="film_ort" placeholder="Postnummer">
<textarea id="film_medelande" name="film_medelande" placeholder="Medelande"></textarea>
<button id="film_submit" type="submit" name="submit">Skicka</button>
<div class="error-mesage" ></div>
</form>
</div>

jQuery making forms disappear and appear after each other

As the title says This is the code that I tried with. The forms must appear one by one because information from previous forms determine how the next ones will look.
$(document).ready(function(){
$('#first_form').submit(function(){
$('#first_form').fadeOut('fast');
$('#second_form').fadeIn('fast');
});
});
<form action="new_patch.php" method="POST" id="first_form">
Title: <input type="text" name="patch" placeholder="Patch 4.20">
<br/>
Number of Champions: <input type="number" name="champ_number" min="1" max="99">
<br/>
<input type="submit" value="submit">
</form>
<form action="new_patch.php" method="POST" id="second_form" style="display: none;" >
<input type="text" value="text">
<input type="submit" value="submit">
<?php
$champ_number = null;
if(isset($_POST['champ_number']))
{
$champ_number = $_POST['champ_number'];
for($champ_number;$champ_number>0;$champ_number--)
{
echo "<br/>Champion ".$champ_number."<input type=\"number\" name=".$champ_number." min=\"1\" max=\"99\">";
}
}
?>
</form>
You're mixing client-side and server-side form code. Submitting the form will reload the page entirely, so from the looks of your code it will fade in the new form when the old form is submitted, but then reload the page so the old form will show again anyway.
You could either:
Let the PHP determine how the next form appears based on the submission of the first form, e.g. if (isset($_POST["First_form_submit"]) { Show second form... }
Probably better and more user-friendly: make the second form appear below once the user has filled in the relevant inputs on the first form before they've submitted
you can use:
$('#first_form').submit(function(){
$('#first_form').fadeOut(function() {
$('#second_form').fadeIn('fast');
});
return false;
});
From the jQuery documentation the syntax is fadeIn( [duration ] [, complete ] ) it accepts a duration and a onComplete callback that you can use to execute the next action when the first is completed.
I did this once too, just add a submit class to the button and make it like this:
<input type="submit" value="submit" class="submit">
Change script to a click function.
$(document).ready(function(event){
event.preventDefault();
$('.submit').click(function(){
$('#first_form').fadeOut(400);
$('#second_form').fadeIn(400);
});
});
PS, also you need to prevent submit default...otherwise it will just submit the form, see this JSfiddle

session_unset and onclick

I'm trying to clear a form that has been populated using PHP sessions.
Your name: <input type="text" name="name"
value="<?php echo($_SESSION['username'])?>" >
Your email address: <input type="text" name="email"
value="<?php echo($_SESSION['email'])?>">
<br>
<textarea name="story" cols="60" rows="10">
<?php echo($_SESSION['story']); ?>
</textarea>
<br>
<input type="submit" value="Submit"/><input type="reset" value="Reset">
The problem is that when I hit the reset button, the form does not clear.
I think I need to use the session_unset command but no matter where I put it, the form is cleared before the reset button is pushed.
How can I combine session_unset and a reset button?
You can do this is two ways. You can start giving the two submit buttons a NAME, and then make a PHP script, which unset the defined Sessions by
<?php
if(isset($_POST['reset']){unset($_SESSION['username'],$_SESSION['email']);}
?>
And then of course change the Value to <?=$_SESSION['username'];?> and <?=$_SESSION['email'];?> - Because then it'll only show value if the two sessions contains any.
Otherwise you can do it with JQuery.
EDIT:
^ You should ofcourse also unset the $_SESSION['story'] (Didn't see it at first)
EDIT2:
$(document).ready(function(e) {
$("form input[type=reset]").click(function(e) {
$("form input[name=name]").attr("value","");
$("form input[name=email]").attr("value","");
$("form textarea[name=story]").attr("value","");
return false;
});
});
or if you want it to reset 'anything' which is text-based:
$(document).ready(function(e) {
$("form input[type=reset]").click(function(e) {
$("form input[type=text], form input[type=email], form input[type=password], form textarea").attr("value","");
return false;
});
});
^ Add more options if you like to :)
I think the Reset button resets the form into the way it was received from the server. So that could be why it is not working. It was received with data, thus the button takes back to it's original state. I could be wrong though, haven't tried that before.
And by the way, to unset a $_SESSION, you could do this
unset($_SESSION['specific']);
or you could destroy the whole thing.
session_destroy();

Jquery returning ObjectObject, first two fields return as expected

I was wondering if someone could help me out as I have googled for quite a while today, and haven't found anything to solve my problem.
The websites I've looked at mentioned it's because it's returning JSON, but they are getting it on all the fields, not just the one.
But what I can't understand, is why isn't the first two fields as well? Hence my confusion
I am submitting a login form, using Jquery and AJAX (I'm knew to this).
The first two fields (email and pass) submit, and return as expected.
For testing purposes I simply return their values in <span id="loginresponse"></span>.
I have a third field, to prevent CSRF, called 't' (named it random names, to see if this was the problem - I still get [object Object] returned). <input type="hidden" name="t" value="RandomToken"/>
When submitting the form, I expect it to return what I entered into the fields - "Email,Pass and RandomToken".
Instead, I get Email,Pass,[Object Object].
Here is my DoLogin function, which is called when the form is submitted.
function DoLogin()
{
var Email = $("#email").val();
var Pass = $("#pass").val();
var LoginResponse = $("#loginresponse");
var T = $("#t");
var EmailPlaceholder="Email address";var PassPlaceholder="Your password here";
$.get('path/to/login_ajax.php?email='+Email+'&pass='+Pass+'&t='+T, function(data)
{
$('#loginresponse').html(data);
});
/*if(Email != EmailPlaceholder && Pass != PassPlaceholder && Email != "" && Email != " " && Pass !="" && Pass != " ")
{
}*/
}
Here is my HTML form:
<form action="javascript:DoLogin();" method="post"><!--Also tried changing method to GET, still got the same problem -->
<input id="email" class="inputemail" type="text" name="email" size="40" value="Email address" onclick="$(this).val('');"/><span>Your email</span><br/>
<input id="pass" class="inputpassword" type="password" name="pass" size="40" value="Your password here" onclick="$(this).val('');"/><span>Your password</span><br/>
<input id="t" type="hidden" name="t" value="RandomToken"/>
<input class="indexsubmit" type="submit" value="Login"/>
</form>
<span id="loginresponse"></span>
And finally, login_ajax.php
<?php
echo $_GET['email'].$_GET['pass'].$_GET['t'];
?>
As mentioned above - I am only echoing the results, for know, as I'm knew to Jquery and AJAX, so I want to check if all fields are returning the values as expected, and one isn't...The token field.
You are chaining the object T of the input element and not the element's value to the query string of your GET request.
You should change this line
var T = $("#t"); // The object of the input element
to this
var T = $("#t").val(); // The value of the input element
Maybe what you want is:
var T = $("#t").val();

jQuery + hidden input fields

A simplified version of problem I am experiencing:
Here is my HTML form:
<form enctype="multipart/form-data" method="post" action="/controller/action">
<input type="text" name="title" id="title" value="" class="input-text" />
<input type="hidden" name="hidden_field" value="" id="hidden_field" />
<input type="submit" name="submit_form" id="submit_form" value="Save" class="input-submit" />
</form>
Here is the JavaScript:
$(document).ready(function() {
$('#submit_form').hover(function() {
$('#hidden_field').attr('value') = 'abcd';
});
});
And here is a really short version of the PHP backend:
if (isset($_POST)) {
var_dump($_POST);
}
What I do is I hover the #submit_form button for a few seconds just to make sure that the jQuery code got executed, then I submit the form and:
the $_POST['hidden_field'] is empty!
Why is that? It should contain 'abcd' as I insert it into the hidden field with jQuery on the hover event.
Correct way to set the value:
$('#hidden_field').val('abcd');
Reference: http://docs.jquery.com/Attributes/val
The statement
$('#hidden_field').attr('value') = 'abcd';
is incorrect. You should get an error there as you're assigning an rvalue (the jQuery object) to another rvalue (a string). (The assignment operator needs an lvalue (e.g. a variable) on the left.)
You probably want:
$('#hidden_field').val('abcd');
or:
$('#hidden_field').attr('value', 'abcd');
(The former is more jQuery-ish, but for this case both are equivilent.)
it is:
$('#hidden_field').attr('value','abcd');
Since these are hidden elements be sure to check these with something other that viewing the page source i.e. pressing F12, check with alert(), etc. The source of the original html page will not reflect changes made to it via javascript.

Categories