Javascript Running 2 script toghether - javascript

I am new to Javascript, I am trying to run these 2 script toghether but one is canceling the other
I have a form and I would like to compute 2 tasks as soon as the user load the picture through the input file.
loading the the new picture in the thunbail
write the new picture path to the input text
Any tips to solve the issue will be appreciated. thank you
<form action="../handlers/processUpdatedProduct.php" method="post" enctype="multipart/form-data">
<div class="mb-3">
<input type="hidden" class="form-control" id="id" name="id" value="<?php echo $product->getId() ?>">
</div>
<div class="mb-3">
<label for="productname" class="form-label">Product Name</label>
<input type="text" class="form-control" id="productname" name="productname" value="<?php echo $product->getProductName() ?>">
</div>
<div class="mb-3">
<label for="description" class="form-label">Description</label>
<input type="text" class="form-control" id="description" name="description" value="<?php echo $product->getDescription() ?>">
</div>
<div class="mb-3">
<label for="listprice" class="form-label">Price</label>
<input type="text" class="form-control" id="listprice" name="listprice" value="<?php echo $product->getListPrice() ?>">
</div>
<div class="mb-3">
<label for="listprice" class="form-label">Picture path</label>
<input type="text" class="form-control" id="picturename" name="picturepath" value="<?php echo $product->getPhotoPath() ?>">
</div>
<div class="mb-3">
<label for="pricelist" class="form-label"> Picture </label><br>
<input type='file' id='thefile' name='fileToUpload' onchange="loadFile(event)">
<div id="rolehelp" class="form-text">Max 500 mb - (.jpg .jpeg .gif .png)</div>
</div>
<img src="../../product_images/<?php echo $product->getPhotoPath() ?>" class="img-thumbnail" alt="..." style="width:150px" id="output" />
<script>
var loadFile = function(event) {
var reader = new FileReader();
reader.onload = function() {
var output = document.getElementById('output');
output.src = reader.result;
};
reader.readAsDataURL(event.target.files[0]);
};
var filename;
document.getElementById('thefile').onchange = function() {
filename = this.value.split(String.fromCharCode(92));
document.getElementById("picturename").value = filename[filename.length - 1];
};
</script>

Related

database array not inserting in my database what is wrong?

