Form check information & insert on same page - javascript

So I've got a regular form
<form action="includes/send.php" method="post" onsubmit="return isValidForm()" />>
<h1>Opgeven workshops</h1>
<label for="name">Voornaam:</label>
<input type="text" autocomplete="off" id="name" name="firstname">
<label class="choice" data-id="1"><input type="checkbox" name="group1" value="use your apple1">use your apple<span class="left" ></span>
</label>---more stuff more stuff more stuff--
Now I submit the form I want to show the information the user filled in in the form like this
$f_name = $_POST['firstname'];
$l_name = $_POST['lastname'];
U hebt zich ingeschreven bij: <br />
Eerste workshop : <?php echo $first; ?><br />
Tweede workshop : <?php echo $second; ?><br />
Klopt dit?
<button type="submit" onclick="send()">Ja</button>
<button type="submit" onclick="noSend()">nee</button>
and when the user clicks on send it sends the information from the previous form to the query to insert it into the database. I'm trying to do this without having to make another 'hidden form' which submits it again because it is unnecessary code when you can just let the script 'wait' and continue with the script / insert functionallity when the button is pressed.
I tried setting a variable $submit= false; and inside the send function (which is in javascript) set submit to true but that doesn't seem to work because it automatically sets the variable to true without pressing the button.
function send(){
<?php $submit = true ?>
var submit = <?php echo $submit ?>;
console.log(submit);
}
if($submit){
echo 'submitted';
} else {
echo 'not true';
}

On your php side pass the values when calling your Javascript 'send()' function
<?php
$first = "First course";
$second = "Second course";
?>
U hebt zich ingeschreven bij: <br />
Eerste workshop : <?php echo $first; ?><br />
Tweede workshop : <?php echo $second; ?><br />
Klopt dit?
<!-- pass the required values into the function, this is just a basic implementation you could also use a loop to fill in the values -->
<button type="button" onclick="send(true, '<?php echo $first ?>', '<?php echo $second ?>')">
Ja
</button>
<button type="button" onclick="send(false)">
nee
</button>
For the receiving function you could implement something like this
<script type="text/javascript">
function send(submit){
//Get all arguments passed except the first variable, the submit boolean
var listOfVariablesToPost = Array.prototype.slice.call(arguments,1);
if(submit){
console.log("post");
console.log(listOfVariablesToPost);
/* Do POST here either by using XMLHttpRequest or jQuery AJAX/POST (Or any other way you like)*/
/* XMLHttpRequest: http://stackoverflow.com/questions/9713058/sending-post-data-with-a-xmlhttprequest */
/* jQuery POST https://api.jquery.com/jquery.post/ */
}else{
console.log("No post")
/* Don't post and do whatever you need to do otherwise */
}
}
</script>
This is a very simple implementation, but I hope it helps.

Related

How to refresh div after ajax success response

I have a form with ajax requests, when the fields are not respected and click on submit button the messages are displayed without page refresh. This works, the problem is that if the form is submitted several times, the error messages accumulate and multiple messages are displayed at the same time.
For example: if you leave field name blank and then submit, the error message (field required) appears. When you enter your name and then submit the success message (Settings Saved) appears but the error message is still visible.
What I want to get is only one message at a time, so the div should update showing the new message and deleting the previous one.
Now, I've tried doing some research and I understand that an if condition with $("#my-div").load("#my-div"); can be used in these cases but i have no idea how to do it, i am new to all this.
Can anyone help me understand how to achieve this? I appreciate any help and thank you for any replies.
My form
<form name="Form" class="mts-edit-account" action="<?php echo admin_url('admin-ajax.php'); ?>" method="post" enctype="multipart/form-data" <?php add_action( 'woocommerce_edit_account_form_tag', 'action_woocommerce_edit_account_form_tag' );?> >
<!-- Message section -->
<div class="msg_box"></div>
<!-- Fist & Last Name Field -->
<div class="row name_surname">
<div class="form-row">
<label class="t3" for="account_first_name">Nome *</label>
<input type="text" placeholder="Inserisci il tuo nome" class="field-settings" name="account_first_name" id="account_first_name" value="<?php echo esc_attr( $user->first_name ); ?>" />
</div>
<div class="form-row">
<label class="t3" for="account_last_name">Cognome *</label>
<input type="text" placeholder="Inserisci il tuo cognome" class="field-settings" name="account_last_name" id="account_last_name" value="<?php echo esc_attr( $user->last_name ); ?>" />
</div>
<!-- Save Settings -->
<p style="margin-bottom: 0px!important;">
<?php wp_nonce_field( 'save_account_details', 'save-account-details-nonce' ); ?>
<button type="submit" class="edit-account-button" name="save_account_details" value="<?php esc_attr_e( 'Save changes', 'woocommerce' ); ?>"><?php esc_html_e( 'Salva modifiche', 'woocommerce' ); ?></button>
<input type="hidden" name="action" value="save_account_details" />
</p>
</div>
</form>
Script
jQuery(document).ready(function($) {
$('.mts-edit-account').on('submit', function(e) {
e.preventDefault();
//Ajax function
jQuery.ajax({
type: "post",
data: jQuery(".mts-edit-account").serialize(),
url: "wp-admin/admin-ajax.php",
success : function( response ) {
jQuery('.msg_box').append(response);
}
});
});
});
Functions.php
add_action( 'wp_ajax_save_account_details', 'save_account_details' );
add_action( 'woocommerce_save_account_details_errors','save_account_details', 10, 1 );
function save_account_details() {
if (trim($_POST['account_first_name']) == '') {
$response = wc_print_notices( $return = false );
} else {
$response = "Settings Saved!";
}
// Don't forget to exit at the end of processing
echo json_encode($response);
exit();
}
You've used jQuery('.msg_box').append(response) method for displaying the messages. The documentation clearly states that this is used to insert content, specified by the parameter, to the end of each element in the set of matched elements.
Naturally giving you the multiple messages. If you just need a single message, then use:
jQuery('.msg_box').html(response)
.html() will ensure that the content of the container is overridden each time.
Reference: Official Documentation

