Retriving a value from a textbox - javascript

I have textbox , i want to retrive the value from the textbox and store it in a php variable . Its not inside a form tag. I am creating a e-commerce website for my class assignment . I retrive each product and display it in the website. I have a quantity text box and a "add to cart button". The value in the cart need to be added to the database
while($row_pro =mysqli_fetch_array($row_mysql) )
{
$product_id=$row_pro['productID'];
$product_name =$row_pro['productName'];
$product_desc= $row_pro['productDesc'];
$product_price= $row_pro['price'];
$product_vendor=$row_pro['Vendor'];
$product_images=$row_pro['image'];
echo "<a href='detail.php?productID=$product_id'><h3>$product_name</h3></a>
<a href='detail.php?productID=$product_id'><img src='images/$product_images' width='180px' height='280px'/></a>
<p>$product_desc</p>
<p>$product_vendor</p>
<h4>$product_price</h4>
<input type='text' name='quantity'>
Add to cart</button>
";
}

You could do something like this:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<input type='text' name='quantity' />
<a id="linkclicker" href='product_display.php?addtocart=1'><button>Add to cart</button></a>
<script type="text/javascript">
$('#linkclicker').click(function() {
var quant = $('input[name="quantity"]').val();
$(this).attr('href', $(this).attr('href') + '&param=' + quant);
});
</script>
Change param to the parameter you want. linkclicker you also might want to change to something more descriptive.
You also could validate that quant is an int if that is a requirement. Don't trust that value though in your next script.
I would probably have done this with an HTML form..

Related

Passing input value via button click to php function in script

I need to use the value from an input field - without a POST - to do a lookup from an external source.
The input field has a button associated with it, which calls the script on button press. So I need to put the input field (id = 'lookup') into the function's parameter (the function is called within the script).
This is the code line in the script that needs the value from the input field (input field called 'lookup')
<?php $product_name = api_request(lookup);?>
My code is below.
(NB: I know about 'PHP is server side, JS is client site'. But the button click does call the PHP function, and the code does display the return value of the function if you do this instead:
<?php $product_name = api_request('1234');?>
which will return "My Product Name" via my api_request() function.)
What is needed to put a script variable in the api_request()'s parameter?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<p>Part Number = <input type="text" id="lookup" value= "12345"></p>
<button>Get product name for this part number</button>
<div id='product_name'>Product Name Goes Here </div>
<script>
$(document).ready(function(){
$("button").click(function(){
// returns value of input field
var lookup = document.getElementById('lookup');
// need to put the input field 'lookup' into the function's parameter
<?php $product_name = api_request(lookup);?>
var product_name = "<?php echo $product_name; ?>";
$('#product_name').text(product_name); // display it on the screen in that div ID
});
});
</script>
</body>
</html>
<?php
function api_request($partnumber) {
// code that returns the product name for that part number, hard coded here
$product_name = "My Product Name";
return $product_name;
}
As you already understand PHP is server and JS is client, you cannot directly use JS variables in PHP.
There are two ways by which you can.
$_POST which you already said you don't want to use. I assume the reason for not using $_POST is that browser prompts to continue refreshing page.
Use $_GET which will add a param in your url.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="get">
<p>Part Number = <input type="text" id="lookup" name="lookup" value= "12345"></p>
<button>Get product name for this part number</button>
</form>
Additionally add this small line in the beginning of your file to access is as a PHP variable.
$lookup = $_GET["lookup"];
ajax is possible.
try this
create file : api_request.php
<?php
function api_request($partnumber) {
// code that returns the product name for that part number, hard coded here
$product_name = "My Product Name";
return $product_name;
}
$number = $_GET["part"];
$product_name = api_request($number);
echo json_encode(array( "product_name" => $product_name ));
And Modify the javascript with this
$(document).ready(function(){
$("button").click(function(){
// returns value of input field
var lookup = document.getElementById('lookup');
// need to put the input field 'lookup' into the function's parameter
$.get(`api_request.php?part=${ lookup.value }`,(resp)=>{
$('#product_name').text(resp.product_name); // display it on the screen in that
},"json");
});
});

How to submit a form as well as execute a javascript function in clicking an input button?

