Pass form Variables to $_SESSION by AJAX in wordpress - javascript

I have several forms on my site that manipulate the data that is held in $_SESSION. I am looking to AJAXify all of these. The main example is below.
FORM:
<form class="form-inline" id="addExerciseForm" role="form" method="post" action=" ">
<div class="form-group">
<input class="hidden" name="ExerciseID" type="text" class="form-control" value="29">
</div>
<div class="form-group lightboxFormText">
<label class="lightboxFromElementLabels" for="exerciseDescription">Description</label>
<textarea class="form-control" name="Description" rows="3"><?php echo the_content(); ?></textarea>
</div>
<br />
<br />
<div class="form-group lightboxFormElements">
<label class="lightboxFromElementLabels" for="exerciseSets">Sets</label>
<input type="text" name="Sets" class="form-control" placeholder="Sets">
</div>
<div class="form-group lightboxFormElements">
<label class="lightboxFromElementLabels" for="exerciseReps">Reps</label>
<input type="text" name="Reps" class="form-control" placeholder="Reps">
</div>
<div class="form-group lightboxFormElements">
<label class="lightboxFromElementLabels" for="exerciseReps">Load</label>
<input type="text" name="Load" class="form-control" placeholder="Load">
</div>
<div class="form-group lightboxFormElements">
<label class="lightboxFromElementLabels" for="exerciseReps">Rest</label>
<input type="text" name="Rest" class="form-control" placeholder="Rest">
</div>
<div class="form-group lightboxFormElements">
<label class="lightboxFromElementLabels" for="exerciseReps">Tempo</label>
<input type="text" name="Tempo" class="form-control" placeholder="Tempo">
</div>
<br />
<br />
<div class="modal-footer">
<div class="form-group">
<input type="hidden" name="action" value="addExercise">
<input type="submit" class="btn btn-success">Add to Collection</input>
</div>
</div>
</form>
Javascript:
jQuery('#addExerciseForm').submit(addExercise);
function addExercise(){
var newExercise = jQuery(this).serialize();
jQuery.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php",
data: addExerciseForm,
success:function(data){
jQuery("#feedback").html(data);
}
});
return false;
}
Function:
function addExercise(){
global $post;
echo $description;
$_SESSION['collection'][$_POST['ExerciseID']] = array(
$description => $_POST['Description'],
$sets => $_POST['Sets'],
$reps => $_POST['Reps'],
$load => $_POST['Load'],
$rest => $_POST['Rest'],
$tempo => $_POST['Tempo']);
$description = $_SESSION['collection'][$exid]['Description'];
$sets = $_SESSION['collection'][$exid]['Sets'];
$reps = $_SESSION['collection'][$exid]['Reps'];
$rest = $_SESSION['collection'][$exid]['Rest'];
$load = $_SESSION['collection'][$exid]['Load'];
$tempo = $_SESSION['collection'][$exid]['Tempo'];
die();
}
add_action('wp_ajax_addExercise', 'addExercise');
add_action('wp_ajax_nopriv_addExercise', 'addExercise');
I understand that I can go straight from jQuery VAR -> session Var however this code is cobbled together from my original $_POST Submit button. The AJAX side of things has got me confused, and throwing in the mix the different way that Wordpress handles things, any assistance will be appreciated.

Using $_SESSION in WordPress isn't the same as a standard php script approach. You have to do things like factoring in when in the sequence of WordPress loading, does the session get set, created, etc.
Have you seen the WP Session Manager? It makes working with sessions in WordPress much more pain-free. Check out https://wordpress.org/plugins/wp-session-manager/

Related

Laravel stripe and cashier no such payment method