Displaying a php script result in a div using jquery

I am a beginner on coding. I am working on a WordPress website using beaver builder theme. My challenge is to display a login form (when the user is not logged in) and the user name when he is logged in, to a specific area of the header that has a class "header-text".
Here is my php code located in a file named "file.php"
<?php
if(is_user_logged_in()) {
$user = wp_get_current_user();
$var1 = "<p>Welcome <?php echo $user->display_name; ?></p>
<p><a href='/login/login.php?logout=true'>Click here to log out</a></p>";
$var2 = "<form action='login.php' method='post'>
<input type='text" autocomplete='off' placeholder='Username' name='username'/>
<input type='text' autocomplete='off' placeholder='Password' name='password'/>
<button type='submit' value='Submit'>Submit</button>
</form>";
echo echo json_encode($var1);
} else {
echo echo json_encode($var2);
}
?>
Here is javascript
<script type="text/javascript">
jQuery(document).ready(function($){
function displayAccess() {
$.get("login/file.php");
return false;
}
if(<?php echo json_encode($var1); ?>) {
var variable1 = <?php echo json_encode($var1); ?>;
document.getElementByClassName("header-text").innerHTML = variable1;
}
if(<?php echo json_encode($var2); ?>){
var variable2 = <?php echo json_encode($var2); ?>;
document.getElementByClassName("header-text").innerHTML = variable2;
}
});
</script>
I need help to correct my script. Thanks!
in this case, javascript an jquery is not necessary, because the login status changes on reload, anyway.
all you need is a change in your php code:
<?php
/* put this to your template file (e.g. header.php) */
if(is_user_logged_in()) {
$user = wp_get_current_user();
/* change $var1 to echo it via html block inside php */
?>
<p>Welcome <?php $user->display_name; ?></p>
<p>Click here to log out</p>
<?php
/* cut $var2 because it is not accessible in the else clause */
} else {
/*
paste $var2 here and echo it
btw:
* For tags that are self-closing, the forward slash should have exactly one space preceding it (https://make.wordpress.org/core/handbook/best-practices/coding-standards/html/#self-closing-elements)
* use single or double quotes – make a decision!
*/
?>
<form action="login.php" method="post">
<input type="text" autocomplete="off" placeholder="Username" name="username" />
<input type="text" autocomplete="off" placeholder="Password" name="password" />
<button type="submit" value="Submit">Submit</button>
</form>
<?php
}
?>

How to keep php $_GET value from a submit button after form submit from javascript?