This code works, but it shows the heading only for an instant, How we can execute an sql query as well as javascript function to change the innerHTML on a form submission.
//HTML
<div id='heading'> </div>
//form
<form method='post'>
<input type='submit name='option' value='option' onclick='myFunction()' >
</form>
//sql query
if(isset($_POST['option'])===true && empty($_POST['option']===true)){
$sql2= 'SELECT * from maptable ORDER by price';
$result = $mysql->query($sql2);
}
//javascript function
<script>
function myFunction(){
document.getElementById('heading').innerHTML ='OptionName';
}
</script>
<input type='submit name='option'
Look at your code here. You skip a quote It should be like this <input type='submit' name='option'
As I see your form submitting without AJAX, so once you click "submit" button, the page will be reloaded and return a result of PHP script execution.
If you want to run your "myFunction" before submitting you can do this:
<form id="myForm">
...
</form>
<input type='button' name='option' onclick="myFunction()">
And "myFunction":
function myFunction(){
document.getElementById('heading').innerHTML ='OptionName';
document.getElementById('myForm').submit();
}
OR, if you want the "heading" div to be shown some time, you can submit the form using timeout:
function myFunction() {
document.getElementById('heading').innerHTML = 'OptionName';
setTimeout(function() {
document.getElementById('myForm').submit();
}, <timeout of submitting in milliseconds>);
}
If my understanding is correct, You want to call the function before the PHP code is executed.
Just change onclick="myFunction()" to onsubmit= "return myFunction()".
It's also a good practice to surrond your document.getElemen.... with a try catch block.
The way you are executing this at the moment isn't going to work. You are posting directly to the same page with your form without AJAX which means the page refreshes. Since JavaScript is client side, it's not going to persist your heading's innerHTML that you set. There are a million and one ways to fix this.
The quickest way to "fix" this is declare what you want the heading to be in your PHP processing and then output that in the H1 element if it exists:
#PHP
if(isset($_POST['option'])===true && empty($_POST['option']===true)){
$sql2= 'SELECT * from maptable ORDER by price';
$result = $mysql->query($sql2);
// Depending on what you want your Heading to be
// $headingName = $_POST['option'];
$headingName = "OptionName";
}
Set your HTML heading like so:
<div id='heading'><?php echo isset($headingName) ? $headingName : '' ?></div>
Also, your input is missing a quotation, and with this change, you don't need the JavaScript portion anymore:
<input type='submit' name='option' value='option'>

How to pass a Javascript ID value into a form Placeholder?

I have used a function to capture the Query String value of "name" - i.e. imagine a party invite site;
https://cometomyparty.com?name=phil
The function used is;
script type="text/javascript">
function getQuerystring(){
var q=document.location.toString();
q=q.split("?");
q=q[1].split("&");
var str=""
for(i=0;i<q.length;i++){
tmp=q[i].split("=")
str+=" "+tmp[1]+"<br />"
}
document.getElementById("name").innerHTML=str
}
onload=function(){
getQuerystring()
}
</script>
Then I can call the value of 'name' using id="name" where I want to use this on my page, i.e. in the heading, I could say, Phil, looking forward to having you at the party...
That's working well. The problem I have is, I have a Form I'm using as well, and within that, it has a Placeholder field, like so;
<div class="form-section">
<input type="text" name="name" class="validate-required" placeholder="Names">
How can I insert my 'id' value of 'name' into my placeholder here? The end result would be, the invite mechanic would work on the same URL, across multiple invitees, but the URL would just change. The RSVP form would reflect what is in the URL as the placeholder, yet the user could still update it if it was incorrect.
Any advice appreciated.
This find placeholder and change using jquery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#name').attr("placeholder", "your place holder here");
});
</script>
if it's a $var also don't need quotes would be like
$('#name').attr("placeholder", $str);
Or using javascript
<script type="text/javascript">
function getQuerystring(){
var q=document.location.toString();
q=q.split("?");
q=q[1].split("&");
var str=""
for(i=0;i<q.length;i++){
tmp=q[i].split("=");
str+=" "+tmp[1]+"<br />";
}
document.getElementById("name").innerHTML=str;
document.getElementById("name").placeholder=str;
}
onload=function(){
getQuerystring();
};
</script>
document.getElementById("name").placeholder="value here" if it's a var so don't need quotes
Also you need to insert an id to your html input field
<div class="form-section">
<input type="text" id="name" name="name" class="validate-required" placeholder="Names">

How to Use one function for input classes with diffrent id's