I am using Laravel 7 and i am integratng stripe with cashier and i am facing issue
No such PaymentMethod: 'tok_1HBxFdEft5GkDC4v7ZnPgW5Y'
I am using custom checkout forms Html code is
<form class="rt-formtheme rt-paymentmethodform" method="POST" action="{{route('subscripe.process')}}" id="subscribe-form">
#csrf
<div class="div-stripe-errors col-12" style="margin-top: 30px;"></div>
<fieldset>
<legend>Choose your card</legend>
<!-- <div class="form-group">
<button type="submit" class="rt-btn rt-savebtn">Save</button>
</div> -->
<div class="form-group">
<span class="rt-radio">
<input type="radio" name="radiobutton" id="visa">
<label for="visa"><img src="{{asset('images/visa.png')}}" alt=""></label>
</span>
</div>
<div class="form-group">
<span class="rt-radio">
<input type="radio" name="radiobutton" id="american-express">
<label for="american-express"><img src="{{asset('images/american-express.png')}}" alt=""></label>
</span>
</div>
<div class="form-group">
<label>Card Number</label>
<input type="text" name="cardnumber" class="form-control" placeholder="1234 5678 9012 3456" data-stripe="number">
</div>
<div class="rt-twocols">
<div class="form-group">
<div class="rt-twoinputfieldholder">
<div class="rt-twoinputfieldbox">
<label>Expiry Month</label>
<input type="text" name="expirymonth" class="form-control" placeholder="MM" data-stripe="exp-month">
</div>
<div class="rt-twoinputfieldbox">
<label>Expiry Year</label>
<input type="text" name="expiryyear" class="form-control" placeholder="YY" data-stripe="exp-year">
</div>
</div>
</div>
<div class="form-group">
<label>CVC</label>
<input type="text" name="cvv" class="form-control" placeholder="123" data-stripe="cvc">
</div>
</div>
<div class="form-group margin-zero rt-savecarddetailbox">
<span class="rt-checkbox">
<input type="checkbox" name="savecarddetail" id="savecarddetail">
<label for="savecarddetail">Save Card Details</label>
</span>
<button type="submit" class="rt-btn float-right">Checkout</button>
</div>
</fieldset>
</form>
and js code is
<script src="https://js.stripe.com/v2/"></script>
<script>
Stripe.setPublishableKey('{{ env("STRIPE_KEY") }}');
$(document).ready(function(){
$('#subscribe-form').submit(function(e){
var form = $(this);
form.find('button').prop('disabled', true);
Stripe.card.createToken(form, function(status, response) {
if (response.error) {
form.find('.div-stripe-errors').text(response.error.message).addClass('alert alert-danger');
form.find('button').prop('disabled', false);
} else {
// append the token to the form
form.append($('<input type="hidden" name="cc_token">').val(response.id));
// debugger
// submit the form
form.get(0).submit();
}
});
e.preventDefault();
});
});
Route is
Route::post('/subscribe_process', 'Dashboard\CheckoutController#subscribeProcess')->name('subscripe.process');
and controller method is
public function subscribeProcess(Request $request)
{
try{
$cc_token = $request->cc_token;
$user = Auth::user();
$user->newSubscription('Main','Monthly')->create($cc_token);
alert()->success('User Updated Successfully', 'Success');
return \redirect()->back();
}catch(\Exception $ex){
return $ex->getMessage();
}
}
and i also create plan on stripe dashboard
when i create a subscription it show error No such payment method i am new in stripe kindly help me
"No such..." errors are usually caused by either a mismatch in API keys (e.g. using a mixture of your test plus live keys) or by trying to access objects that exist on a different account (e.g. trying to perform an operation from your platform account on an object that was created on a connected account).

checkValidity() not showing any html5 error notifications when fields are empty and posting with Ajax