I have a php page with 2 submit buttons and 2 radio buttons:
<?php
$choiceIdx = 1;
$language = 'English';
if($_GET)
{
if(isset( $_GET['choice'] ))
{
$choiceIdx = $_GET['choice'];
}
if(isset( $_GET['language'] ))
{
$language = $_GET['language'];
}
}
?>
<form method="get">
<button type='submit' name='choice' value='1'>Choice1</button>
<button type='submit' name='choice' value='2'>Choice2</button>
<input id="English" type="radio" name="language" value="English" <?php echo ($language=='English')?'checked':'' ?> onchange="this.form.submit();" />
<label for="English">English</label>
<input id="Slovenian" type="radio" name="language" value="Slovenian" <?php echo ($language=='Slovenian')?'checked':'' ?> onchange="this.form.submit();" />
<label for="Slovenian">Slovenian</label>
</form>
If I click on Slovenian radio button, I get:
http://localhost/index.php?language=Slovenian
If I then click on Choice2 submit button, "language" is saved and I get:
http://localhost/index.php?choice=2&language=Slovenian
If I then click on English radio button, "choice" is not saved and I get:
http://localhost/index.php?language=English
This is my first php page and after hours of googling i added this line:
<input type="hidden" name="choice" value="<?php echo $choiceIdx; ?>">
The "choice" is now saved, but i get:
http://localhost/index.php?choice=1&language=Slovenian&choice=2
I don't want it twice in url. Please explain what i am doing wrong. Thank you!
EDIT: I want to use GET (and not POST) because the URL has to be saved as a bookmark.
Here is an alternate version (as a followup to my first answer) that updates the hidden value when clicking the choice-button:
<script>
function setChoice(val) {
document.getElementById('hiddenChoice').value=val;
}
</script>
<form method="get">
<button type='submit' onClick="setChoice(1);">Choice1</button>
<button type='submit' onClick="setChoice(2);">Choice2</button>
<input type='hidden' id='hiddenChoice' name='choice' value='<?php echo $choiceIdx; ?>'>
<input id="English" type="radio" name="language" value="English" <?php echo ($language=='English')?'checked':'' ?> onchange="this.form.submit();" />
<label for="English">English</label>
<input id="Slovenian" type="radio" name="language" value="Slovenian" <?php echo ($language=='Slovenian')?'checked':'' ?> onchange="this.form.submit();" />
<label for="Slovenian">Slovenian</label>
</form>
If you have more values to retrieve you might want to create a more sofisticated and less specific js-function. You could easily pass in the id of the target input f.e.
Also you should rethink if it's realy neccessary to always submit the form, or if it might be better to first collect all the data and only send one form back to the server.
Add that to your form:
<input type='hidden' name='choiceStored' value='<?php echo $choiceIdx; ?>'>
This will store the last received val for choice and re-send it at the next form submit.
and change your php to:
$choiceIdx = 1;
$language = 'English';
if($_GET)
{
// eighter get new value
if(isset( $_GET['choice'] ))
{
$choiceIdx = $_GET['choice'];
// or if we don't have a new value, take the 'stored' one:
} elseif (isset($_GET['choiceStored']))
{
$choiceIdx = $_GET['choiceStored'];
}
if(isset( $_GET['language'] ))
{
$language = $_GET['language'];
}
}
You are passing the same name twice. 'choice' has been defined as both the hidden value name and the button value name. To be able to differentiate, you should change the hidden value name to something like 'savedchoice'. And reference it by that name

preparing online test in php using javascript

