Passing input value via button click to php function in script - javascript

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");
});
});

Related

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 js variable into hidden form field?

I want to pass js variable into hidden form field value. I set value using php echo code but it is not working.
js variable :-
<script type="text/javascript"> var demo = 1; </script>
html :-
<input type="hidden" name="demo_val" value="<?php echo <script>demo</script>" id="demo_val"/>
and in js file call hidden field value :-
$('#demo_val').val();
but it is not working...
How to do it..?
Remove this <?php echo <script>demo</script> from hidden field and leave it blank.
Write followed code
var demo =1;
$('#demo_val').val(demo);
in your script.
You can get value by
var field_vemo = $('#demo_val').val();
Put
document.getElementById("demo_val").value = demo;
in your javascript section
you should pass the variable since javascript yo input hidden, not it´s good idea pass the variable with , you can use jQuery :
var demo = "hola";
$('#demo_val').val(demo);
Now input with name demo_val should have the value "hola"
If you like get the value you can
var valueDemo = $('#demo_val').val();
try this
<input type="hidden" name="demo_val" value="" id="demo_val"/>
<script type="text/javascript">
var demo = 1;
$(document).ready(function() {
$('#demo_val').val(demo);
});
</script>

Javascript two weird problems: POST not working, window.location.href not working

I created an instant search similar to google search using JQuery. The highlighted code doesn't work. It is weird since they work fine by its own and everything else works fine. Any idea why this is happening?
Q1.
searchq() works fine, but the createq() function doesn't work, and the variable txt could be posted to other files(search.php). However, the function createq() can't POST. It does get the global variable txt after testing, but the php file(create_object.php) can't get it no matter what POST method I used. Could anyone helps to write a bit POST code which can work in my code.
Q2
I want to create a function that,when the enter is pressed, the user will be redirected to the first search result(which is anchored with an url) . To achieve this, I create a function that variable redirectUrl got the anchored url as string, however, the redirect function window.location.href doesn't work, the page simply refreshed. I tested window.location.href function by its own in another file, it works though. It is so weird that my page simply refreshed, It even refreshed when I direct to google. window.location.href("www.google.com").
Note that I didn't include the connect to database function here. Coz I think the database username and password setting would be different to yours.So please create your own if you want to test it. The mysql is set with a table is called "objects", and it has one column named "name".
Thanks in advance!
<html>
<!-- google API reference -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<!-- my own script for search function -->
<center>
<form method="POST">
<input type="text" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
<div id="output">
</div>
</form>
</center>
<!-- instant search function -->
<script type="text/javascript">
function searchq(){
// get the value
var txt = $("input").val();
// post the value
if(txt){
$.post("search.php", {searchVal: txt}, function(result){
$("#search_output").html(result+"<div id=\"create\" onclick=\"creatq()\"><br>Not found above? Create.</div>");
});
}
else{
$("#search_output").html("");
}
};
function createq(){
// allert for test purpose: test if the txt has got by the createq function
alert(txt);
**$.post( "create_object.php",{creatVal:txt} );**
}
// if enter key pressed, redirect page to the first search result
$("#search").keypress(function(evt){
if (evt.which == 13) {
// find the first search result in DOM and trigger a click event
var redirectUrl = $('#search_output').find('a').first().attr('href');
alert(redirectUrl);
**window.location.href = "www.google.com";
window.location.href = "www.google.com";**
}
})
</script>
</html>
PHP file (search.php)
<?php
if(isset($_POST["searchVal"])){
//get the search
$search=$_POST["searchVal"];
//sort the search
$search=preg_replace("#[^0-9a-z]#i","",$search);
//query the search
echo "<br/>SELECT * from objects WHERE name LIKE '%$search%'<br/>";
$query=mysqli_query($conn,"SELECT * from objects WHERE name LIKE '%$search%'") or die("could not search!");
$count=mysqli_num_rows($query);
//sort the result
if($count==0){
$output="there was no search result";
}
else{
while($row=mysqli_fetch_assoc($query)){
$object_name=$row["name"];
$output.="<div><a href='##'>".$object_name."</a></div>";
}
}
echo $output;
}
?>
php file (create_object.php)
<?php
if(isset($_POST["createVal"])){
$name=$_POST["createVal"];
var_dump($name);
}
?>
Try to bind the input with id
var txt = $("input").val();
<input type="text" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
Change above to this
var txt = $("#searchinput").val();
<input type="text" id="searchinput" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
and I think you are trying to show the search result here
<div id="output"></div>
and the jQuery binding is this in your code
$("#search_output").html("");
So change the HTML to this
<div id="search_output"></div>
also this in our code
$("#search").keypress(function(evt){
there is not HTML element bind with it and I think you are trying to bind it with search input so change above to this
$("#searchinput").keypress(function(evt){
The above change should also resolve the window.location.href not working problem
So the HTML will be;
<form method="POST">
<input type="text" id="searchinput" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
<div id="search_output"></div>
</form>
and Script will be
<script type="text/javascript">
function searchq(){
// get the value
var txt = $("#searchinput").val();
// post the value
if(txt){
$.post("search.php", {searchVal: txt}, function(result){
$("#search_output").html(result+"<div id=\"create\" onclick=\"creatq()\"><br>Not found above? Create.</div>");
});
}
else{
$("#search_output").html("");
}
}
function createq(){
// allert for test purpose: test if the txt has got by the createq function
alert(txt);
**$.post( "create_object.php",{creatVal:txt} );**
}
// if enter key pressed, redirect page to the first search result
$("#searchinput").keypress(function(evt){
if (evt.which == 13) {
// find the first search result in DOM and trigger a click event
var redirectUrl = $('#search_output').find('a').first().attr('href');
alert(redirectUrl);
**window.location.href = "www.google.com";
window.location.href = "www.google.com";**
}
});
</script>
Note: If you check browser console, you may see some errors, there are some typo mistakes like missing ; in your JS too.
In the PHP, here
if($count==0){
$output="there was no search result";
}
else{
while($row=mysqli_fetch_assoc($query)){
$object_name=$row["name"];
$output.="<div><a href='##'>".$object_name."</a></div>";
}
}
$output. is wrong with dot, so change it to following
if($count==0){
$output="there was no search result";
}
else{
while($row=mysqli_fetch_assoc($query)){
$object_name=$row["name"];
$output="<div><a href='#'>".$object_name."</a></div>";
}
}
Two things:
Input search id is not defined, $("#search").keypress won't work. Change to:
< input type="text" name="search" id="search" style="width:400px " placeholder="Search box" onkeyup="searchq();" >
Div id "output", should be "search_output", as required in $("#search_output"). Change to:
< div id="search_output" >
< /div >

pass JavaScript variable to HTML input box and (to use in PHP file)

I'm trying to pass a JavaScript variable to the value of an hidden input button to use in my PHP file output.
My HTML is:
<input type = "hidden" id = "location2" name = "location2" value = ""/>
I'm using this onclick="myFunction();" in my "Submit Form" input to run the function as it is not able to be done in the window.load()
My JavaScript below is calling indexes from another function and assigning the text to the variable 'location' (I know this sounds strange but it was the only way I have got it to work so far):
function myFunction() {
var x = document.getElementById("box2").selectedIndex;
var y = document.getElementById("box2").options;
var location=(y[x].text);
document.getElementById("location2").value=(location);
}
Any help would be hugely appreciated as I am really struggling and have been working on this for some time (as you can probably tell, I dont really know what I'm doing) - I just need to call the value of this variable into my PHP file output and the majority of my web form is completed.
Thanks very much
Marcus
I've just changed my HTML as follows
I've removed myFunction from my submit
I've added the following HTML button:
<button onclick="myFunction();" id = "location2" name = "location2" value="">Click me</button>
The variable is now passing!!!! The only problem is when I press the onclick button, it is now submitting my form!!
Is it okay for me to replace my previous submit button with this code??
THANKS TO EVERYONE FOR THEIR HELP ON THIS!!
I Was not sure what you doing but below example may help you. It will post the value as well as the option text.
Here we are using print_r to print the $_POST array from the AJAX Request. using this method, you should be able to debug the issue.
<!DOCTYPE html>
<html>
<body>
<?php if($_POST) {
print_r($_POST); die;
} ?>
<form name="" id="" method="post" >
Select a fruit and click the button:
<select id="mySelect">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
<input type = "hidden" id = "location2" name = "location2" value = ""/>
<input type = "hidden" id = "locationname" name = "locationname" value = ""/>
<button type="submit" id="submit">Display index</button>
</form>
<script>
function myFunction() {
var x = document.getElementById("mySelect").selectedIndex;
var y = document.getElementById("mySelect").options;
//alert("Index: " + y[x].index + " is " + y[x].text);
document.getElementById("location2").value=(y[x].index);
document.getElementById("locationname").value=(y[x].text);
//alert($("#location2").val());
}
var submit = document.getElementById('submit');
submit.onsubmit = function(e){
myFunction();
};
</script>
</body>
</html>
i'm assuming your form method is 'POST' and action value is the same php page where you are expecting to see the 'location2' hidden input value, if that is the case, you can use $_POST['location2'] to get the value in that php page.
Yes it is fine to use button tag by default it acts like the submit button inside the form tag. You can also make it act like button(won't submit the form) by using the attribute type='button'.
Edited
button or input type='submit' can submit the form only when it is placed within the form tag(without javascript).
<form action='http://www.stackoverflow.com/'>
<button>stackoverflow</button> <!-- this works -->
</form>
<form action='http://www.stackoverflow.com/'></form>
<button>stackoverflow</button><!-- this won't work -->
var go = function() {
document.forms[0].submit();
};
<form action='http://www.stackoverflow.com/'></form>
<button onclick='go()'>stackoverflow</button><!-- still works -->

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