I have a form like this
<div class="form-group">
<label class="col-sm-3 control-label">
<?php echo get_phrase('account');?>
</label>
<div class="col-md-6">
<input type="text" name="account" class="form-control" width="200px">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">
<?php echo get_phrase('dr_to');?>
</label>
<div class="col-md-6">
<input type="text" name="drto" class="form-control" width="200px">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">
<?php echo get_phrase('item');?>
</label>
<div class="col-md-6">
<input type="text" name="item" class="form-control" width="200px">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">
<?php echo get_phrase('Source_of_fund');?>
</label>
<div class="col-md-6">
<input type="text" name="sof" class="form-control" width="200px">
</div>
</div>
And another form which contain arrays like this
<tbody class="detail">
<tr>
<td class="no">1</td>
<td><input type="text" class="form-control productname" name="productname[]"></td>
<td><input type="text" class="form-control quantity" name="quantity[]"></td>
<td><input type="text" class="form-control price" name="price[]"></td>
<td><input type="text" class="form-control discount" name="discount[]"></td>
<td><input type="text" class="form-control amount" name="amount[]"></td>
<td><a href="#" class="remove">Delete</td>
</tr>
<!-- rest of table -->
i tried to insert it into the database i do not see any errors but yet still the data does not get inserted into my database the database always shows up empty this the php code i am using to do the insert
if(isset($_POST['save'])) {
$data['numb'] = $_POST['numb'];
$data['account'] = $_POST['account'];
$data['drto'] = $_POST['drto'];
$data['item'] = $_POST['item'];
$data['sof'] = $_POST['sof'];
$this->db->insert('voucherinfo', $data);
$this->db->query('voucherinfo', $data);
$id = $this->db->insert_id();
for($i = 0; $i<count($_POST['productname']); $i++)
{
mysqli_query("INSERT INTO vouchers
SET orderid = '{$id}',
issue_date = '{$_POST['productname'][$i]}',
details = '{$_POST['quantity'][$i]}',
price = '{$_POST['price'][$i]}',
amount = '{$_POST['discount'][$i]}',
unit_total = '{$_POST['amount'][$i]}'");
}
}
if(isset($_POST['save']))
{
$data['numb']=$_POST['numb'];
$data['account']=$_POST['account'];
$data['drto']=$_POST['drto'];
$data['item']=$_POST['item'];
$data['sof']=$_POST['sof'];
//use this to prevent sql injection
mysqli_real_escape_string($data);
$this->db->insert('voucherinfo' , $data);
$this->db->query('voucherinfo' , $data);
$id = $this->db->insert_id();
for($i = 0; $i<count($_POST['productname']); $i++) {
mysqli_query("INSERT INTO vouchers
SET orderid = $id',
issue_date = '$_POST['productname'][$i]',
details = '$_POST['quantity'][$i]',
price = '$_POST['price'][$i]',
amount = '$_POST['discount'][$i]',
unit_total = '$_POST['amount'][$i]'");
}
}

Dynamic display of Html div with php expression using javascript on button click

please help me with my problem, been cranking my head for this one, so basically I want to dynamically add a <div> with form elements on it. I want to append it on button click using javascript. I had it working at first until the part where I have to place a php expression on the <select> tag in the labels and values of the select option comes from my database.
HTML
<div id="file-container" class="container-fluid">
<div class="form-inline thumbnail">
<label class="sr-only">File Name</label>
<input type="text" class="form-control input-sm" name="filename[]" placeholder="File name *">
<select class="selectpicker" data-live-search="true" title="Choose Article" name="article[]">
<?php while($row_rsArticles = mysqli_fetch_assoc($rsArticles)){ ?>
<option value="<?php echo $row_rsArticles['id']; ?>" ><?php echo $row_rsArticles['name']; ?></option>
<?php } mysqli_data_seek($rsArticles, 0);?>
</select>
<div class="radio">
<fieldset id="group1">
<label class="radio"><input type="radio" class="radio" name="filemode[] id=group1" value="0">Can View</label>
<label class="radio"><input type="radio" class="radio" name="filemode[] id=group1" value="1">Can Download</label>
</fieldset>
</div>
<label for="fileinput" class="sr-only">File input</label>
<input type="file" class="form-control input-sm" name="fileinput[]">
<button type="button" class="btn btn-danger" id="deletefileinput">Delete</button>
</div>
SQL
mysqli_select_db($connection, $database);
$query_rsArticles = "SELECT * FROM article order by name asc";
$rsArticles = mysqli_query($connection, $query_rsArticles) or die("Error in retrieving article records");
$totalRows_rsArticles = mysqli_num_rows($rsArticles);
JAVASCRIPT
$(function() {
var counter = 2;
$('#addfileinput').click(function(){
var newDiv = $('<div class="form-inline thumbnail"><label class="sr-only">File Name</label><input type="text" class="form-control input-sm" name="filename[]" placeholder="File name *"><select class="selectpicker" data-live-search="true" title="Choose Article" name="article[]"><?php while($row_rsArticles = mysqli_fetch_assoc($rsArticles)){ ?><option value="<?php echo $row_rsArticles['id']; ?>" ><?php echo $row_rsArticles['name']; ?></option><?php } mysqli_data_seek($rsArticles, 0);?></select><div class="radio"><fieldset id="group'+counter+'"><label class="radio"><input type="radio" class="radio" name="filemode[] id=group'+counter+'" value="0">Can View</label><label class="radio"><input type="radio" class="radio" name="filemode[] id=group'+counter+'" value="1">Can Download</label></fieldset></div><label for="fileinput" class="sr-only">File input</label><input type="file" class="form-control input-sm" name="fileinput[]"><button type="button" class="btn btn-danger" id="deletefileinput">Delete</button></div>').append(newDiv);
counter ++;
});
});
I think ajax is the way to go. Try this approach...
HTML
<div id="file-container" class="container-fluid">
<div class="form-inline thumbnail">
<form id="articles_search">
<label class="sr-only">File Name</label>
<input id= "srch_input" type="text" class="form-control input-sm" name="filename[]" placeholder="File name *">
<button class = "btn btn-default" id="articles">Ajax</button>
</form>
<div id="srch">
</div>
<div class="radio">
<fieldset id="group1">
<label class="radio"><input type="radio" class="radio" name="filemode[] id=group1" value="0">Can View</label>
<label class="radio"><input type="radio" class="radio" name="filemode[] id=group1" value="1">Can Download</label>
</fieldset>
</div>
<label for="fileinput" class="sr-only">File input</label>
<input type="file" class="form-control input-sm" name="fileinput[]">
<button type="button" class="btn btn-danger" id="deletefileinput">Delete</button>
JAVASCRIPT
$(document).ready(function() {
$('#articles').click(function(){
var title = $("#srch_input").val();
$.ajax({
url: 'processing_php_file.php',
type: "POST",
data: {'title': $("#srch_input").val()},
processData: true,
success: function(data){
$('#srch').fadeIn(200).html(data);
},
error: function(){
}
});
});
PHP
Name of the php file should be processing_php_file.php.
<?php
mysqli_select_db($connection, $database);
$query_rsArticles = "SELECT * FROM article order by name asc";
$rsArticles = mysqli_query($connection, $query_rsArticles) or
die("Error in retrieving article records");
$totalRows_rsArticles = mysqli_num_rows($rsArticles);
while($row_rsArticles = mysqli_fetch_assoc($rsArticles));
echo '<select>';
for ($i=0; $i <sizeof($totalRows_rsArticles) ; $i++) {
echo '<option>';
echo $row_rsArticles['id'];
echo $row_rsArticles['name'];
echo '</option>';
}
echo '</select>';
?>
In this example we are querying the database via ajax call and retrieving the data from the database and showing them in the web page without page refresh.
note: You need to modify your php according to your need. I just used the code provided by you as it is just to show you the approach. I added the echo part to show the result in your webpage. You can optimize the look by css.
Hope this helps!

Display certain fields dependant on radio button select on page load

I am dragging data from a database and want to display different disabled form fields dependant on the selected radio button.
I have tried using onload="javascript:...." but it's not working.
HTML:
<fieldset>
<legend>Employment/Education Details</legend>
<div class="input-wrapper">
<label>Are you?<br>
<input type="radio" onload="javascript:employmentCheck();" name="employment_status" value="employed" id="employed" <?php if
($employment_status=="employed") echo "checked"; ?> disabled><label for="employed">Employed</label>
<input type="radio" onload="javascript:employmentCheck();" name="employment_status" value="self_employed" id="self_employed" <?php if
($employment_status=="self_employed") echo "checked"; ?> disabled><label for="self_employed">Self Employed</label>
<input type="radio" onload="javascript:employmentCheck();" name="employment_status" value="student" id="student" <?php if
($employment_status=="student") echo "checked"; ?> disabled><label for="student">Student</label>
<input type="radio" onload="javascript:employmentCheck();" name="employment_status" value="other" id="other" <?php if
($employment_status=="other") echo "checked"; ?> disabled><label for="other">Other</label>
</label>
</div>
<div id="college_nus" style="display:none">
<div class="row">
<div class="large-6 columns">
<div class="input-wrapper">
<label>College or NUS Number
<input type="text" name="college_nus" value="<?php echo $college_nus; ?>" disabled>
</label>
</div>
</div>
</div>
</div>
<div id="employment_details" style="display:none">
<div class="row">
<div class="large-6 columns">
<div class="input-wrapper">
<label>Employer Name
<input type="text" name="employment_company" value="<?php echo $employment_company; ?>" disabld>
</label>
</div>
</div>
<div class="large-6 columns">
<div class="input-wrapper">
<label>Job Title
<input type="text" name="employment_title" value="<?php echo $employment_title; ?>" disabled>
</label>
</div>
</div>
</div>
<div class="row">
<div class="large-6 columns">
<div class="input-wrapper">
<label>Employment Address
<textarea name="employment_address" rows="4" value="<?php echo $employment_address; ?>" disabled></textarea>
</label>
</div>
</div>
<div class="large-6 columns">
<div class="input-wrapper">
<label>
Occupation
<input type="text" value="<?php echo $occupation; ?>" disabled>
</label>
</div>
</div>
</div>
<div class="row">
<div class="large-6 columns">
<div class="input-wrapper">
<label>Employment Email
<input type="text" name="employment_email" value="<?php echo $employment_email; ?>" disabled>
</label>
</div>
</div>
<div class="large-6 columns">
<div class="input-wrapper">
<label>Employment Phone
<input type="text" name="employment_phone" value="<?php echo $employment_phone; ?>" disabled>
</label>
</div>
</div>
</div>
</div>
</fieldset>
Javascript:
function employmentCheck() {
if (document.getElementById('student').checked) {
document.getElementById('college_nus').style.display = 'block';
}
else document.getElementById('college_nus').style.display = 'none';
if (document.getElementById('employed').checked || document.getElementById('self_employed').checked) {
document.getElementById('employment_details').style.display = 'block';
}
else document.getElementById('employment_details').style.display = 'none';
}
Can anyone help please?
I changed the function to window.onload and it worked fine. Here is a plunker.
https://plnkr.co/edit/Pz2rKRg9geglgKhdJM4H?p=preview
Here is the function
window.onload = function(){
if (document.getElementById('student').checked) {
console.log("student");
document.getElementById('college_nus').style.display = 'block';
}
else {
document.getElementById('college_nus').style.display = 'none';
}
if (document.getElementById('employed').checked || document.getElementById('self_employed').checked) {
console.log("employed");
document.getElementById('employment_details').style.display = 'block';
}
else {
document.getElementById('employment_details').style.display = 'none';
}
}
I don't think there is an event of onload defined on the radio button object.
Thanks
Paras

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>

Pass form Variables to $_SESSION by AJAX in wordpress

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/

Categories

Resources