I want to create a test pattern in PHP using MySQL database.Here i want to fetch questions form database and display those in my html pages. Now i want to create a division with next button and when user clicks it should display the next question that fetched from database in the same division dynamically. i guess it can be achieved through jQquery or javascript but unable to get the logic.
can anyone help.
thanks in advance.
here is a sample code that i have tried to display multiple divisions with javascript.
this is my database structure,
fields : qid,question,opt1,opt2,opt3,opt4
this is php code for fetching data form database.
<?php
$result=executeQuery("select * from quest");
if(mysql_num_rows($result)>0){
while($row=mysql_fetch_array($result)){
//echo $row['qid'];echo "<br/>";
echo $row['question']; echo "<br/>";
?>
<input type="radio" name="a1" value="'<?php echo $row['opt1']; ?>'" ><?php echo $row['opt1']; echo "<br/>"; ?>
<input type="radio" name="a1" value="'<?php echo $row['opt2']; ?>'" ><?php echo $row['opt2']; echo "<br/>";?>
<input type="radio" name="a1" value="'<?php echo $row['opt3']; ?>'" ><?php echo $row['opt3']; echo "<br/>";?>
<input type="radio" name="a1" value="'<?php echo $row['opt4']; ?>'" ><?php echo $row['opt4']; echo "<br/>";?>
<?php
}
}
?>
<input type="submit" name="submit" value="submit">
now this fetches all the rows at a time and displays it.
this is javascript
var x=1;
function myfunc(){
document.getElementById(x).style.display="block" ;
x++;
}
when i click on button every time,respected division is displayed, but i want to display all data within one common division when each time the button is clicked.
If you don't want to reload a page when clicking the next button, we can use a Javascript library called jQuery.
I would also suggest that you use prepared statement rather than using the deprecated mysql_* API.
Lets start first by re-establishing your mysql_* and turn it to mysqli_*:
/* ESTABLISH CONNECTION */
$con = new mysqli("Host", "username", "password", "database"); /* REPLACE NECESSARY DATA INSIDE */
/* CHECK CONNECTION */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if($stmt = $con->prepare("SELECT qid, question, opt1, opt2, opt3, opt4 FROM quest ORDER BY qid LIMIT 1")){
$stmt->execute(); /* EXECUTE THE QUERY */
$stmt->bind_result($qid, $question, $opt1, $opt2, $opt3, $opt4); /* BIND THE RESULT TO THESE VARIABLES */
$stmt->fetch(); /* FETCH THE RESULT */
$stmt->close();
} /* END OF PREPARED STATEMENT */
After we get the data, we can now put it inside your form.
<h1 id="question"><?php echo $question; ?></h1>
<input type="hidden" id="qid" value="<?php echo $qid; ?>">
<input type="radio" name="a1" id="op1" value="<?php echo $opt1; ?>"><span id="op1text"><?php echo $opt1; ?></span><br/>
<input type="radio" name="a1" id="op2" value="<?php echo $opt2; ?>"><span id="op2text"><?php echo $opt2; ?></span><br/>
<input type="radio" name="a1" id="op3" value="<?php echo $opt3; ?>"><span id="op3text"><?php echo $opt3; ?></span><br/>
<input type="radio" name="a1" id="op4" value="<?php echo $opt4; ?>"><span id="op4text"><?php echo $opt4; ?></span><br/>
<input type="submit" name="submit" id="submit" value="Next"> <!-- THIS SERVES AS THE SUBMIT AND NEXT BUTTON -->
Before you proceed, download the library here.
Now, we can create a script that will take the answer and go to the next question. We will submit the answer of the user to the database using AJAX.
<script src="jquery-1.9.1.min.js"></script> <!-- REPLACE NECESSARY JQUERY FILE DEPENDING ON THE VERSION YOU HAVE DOWNLOADED -->
<script>
$(document).ready(function(){
$("#submit").click(function(){ /* WHEN SUBMIT IS CLICKED */
var qid = $("#qid").val(); /* GET THE question id */
var selected = $("input[type='radio'][name='a1']:checked");
if (selected.length > 0) { /* CHECK THE SELECTED RADIO BUTTON */
answer = selected.val();
}
$.ajax({
type: "POST", /* THE METHOD WE WILL BE USING TO PASS THE DATA */
url: "action.php", /* THIS IS WHERE THE DATA WILL GO */
data: {"questionid" : qid, "answer" : answer}, /* THE DATA WE WILL BE PASSING */
dataType : 'json',
success: function(result){ /* WHEN IT IS SUCCESSFUL */
/* THIS WILL REPLACE THE DATA IN OUR QUESTION PAGE */
$("#qid").val(result.questionid);
$("#question").html(result.question);
$("#op1").val(result.op1);
$("#op2").val(result.op2);
$("#op3").val(result.op3);
$("#op4").val(result.op4);
$("#op1text").html(result.op1);
$("#op2text").html(result.op2);
$("#op3text").html(result.op3);
$("#op4text").html(result.op4);
}
}); /* END OF AJAX */
});
});
</script>
Then, we can create the action.php which takes the data/answer from the question page.
<?php
if(isset($_POST["questionid"])){
/* INCLUDE OUR NEW ESTABLISHED CONNECTION HERE */
/* PUT HERE YOUR INSERT QUERY WHICH STORES THE USER'S ANSWERS */
/* THEN FETCH THE NEXT QUESTION */
if($stmt = $con->prepare("SELECT qid, question, opt1, opt2, opt3, opt4 FROM quest WHERE qid > ? ORDER BY qid LIMIT 1")){
$stmt->bind_param("i", $_POST["questionid"]);
$stmt->execute();
$stmt->bind_result($qid, $question, $opt1, $opt2, $opt3, $opt4);
$stmt->fetch();
$stmt->close();
} /* END OF PREPARED STATEMENT */
/* THIS SET OF DATA WILL REPLACE THE DATA IN OUR CURRENT QUESTION PAGE */
echo json_encode(array("questionid" => $qid, "question" => $question, "op1" => $opt1, "op2" => $opt2, "op3" => $opt3, "op4", => op4));
} /* END OF ISSET */
?>
if you dont want to implement with ajax. Then list all questions and use jQuery to display single div. Use 'click' functions on next button to display the next questions.
If you are going by this method, try the following instruction. Hope It will be simple for you.
Display all the questions and answers.
while($row=mysql_fetch_array($result)){ ?>
<li class="test " id="qid_<?php echo $row['id']; ?>" >
<?php echo $row['question']; /* here display the stuff */ ?></li>
<?php }
Create "prev" and "next" buttons.
<span class="prev_q">Prev</span>
<span class="next_q">Next</span>
Add this css( to make first question as active )
li.test { display:none; }
li.activequestion{ display:block;background:#cccccc; color:#c40001; }
Add the script to make prev, next buttons working
<script>
jQuery(document).ready(function(){
jQuery('li.test:first').addClass('activequestion');
jQuery('.next_q').click(function(){
var nonext=jQuery('.test:last').hasClass('activequestion');
if(nonext)
{ alert("no next available"); return false; }
var currentdiv=jQuery('.activequestion').attr('id');
jQuery('.test.activequestion').next().addClass('activequestion');
jQuery('#'+currentdiv).removeClass('activequestion');
});
jQuery('.prev_q').click(function(){
var noprevious=jQuery('.test:first').hasClass('activequestion');
if(noprevious)
{ alert("no previous available"); return false; }
var currentdiv=jQuery('.activequestion').attr('id');
jQuery('.test.activequestion').prev().addClass('activequestion');
jQuery('#'+currentdiv).removeClass('activequestion');
});
});
</script>

Required Entry for only one button of two

I have a form that has a text field that is a required entry for one(1) of my two(2) buttons. The first(1st) button applies a code, in the text field, to the products in the cart section of my store. The second(2nd) removes all codes from all products in the cart section.
What's the best way of going about this?
Thx.
<div id="cart-coupon-menu" class="coupon-menu-hide">
<form id="discount-coupon-form" action="<?php echo $this->getUrl('checkout/cart/couponPost') ?>" method="post">
<div class="discount">
<div class="discount-form">
<input type="hidden" name="remove" id="remove-coupone" value="0" />
<div class="input-box">
<input class="input-text" id="coupon_code" name="coupon_code" value="<?php echo $this->escapeHtml($this->getCouponCode()) ?>" placeholder="Enter a Coupon or Promo Code" autocomplete="off"/>
</div>
<div class="buttons-set">
<button type="button" title="<?php echo $this->__('Apply Coupon') ?>" class="button" onclick="discountForm.submit(false)" value="<?php echo $this->__('Apply Coupon') ?>"><span><span><?php echo $this->__('Apply Coupon') ?></span></span></button>
<button type="button" title="<?php echo $this->__('Cancel Coupon') ?>" class="button" onclick="discountForm.submit(true)" value="<?php echo $this->__('Cancel Coupon') ?>"><span><span><?php echo $this->__('Cancel Coupon') ?></span></span></button>
</div>
</div>
</div>
</form>
</div>
The above form will be serialized and set to a controller via AJAX and an appropriate response will be returned.
When the input box is null I want the input box to act as a required field and disallow submission via the first button. However, when it is null the second button should still allow for submission. When text is entered into the input box they both behave normally.
Currently i'm attempting to do something like this:
<script type="text/javascript">
//<![CDATA[
var discountForm = new VarienForm('discount-coupon-form');
discountForm.submit = function (isRemove) {
if (isRemove) {
$('coupon_code').removeClassName('required-entry');
$('remove-coupone').value = "1";
} else {
$('coupon_code').addClassName('required-entry');
$('remove-coupone').value = "0";
}
if(something where I identify if it is required and the field is null){return null;}
else{continue with ajax call;}
I think it's just a simple javascript something like:
<button type="button" title="<?php echo $this->__('Apply Coupon') ?>" class="button" onclick="isValid() ? discountForm.submit(false) : handleInvalid()" value="<?php echo $this->__('Apply Coupon') ?>"><span><span><?php echo $this->__('Apply Coupon') ?></span></span></button>
I used a ternary operator in there... so basically it says if isValid() returns true, execute: discountForm.submit(false) otherwise execute: handleInvalid().
Then the javascript functions would be:
function isValid() {
var couponCode = document.getElementById('coupon_code').value;
return /* whatever logic you want here... */
}
function handleInvalid() {
// do whatever you want to the coupon_code input to indicate it's required and pop up an error message
alert("Please enter a coupon code!");
}
You should give knockout a try. It updates your view(html) according to changes in your js code. See this example.

Categories