I am working on a new project and i have created a search where users can search the app for other users.
So basically i have a price input box and a counter beside for every user.
The problem is It only changes the value of the price for the first user that was queried from the SQL database.
I know its because i put an id on the price form field.
I just don't know to how to to get values for other users after the first one
and I don't know how to write a code without using 'get element by id' .
I am new to javascript any help would be appreciated please.
Thanks.
Here's the php and mysql code:
$con = mysqli_connect("localhost","root","","testing");
$q = mysqli_query($con,"SELECT * FROM user");
while($row = mysqli_fetch_assoc($q)){
if($row['image'] == ""){
echo "<span class = 'userpic'><img width='100' height='100' src='images/verify.jpg' alt='Default Profile Pic'> </span>";
} else {
echo "<span class = 'userpic'><img width='100' height='100' src='images/".$row['image']."' alt='Profile Pic'</span>";
}
echo "
<span class = 'username'>".$row['username']."</span>
<form name = 'matchcreator' class = 'amount' action='arena.php' method ='post'>
<input class='price' textarea class='price-box' type='text' id='price1' name='price' size='1' maxlength = '15' value='0'/>
<button class='up' type ='button' onclick='incrementValue();'><img src='images/up.png' width='10px' height='10px' href='#'> </button>
<button class='down' type ='button' onclick='decreaseValue();' ><img src='images/down.png' width='10px' height='10px' href='#'></button>
<div class = 'light'>
</div>
<div class = 'light2'>
</div>
<div class = 'light3'>
</div>
<div class = 'light4'>
</div>
<div class = 'light5'>
</div>
<button class='send' type = 'submit' onclicl=onclick='return confirm('Are you sure?')'>Send Challenge</button>
</form>
";
echo "<br>";
}
?>
Here's the javascript :
function incrementValue()
{
var value = parseInt(document.getElementById('price1').value, 0);
value = isNaN(value) ? 0 : value;
value++;
document.getElementById('price1').value = value;
}
function decreaseValue()
{
var value = parseInt(document.getElementById('price1').value, 0);
value = isNaN(value) ? 0 : value;
value--;
document.getElementById('price1').value = value;
}
Please kindly help me out
I would recommend using jQuery if you're not really experienced with Java Script.
With jQuery this is very easily accomplished by doing:
<!doctype html>
<html lang="en">
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<input class='price' textarea class='price-box' type='text' id='price1' name='price' size='1' maxlength = '15' value='0'/>
<button class='up' type ='button' onclick='change();'>
<button class='down' type ='button' onclick='change();'>
<script>
function change(){
var text = $(".price").text();
alert(text + " " + $.isNumeric(text));
}
</script>
</body>
</html>
Your title and question do not seem to mirror each other. The question:
"How to Use one function for input classes with diffrent id's"
Use jQuery.
To use one function with onclick by id, class, element
ELEMENT:
$('element').on('click',function(){
//do something.......
});
ID:
$('#id').on('click',function(){
//do something.......
});
CLASS:
$('.class').on('click',function(){
//do something.......
});
MULTIPLE ID's
$('#id1').add('#id2').on('click',function(){
//do something.......
});
Or just fire the onclick attribute.
Your HTML
<button name="x" id="x" onclick="doSomething();">
The Function
function doSomething(){
//do something.......
}
Instead of using "on.('click',function) you could also use:
$('.class1').add('.class2').add('.class3').click(function(){
//do something.........
});
You can also mix it up and add IDs, Classes, and elements but it makes managing the firing of all of these clicks a pain.
Be sure to put your javascript and or jquery between <script></script> tags if you have them in your HTML markup. Only mentioning this since you say you are not very familiar with Javascript.
You could also set the jQuery click methods when the document loads like this:
$(document).ready(function(){
//put any one of the above methods here.
});

Get the value of a hidden input in server side Php which was set by javascript

This wordpress stuff driving me mad again.
I have an output page which uses a short code to call a function (Stores)... the code of which in part is beneath.
It has a dropdown and a table of data, ..the data being dependant on the selected option of the drop down.
I use javascript to set the hidden input...successfully.
In fact I tried a normal, non hidden input as well...same result,..on server side, with$_POST["txtSelection"] or
$_POST["hdnSelect"]
But when I try get it's value on the php server side code, it is empty,..
How on earth do I retrieve it?
the hidden input is inside the form tag.
<?php
function Stores()
{
global $wpdb;
global $MyPage;
$MyPage = str_replace( '%7E', '~', $_SERVER['REQUEST_URI']);
?>
<form name="frmSB_stores" method="post" action="<?php echo $MyPage ?>">
<input type="hidden" name="hdnSelect" id="hdnSelect" value="">
<input type="text" name="txtSelection" size="19" id="txtSelection" value="">
<script type="text/javascript">
function SetDDLValueOnChange (objDropDown) {
var objHidden = document.getElementById("hdnSelect");
if ( objDropDown.value.length > '0')
{
objHidden.value = objDropDown.value; //.substr(0,1);
//alert(" hdn = " + objHidden.value);
window.location = '<?=$MyPage;?>' ;
}
}
</script>
the dropdown's markup here,..then
<table width='100%' border='0' cellspacing='5' cellpadding='3'>
<?php
$Area = $_POST['txtSelection']; //or $_POST['hdnSelect']
which has zilch in it , even though it is set successfully by jvascript
Why is this such an issue in WordPress,
How do i overcome it.
It's nuts spending a full day on something which should be so trivial (works fine in a normal php situation, os asp or asp.net,..but not in WP.)!
TIA
N
This doesn't submit the form it just tell the browser to goto that page. Hence your value always empty.
window.location = '<?=$MyPage;?>' ;
Replace that line with this instead.
document.forms["frmSB_stores"].submit();

Categories