I have a form that posts using Ajax, I also want to set an HTML5 required attribute on some input fields, but this stops working as expected with Ajax.
So I did the following:
$("body").on("click",".register-button",function(e){
e.preventDefault();
if($('#registerform')[0].checkValidity()){
registerform = $(".register-form").serialize();
$.ajax({
type:'post',
url:"includes/registreren.php",
data:({registerform: registerform}),
success:function(data){
var content = $( $.parseHTML(data) );
$( "#registerresult" ).empty().append( content );
}
});
}else{
}
});
This way the form is not posted when empty, but I also don't get any notifications that fields are empty like I would get when only using HTML to post.
I also tried logging the validity like so:
$("body").on("click",".register-button",function(e){
e.preventDefault();
$check = $('#registerform')[0].checkValidity();
console.log($check);
registerform = $(".register-form").serialize();
$.ajax({
type:'post',
url:"includes/registreren.php",
data:({registerform: registerform}),
success:function(data){
var content = $( $.parseHTML(data) );
$( "#registerresult" ).empty().append( content );
}
});
});
Which shows false in my console when empty. So the code works, why are the HTML5 notifications not shown? I remember doing something similar in the past and I didn't have to add any custom error messages then, it just worked.
This is my HTML markup:
<form id="registerform" class="register-form" method="post">
<div class="row">
<div class="col-md-6">
<input type="text" name="voornaam" placeholder="Voornaam" required>
</div>
<div class="col-md-6">
<input type="text" name="achternaam" placeholder="Achternaam" required>
</div>
<div class="col-md-12">
<input type="text" name="bedrijf" placeholder="Bedrijfsnaam (optioneel)">
</div>
<div class="col-md-6">
<input type="text" name="telefoon" placeholder="Telefoonnummer" required>
</div>
<div class="col-md-6">
<input type="text" name="email" placeholder="E-mail" required>
</div>
<div class="col-md-3">
<input type="text" name="huisnummer" id="billing_streetnumber" placeholder="Huisnummer" required>
</div>
<div class="col-md-3">
<input type="text" name="tussenvoegsel" placeholder="Tussenvoegsel" required>
</div>
<div class="col-md-6">
<input type="text" name="postcode" id="billing_postcode" placeholder="Postcode" required>
</div>
<div id="postcoderesult" class="col-lg-12">
<div class="row">
<div class="col-md-6">
<input type="text" name="straat" placeholder="Straatnaam" readonly required>
</div>
<div class="col-md-6">
<input type="text" name="woonplaats" placeholder="Woonplaats" readonly required>
</div>
</div>
</div>
<div class="col-md-6">
<input type="password" name="password" placeholder="Wachtwoord (minimaal 6 tekens)" required>
</div>
<div class="col-md-6">
<input type="password" name="confirmpassword"placeholder="Herhaal wachtwoord" required>
</div>
<div id="registerresult">
</div>
</div>
<button type="button" name="submit" class="register-button">Account aanmaken</button>
</form>
What am I missing?

Pass form results to another form into a form value

I have two forms on a page the "top form" searches for movies and I'm trying to get the data found from the top form and pass it as a value to the bottom form so it can get entered into a database.
I am unable to do this but, I can get the results to be displayed on the page. Here is my code:
TOP FORM DATA
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<?php
$squery="";
if(isset($_GET["squery"]))
{
$squery=$_GET["squery"];
}
?>
<div class="col-xs-8 col-xs-offset-2">
<form action="#" method="GET" class="form-horizontal">
<div class="form-group">
<label for="newMovieName" class="col-sm-3 control-label">Search what movie?</label>
<div class="col-sm-9"> <input type="text" name="squery" class="form-control"><br />
<input type="submit" value="Submit" class="btn btn-success"></div></div>
</form>
<script type="text/javascript" charset="utf-8">
var api_key = '6969696969696969696969696969696';
$(document).ready(function(){
$.ajax({
url: 'http://api.themoviedb.org/3/search/movie?api_key=' + api_key + '&query=<?php echo $squery; ?>',
dataType: 'jsonp',
jsonpCallback: 'testing'
}).error(function() {
console.log('error')
}).done(function(response) {
var i=0;
// for (var i = 0; i < response.results.length; i++) {
$('#search_results').append('<li>' + response.results[i].title + '</li>');
// }
$('#search_results_title').append(response.results[i].title);
$('#search_results_release').append(response.results[i].release_date);
$('#search_results_overview').append(response.results[i].overview);
$('#search_results_poster').append('https://image.tmdb.org/t/p/w185' + response.results[i].poster_path);
$('#search_results_votes').append(response.results[i].vote_count);
});
});
</script>
TOP FORM RESULTS
Here is where the results are displayed from the form above BUT, I would like these results to be displayed as a value in the form below.
<h3>Results</h3>
<p id="error"></p>
<ul id="search_results_title"></ul>
<ul id="search_results_release"></ul>
<ul id="search_results_overview"></ul>
<ul id="search_results_poster"></ul>
<ul id="search_results_votes"></ul>
BOTTOM FORM DATA
Here is the bottom form that SHOULD get submitted to the database with the "Results" that are above as the value.
<form class="form-horizontal" role="form" action="processmovie.php" method="get" enctype="text/plain">
<div class="form-group">
<label for="newMovieName" class="col-sm-3 control-label">Title</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="newMovieName" name="movie_name" placeholder="Movie Title" required value="">
</div>
</div>
<div class="form-group">
<label for="movieYear" class="col-sm-3 control-label">Year</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="movieYear" name="movie_year" placeholder="Year" required>
</div>
</div>
<div class="form-group">
<label for="movieBio" class="col-sm-3 control-label">Storyline</label>
<div class="col-sm-9">
<textarea type="email" class="form-control" id="movieBio" name="movie_bio" rows="4" placeholder="Enter Storyline" required></textarea>
</div>
</div>
<div class="form-group">
<label for="newImage" class="col-sm-3 control-label">Movie Cover URL</label>
<div class="col-sm-9">
<input type="text" id="newImage" class="form-control" name="movie_img" placeholder="Enter URL" required>
</div>
</div>
<div class="form-group">
<label for="movieRating" class="col-sm-3 control-label">Rating</label>
<div class="col-sm-9">
<select id="movieRating" name="movie_rating" class="form-control" required>
<option value="G">G</option>
<option value="PG">PG</option>
<option value="PG-13">PG-13</option>
<option value="R">R</option>
<option value="NR">NR (Not Rated)</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-9">
<button type="submit" class="btn btn-success">Add Movie</button>
</div>
</div>
</form>
I tried to use a variaty of code to try and get the value here is an example: <?php echo $_GET['search_results_title'];?>
I've also found examples like this: How to pass the value of a form to another form? but, my forms are on the same page and not different ones.
As I said in my comment, you would just want to change your ajax call to something like this:
$.ajax({
url: 'http://api.themoviedb.org/3/search/movie?api_key=' + api_key + '&query=<?php echo $squery; ?>',
dataType: 'jsonp',
jsonpCallback: 'testing'
}).error(function() {
console.log('error')
}).done(function(response) {
var i=0;
$('#newMovieName').val(response.results[i].title);
$('#movieYear').val(response.results[i].release_date);
$('#movieBio').val(response.results[i].overview);
$('#newImage').val('https://image.tmdb.org/t/p/w185' + response.results[i].poster_path);
});
(I'm not sure about the relationship you have between response.results[i].vote_count and movieRating)
Here is a fiddle sort of showing the result, though I can't exactly replicate your code there because of the ajax calls

Trouble serializing form with jQuery

I cannot for the life of me figure out why my form will not serialize when using jQuery prior to posting via AJAX.
Whenever I debug the javascript 'formData' results in "".
I've tried this with the form id's hardcoded and it still results in the blank serialization, tried .get(0) at the end of the $(this) selector and tried without underscores in names and to no avail.
When debugging the selector contains the inputs as children, and I've serialized forms before where the inputs are nested in other elements without problems.
The reason I'm dynamically selecting the form with $(this) and not hardcoding the event handlers is that this will be part of the application where we will bolt on additional forms so I'd like it to be concise and maintainable.
Any insight is greatly appreciated.
My code is below:
HTML/PHP view (using CodeIgniter)
<div class="tabs-content">
<section role="tabpanel" aria-hidden="false" class="content active" id="details">
<div class="login-form">
<p class="lead">To change basic personal details such as name and email address use this form.</p>
<form action="<?php echo base_url() ?>ajax/update_details" method="POST" name="updateDetailsForm" id="updateDetailsForm">
<div class="row">
<div class="small-12 columns">
<label>First Name
<input type="text" placeholder="e.g. John" name="first_name" value="<?php echo $first_name ?>" />
</label>
</div>
</div>
<div class="row">
<div class="small-12 columns">
<label>Surname
<input type="text" placeholder="e.g. Smith" name="last_name" value="<?php echo $last_name ?>" />
</label>
</div>
</div>
<div class="row">
<div class="small-12 columns">
<label>Email
<input type="email" placeholder="e.g. me#example.com" name="email" value="<?php echo $email ?>" />
</label>
</div>
</div>
<input type="submit" class="button small" value="Update" />
</form>
</div>
</section>
<section role="tabpanel" aria-hidden="true" class="content" id="password">
<div class="login-form">
<p class="lead">You can use the form below to update your account password.</p>
<p>Passwords must be between 8 and 50 characters in length.</p>
<form action="<?php echo base_url() ?>ajax/update_password" method="POST" name="updatePasswordForm" id="updatePasswordForm">
<div class="row">
<div class="small-12 columns">
<label>Old Password <small>Required</small>
<input type="password" name="oldpw" />
</label>
</div>
</div>
<div class="row">
<div class="small-12 columns">
<label>New Password <small>Required</small>
<input type="password" name="newpw1" />
</label>
</div>
</div>
<div class="row">
<div class="small-12 columns">
<label>Confirm New Password <small>Required</small>
<input type="password" name="newpw2" />
</label>
</div>
</div>
<input type="submit" class="button small" value="Update Password" />
</form>
</div>
</section>
</div>
Javascript
$('form').on('submit', (function (e) {
e.preventDefault();
var url = $(this).attr('action');
$(this).html(loadingHTML);
var formData = $(this).serialize();
$.ajax({
type: 'POST',
url: url,
data: formData,
done: function (data) {
$(this).html(data);
}
});
}));
Swap lines
var formData = $(this).serialize();
$(this).html(loadingHTML);

Echoing/outputting information that was added to an input field on the same page

I'm creating a checkout system. I have three parts to it:
Shipping info
Payment info
Order confirmation
I'm trying to figure out a way that when the customer enters their shipping information, that data can be echo'd out onto my order confirmation part, so they can confirm that is where they want it shipped to.
The way I designed my checkout system is that all three parts are on the same page. Only one part shows at once and the others are hidden until the customer would click 'Proceed to xxxx'. When they click that Proceed button, nothing is being sent. It is just taking the div and showing it and hiding the previous div. Nothing is sent until when the customer clicks Submit order on the confirmation div.
I validate the fields and assigned them to variables so I can post the shipping and product info into my db.
if($validation->passed()) {
if(isset($_POST['create'])){
$fullname = trim( $_POST['customer_name'] );
$streetline1 = trim( $_POST['streetline1'] );
$streetline2 = trim( $_POST['streetline2'] );
$city = trim( $_POST['city'] );
$state = trim( $_POST['state'] );
$zipcode = trim( $_POST['zipcode'] );
$phone_number = trim( $_POST['phone_number'] );
$email = ( $_POST['email'] );
//etc...
Shipping Information Section:
<div class="shippinginfocontainer">
<span class="summarytitle">
<p>Enter Shipping Information</p>
</span><br>
<div class="center">
<div class="field">
<label class="paddingleft" for="fullname">Full Name</label>
<div class="center">
<input type="text" class="biginputbarinline" name="fullname" value="<?php echo escape(Input::get('firstname')); ?>" required>
</div>
</div>
<div class="field">
<label class="paddingleft" for="streetline1">Street Line 1</label>
<div class="center">
<input type="text" class="biginputbarinline" name="streetline1" value="<?php echo escape($user->data()->streetline1); ?>" required>
</div>
</div>
<div class="field">
<label class="paddingleft" for="streetline2">Street Line 2</label>
<div class="center">
<input type="text" class="biginputbarinline" name="streetline2" value="<?php echo escape($user->data()->streetline2); ?>">
</div>
</div>
<div class="field">
<label class="paddingleft" for="city">City</label>
<div class="center">
<input type="text" class="biginputbarinline" name="city" value="<?php echo escape($user->data()->city); ?>" required>
</div>
</div>
</div>
<div class="formleftcenter">
<div class="field">
<label for="state">State</label>
<input type="text" class="mediuminputbar" name="state" value="<?php echo escape($user->data()->state); ?>" required>
</div>
<div class="field">
<label for="Phone Number">Phone Number</label>
<input type="text" class="mediuminputbar" name="Phone Number" value="<?php echo escape($user->data()->phone_number); ?>">
</div>
</div>
<div class="formrightcenter">
<div class="field">
<label for="zipcode">Zip Code</label>
<input type="text" class="mediuminputbar" name="zipcode" value="<?php echo escape($user->data()->zipcode); ?>" required>
</div>
<div class="field">
<label for="email">Email</label>
<input type="text" class="mediuminputbar" name="email" value="<?php echo escape($user->data()->email); ?>" required>
</div>
</div>
<div class="clear">
<button class="checkoutbutton" id="button2">Proceed to Payment Information</button>
</div>
</div>
I won't add my payment part as it is irrelevant to this question.
Then this is the relevant part of the Confirmation part. I wasn't sure how to do this, so I just wrote in echo's to show what I am trying to do.
<div class="confirmshippinginfo">
<p>Shipping to:</p>
<p><?php echo $fullname; ?></p>
<p><?php echo $streetline1; ?></p>
<p><?php echo $streetline2; ?></p>
<p><?php echo $city . $state . $zipcode; ?></p>
</div>
</div>
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
<input class="widebutton" type="submit" value="Place Your Order">
Is there a way to do this with keeping this all on the same page? I really do not want to have multiple pages for this and I like the way I have all of this formatted. I just can't figure out this part.
You could possibly use AJAX via serialize() of your form when you click a review button (as Matthew Johnson suggested). Second idea is something like this where you copy from one input to another, in a different part of your page. It would take a bit more work to set up than something like AJAX because you are basically duplicating a form. Using .html() inside a div or span placeholder would probably work too:
HTML:
<input type="text" class="copy-from" data-copy="name" name="name" />
<input type="text" class="this-elem" id="name" disabled />
CSS
.this-elem {
border: none;
font-size: 18px;
color: #333;
}
jQuery
$(document).ready(function() {
$(".copy-from").keyup(function() {
var ElemId = $(this).data('copy');
$("#"+ElemId).val($(this).val());
});
});
Demo
http://jsfiddle.net/fh5kfhtm/4/
EDIT: AJAX/PHP Solution
<!-- This is the placeholder for the data after submission -->
<div id="final"></div>
<!-- FORM, well really simplified form -->
<form id="orderform" method="post" action="process.php">
<input type="hidden" name="order_form" />
<input type="text" name="address" />
<!--
This triggers the ajax (you would use your
"Proceed to Order Confirmation" button)
-->
<div id="confirm">CONFIRM</div>
<input type="submit" name="submit" value="ORDER" />
</form>
new.php
File name/path must match what's in the AJAX url
<?php
if(isset($_POST['order_form'])) {
print_r($_POST);
exit;
}?>
jQuery AJAX
<!-- GET THE LIBRARIES (YOU SHOULD ALREADY HAVE THEM) -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<script>
$(document).ready(function() {
$("#confirm").click(function() {
$.ajax({
// This is where you need the right path to the new php file
url:'/path/to/new.php',
type: 'post',
data: $("#orderform").serialize(),
success: function(response) {
$("#final").html(response);
}
});
});
});
</script>

Categories

Resources