I've read lots of threads on passing Jquery variables to PHP, however almost all of the posts were on the "Expert" level, and i couldn't understand a single thing (PHP/Jquery beginner here). Hopefully I can get some help.
Once the user selects from the drop down list, the script function will run. I want to get the user's selection from jquery to a php variable. From then, I want to use the user's selection to retrieve data from the database and display values on the same page itself.
I'm not getting any output.
EDITED: So this is what I did after looking at the ajax function
AFile.php
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#company').change(function(){
$.ajax({
type: 'GET',
url: '<?php echo url_mgt::getTest(); ?>',
data: 'company_name=' + $('#company').val(),
success: function(msg) {
$('#other').html(msg);
}
});
});
});
</script>
</head>
<body>
<select id="company" name="company">
<option value="Company_A">A</option>
<option value="Company_B">B</option>
<option value="Company_C">C</option>
<option value="Company_D">D</option>
</select>
<div id="other"></div>
</body>
companyArray.php
<?php
require('protect.php');
require_once(dirname(__FILE__) . '\..\controller\company_controller.php');
require_once(dirname(__FILE__) . '\..\controller\url.php');
$companyCtrl = new company_controller();
$compArray = $companyCtrl->retrieveAllCompany();
if($_GET['company_name']) {
$get_comp = $_GET['company_name'];
$inSpace = str_replace("_"," ", $get_comp);
foreach($compArray as $company) {
$comp_name = $company->getCompanyName();
if($get_comp == $company) {
$comp_add = $company->getCompanyAddress();
echo $comp_add;
}//end if
}//end foreach
} //end if
?>
I inspected element, but when i click on the drop down list nothing happens, i doubt its going to the companyArray.php. I also don't think its the url_mgt::getTest() link because ive been using this url pattern throughout the project.
use Ajax request on change and then populate the received values from the server on success and you can do what you are asking for.
note: you can't pass a variable from client side (js) to server side (php) without sending it as a request.
You aren't concatenating your data.
'company_name=' $('#company').val(),
should be
'company_name=' + $('#company').val(),
Related
I'm loading values from an XML file and then updating the XML with a form on a php page. My problem is this - I have a query running a count on nodes, which works perfectly fine, but I also want to update nodes with the count and get accurate values back. When I submit my form, it submits the values as they are when I load the file, but in order to update the count properly (because I need the updated node count) I need to have it submit twice. I've tried to have it submit the form on a body onload function but from what I can ascertain when you hit the submit button it doesn't do a true full page refresh. It reloads the page but I've been unable to have it actually run any scripts or onload functions. The alternative that I thought of but can't figure out how to implement is having the count go down if I change the option value to closed.
<!DOCTYPE html>
<?php
$xml->load('test.xml');
$xpath = new DOMXpath($xml);
$liftsopen = $xpath->query("//node/Lifts-Open")->item(0);
$lift1status = $xpath->query("//areas/area[#name='Lift1']/lifts/lift[#name='Lift1']/#status")->item(0);
$lift2status = $xpath->query("//areas/area[#name='Lift2']/lifts/lift[#name='Lift2']/#status")->item(0);
$liftcount = 0;
foreach ( $xpath->query('//lifts/lift[#status="OPEN"]') as $count1 ) {
$liftcount++;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$lift1->nodeValue = $_POST['lift1statusform'];
$lift2->nodeValue = $_POST['lift2statusform'];
$liftsopen->nodeValue = $liftcount;
$xml->save('test.xml');
}
?>
<body>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<h4>Lift1</h4>
<select name="lift1statusform" >
<option selected value="<?= htmlspecialchars($lift1status->nodeValue) ?>"><?= htmlspecialchars($lift1status->nodeValue) ?></option>
<option value="OPEN">OPEN</option>
<option value="CLOSED">CLOSED</option>
</select>
<h4>Gondola</h4>
<select name="lift2statusform" >
<option selected value="<?= htmlspecialchars($lift2status->nodeValue) ?>"><?= htmlspecialchars($lift2status->nodeValue) ?></option>
<option value="OPEN">OPEN</option>
<option value="CLOSED">CLOSED</option>
</select>
<input name="submit" type="button" value="Save"/>
</form>
</body>
</html>
used the following Ajax function to submit the form twice:
function Test() {
var form = $('form');
$.ajax({
type: 'POST',
url: form.attr('action'),
data: form.serialize(),
success: function(data) {
$.ajax({
type: 'POST',
url: form.attr('action'),
data: form.serialize(),
success: function(data) {
location.reload(true);
}
});
}
});
}
Would AJAX be a valid solution to your problem?
If you need to perform multiple "form submits", you should check out the capabilities of AJAX. Ajax allows you to send exchange data with a back-end PHP file without leaving (or even refreshing) the current page. Perhaps it is your solution.
As with most js actions, it can be event-driven (that is, triggered one-or-more-times by some event), or repeated inside a loop, etc.
AJAX is most implemented using the jQuery library:
$(document).ready(function(){
$.ajax({
type: 'post',
url: 'my_backend_file.php',
data: {varname:value}
}).done(function(recd){
console.log('data recd from PHP side, if needed: ' + recd);
});
});
although it is equally well handled in vanilla js also.
References and Other Examples:
https://stackoverflow.com/a/54332971/1447509
Should I have one form or two separate forms
https://www.html5rocks.com/en/tutorials/file/xhr2
Hope someone can help me..
i made my program more simpler so that everybody will understand..
i want my program to get the value of the without submitting, i know that this can only be done by javascript or jquery so I use the onChange, but what I want is when i select an option the value should be passed immediately on the same page but using php..
<select id="id_select" name="name" onChange="name_click()">
<option value="1">one</option>
<option value="2">two</option>
</select>
<script>
function name_click(){
value_select = document.getElementById("id_select").value;
}
</script>
and then i should pass the value_select into php in post method.. i dont know how i will do it.. please help me..
You cannot do this using PHP without submitting the page. PHP code executes on the server before the page is rendered in the browser. When a user then performs any action on the page (e.g. selects an item in a dropdown list), there is no PHP any more. The only way you can get this code into PHP is by submitting the page.
What you can do however is use javascript to get the value - and then fire off an AJAX request to a php script passing the selected value and then deal with the results, e.g.
$(document).ready(function() {
$('#my_select').on('change', do_something);
});
function do_something() {
var selected = $('#my_select').val();
$.ajax({
url: '/you/php/script.php',
type: 'POST',
dataType: 'json',
data: { value: selected },
success: function(data) {
$('#some_div').html(data);
}
});
}
With this code, whenever the selected option changes in the dropdown, a POST request will be fired off to your php script, passing the selected value to it. Then the returned HTML will be set into the div with ID some_div.
not sure ..but i guess ajax is what you need..
<script>
function name_click(){
value_select = $("#id_select").val();
$.post('path/to/your/page',{"value":value_select},function(data){
alert('done')
})
}
</script>
PHP
$value=$_POST['value']; //gives you the value_select data
Post with ajax as Alex G was telling you (+1) and then handle the post with PHP. You can define a callback in Javascript which will run when the page responds.
My suggestion go with jquery. Try with this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
<script>
$(document).ready(function(){
$("#id_select").change(function(){
var url = 'http:\\localhost\getdata.php'; //URL where you want to send data
var postData = {'value' : $(this).value};
$.ajax({
type: 'POST',
url: url,
data : postData,
dataType: 'json',
success: function(data) {
//
},
error: function(e) {
console.log(e.message);
}
});
})
})
</script>
In getdata.php
<?php
var $value = $_POST['value'];
// you can do your logic
?>
I've written a script using jQuery Ajax and PHP which should fetch data from a MySQL database and append the result as an <option> within a <select> element.
The code should work like this:
When the name in the text input changes, all options of class .modpick are removed from the <select> element. An Ajax call then connects to a PHP script which checks whether there is more than one record in the database with the same name. If not, another Ajax call connects to another PHP script which pulls the data from the database and echos it out as an <option> element. The Ajax callback then appends the data from the PHP script to the <select> element.
The problem I'm having is that sometimes the <option> element is appended twice, so when you open the <select> element it displays the same <option> twice. What is really confusing is that this doesn't happen all the time - only occassionally.
I can't figure out why this is happening, especially as it doesn't happen every time, nor can I identify whether it's a problem with the jQuery or the PHP. Any help would be greatly appreciated.
The code:
jQuery:
$(document).on('change', "#uploadname", function () {
uploadname = $(this).val();
$('.modpick').remove();
$.ajax({
url: "uploadnames.php",
type: "POST",
data: {
uploadname: uploadname
},
success: function (data) {
$('#checkulinputs').html(data);
uploademailcheck = $('#emailupcheckinput').val();
if (uploademailcheck == 'nochoose') {
uploademail = '';
$('#ulemailcheck').slideUp();
$.ajax({
url: "uploadnamesmodules.php",
type: "POST",
data: {
uploadname: uploadname
},
success: function (data) {
$(data).appendTo($('#uploadmoduleselect'));
}
});
}
}
})
})
PHP:
include_once('../../dbconnect.php');
$name = mysqli_real_escape_string($conn, $_POST['uploadname']);
$query = "SELECT * FROM marking_assignments WHERE name = '$name' ORDER BY unit ASC";
$details = $conn->query($query);
while ($row = $details->fetch_assoc()){
$modnamequery = "SELECT mod_name FROM modules WHERE module = '" . $row['unit'] . "'";
$modname = $conn->query($modnamequery);
while ($line = $modname->fetch_assoc()){
$descrip = $line['mod_name'];
}
echo '<option value="' . $row['unit'] . '" id="m' . $row['unit'] . '" class="modpick">' . $descrip . '</option>';
}
HTML (After query has been run - note the two identical <option> elements):
<form id="uploadfeedbackform" method="POST" action="uploadfeedback.php">
<input type="text" class="inputs" name="upload_name" id="uploadname" placeholder="Enter Student Name" />
<div id="checkulinputs"></div>
<div id="ulemailcheck" class="emailchecker"></div>
<select id="uploadmoduleselect" name="uploadmodules">
<option value="choose" class="choosemod">Select Module</option>
<option value="405" id="m405" class="modpick">4.05 Managing Health & Safety at Work</option>
<option value="405" id="m405" class="modpick">4.05 Managing Health & Safety at
</select>
</form>
Seems to me that your change handler can be called multiple times, leading to multiple ajax requests which (quite rightly) fire their success callbacks.
Ajax requests will just queue up rather than replacing the previous request, leading to a possible queue of pending callbacks.
You can store the ajax request in a variable and abort() the request in the event that your handler somehow gets called twice.
Example:
var myRequest;
//in your change handler...
if (myRequest)
{
myRequest.abort();
}
myRequest = $.ajax({...});
This way there will only be one active ajax request at a time, and only one success callback that is pending.
I am working on a form in which changing one "select" element modifies the values of another "select" element. The values of both the elements come from a MSSQL database. What is the best way to implement code that can accomplish this?
There are two ways that I can think to do it.
Store the table into a javascript variable and make the onchange event of the first element modify the second element.
Send a GET request to the page and reload it, using PHP to modify the second element.
I don't like the first method because storing the database from the PHP side to the javascript side seems kind of hacky and really cumbersome to do. I don't like the second way either, because reloading the page disrupts the user experience and makes him have to scroll down again.
You should use AJAX to pull in data and populate the second select element. In a nutshell, AJAX is simply a separate page request that happens behind the scenes. You can use it to load a simple HTML page or partial and display it in a DOM element, or you can use it to dynamically retrieve structured data.
The best way to do this would be using JSON (JavaScript Object Notation). In this case, you would use Javascript to make an AJAX call to a PHP page, and that PHP page would take an argument in the query string that represents the value of the first select element. With that, you would make a call to your MSSQL database to get all of the corresponding options for the second select, and then echo those out. In turn, the Javascript you use to make the AJAX request can parse the response and interpret it as a JavaScript object literal, allowing you to loop through the results and do what you want with them.
Here's an example (I'm using jQuery, since it makes AJAX really easy).
At the top of your form page:
$(document).ready(function() {
$('#select1').change(function() {
var select1val = $(this).val();
$.getJSON('/path/to/response.php', 'select1=' + select1val, function(response) {
$('#select2').empty();
if(response) {
for(var option in response) {
$('<option/>').val(option.value).html(option.label).appendTo($('#select2'));
}
}
});
});
});
And then your response.php page should look like this:
<?php
$select1 = $_GET['select1'];
// Do validation here, to make sure it's a legitimate value for select1. Never trust the
// user input directly.
// Replace this with whatever code you use to make DB queries.
$options = $mydb->query("SELECT value,label FROM select2_options WHERE select1_value=?", $select1);
echo json_encode($options);
Use Ajax if you don't want to reload the page. Read more about AJAX
$('#select1').change(function() {
var value = $(this).val();
var dataString = 'id='+ value;
if(value != '')
{
$.ajax({
type: "POST",
url: "fetchOptionsForSelect2.php",
data: dataString,
success: function(html) {
$('#select2').html(html);
}
});
}
else
{
//reset select2
$('#select2').html("<option value=''>Select value from select1 first</option>");
}
});
Here is a stand-alone example that does what you want. It might look complicated at first, but AJAX via jQuery is quite straight-forward.
This example uses two files:
1) TEST.PHP - contains the javascript/AJAX, and the HTML with the <select> controls
2) PROCESS.PHP - receives data from test.php (via AJAX), runs a MySQL lookup on that data, returns HTML back to TEST.PHP
TEST.PHP
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#workers").change(function(event) {
var w = $(this).val();
//alert('Value of w is: ' + w);
//return false;
$.ajax({
type: "POST",
url: "process.php",
data: 'worker=' + w,
success:function(data){
//alert(data);
$('#laDiv').html(data);
}
}); //END ajax
});
}); //END $(document).ready()
</script>
</head>
<body>
Worker:
<select id="workers">
<option>Roy</option>
<option>John</option>
<option>Dave</option>
</select>
<div id="laDiv"></div>
</body>
</html>
PROCESS.PHP
<?php
$w = $_POST['worker'];
$ret = '
Fruit Options:
<select id="fruitopts" name="Select2">
';
if ($w == 'Roy'){
$ret .= '
<option>Apples</option>
<option>Oranges</option>
<option>Pears</option>
';
}else if ($w == 'John') {
$ret .= '
<option>Peaches</option>
<option>Grapes</option>
<option>Melons</option>
';
}else if ($w == 'Dave') {
$ret .= '
<option>Nut</option>
<option>Jelly</option>
';
}
$ret .= '</select>';
echo $ret;
Here's what happens:
a. TEST.PHP - User selects choice from dropdown "workers"
b. change() event fires, gets value of ("w"), and sends that to process.php
c. PROCESS.PHP receives a variable key named w in its $_POST[] array, stores in $w
d. PROCESS.PHP does a MySQL lookup on the selected worker (value of $w)
e. PROCESS.PHP constructs some HTML in a var called $ret, then ECHOs it out
f. TEST.PHP receives the HTML string inside the $.ajax success function
g. TEST.PHP calls the received data data (-1 for originality)
h. TEST.PHP injects the received HTML into the DIV with id="laDiv"
Hope that helps.
Use http://www.appelsiini.net/projects/chained
<script src="jquery.chained.min.js"></script>
<select id="mark" name="mark">
<?php
foreach($select1_opt as $opt)
{
echo "<option value=$opt>$opt</option>";
}
?>
</select>
<select id="series" name="series">
<?php
foreach($select2_opt as $opt)
{
echo "<option value=$opt>$opt</option>";
}
?>
</select>
Sorry in advance everyone for this question as I know the cascading select boxes has been done to death but I can't seem to find any good help. I've tried various things but it all seems to fail and I'm not understanding why.
Here's the jquery I have currently:
function tester() {
$("select#type").attr('disabled', 'disabled');
$("select#cat").change(function(){
var vid = $("select#cat option:selected").attr('value');
var request = $.ajax({
url: "show_type.php",
type: "POST",
data: {id : vid}
});
request.done(function(msg) {
$("#result").html( msg );
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
}
Don't mind the first section of the code with the select#type and select#cat as these are for what I was trying to get the code to populate at first, however the .change is my trigger for the .ajax request. The rest of the code I'm merely trying to dump a simple return message into an empty div#result upon a successful ajax request.
I ran a test, and the var vid populates correctly.
Here's the simple PHP file I'm trying to call with the ajax:
<?php
$requ;
if (isset($_POST['id'])) {
$requ = 'Worked';
} else {
$requ = "didn't work";
}
echo $requ;
?>
I thought perhaps the problem was the id wasn't being passed properly so I altered the PHP script to give me any valid output regardless of whether the $_POST was set or not.
I won't post the HTML as I'm just trying to dump this all into a div while I test it. When I run the script I get the 'Request Failed' error message with a message of "error".
Here is the other jquery & PHP I have also tried, using the .post instead of the .ajax:
function tester() {
$("select#type").attr('disabled', 'disabled');
$("select#cat").change(function(){
$("select#type").html("<option>wait...</option>");
var vid = $("select#cat option:selected").attr('value');
$.post("show_type.php", {id:vid}, function(data){
$("#result").empty().append(data);
}, "json");
});
}
And the PHP to accompany this particular jquery:
$requ = $_POST['id'];
$ret = 'You selected: ' . $requ;
echo json_encode($ret);
Again, it all failed. I also tried the above code without using the json encoding/parameters. All I want to do is a simple (so I would think) cascading select dropboxes. The second box to be dependent of the first boxes selection. I'm beginning to think that this all just may not be worth it and just sticking strictly to PHP with links to resubmit the page with a GET and populate a new section or div with the results of the first click. Any help or suggestions you might have would be greatly appreciated, I've spent 2 solid days trying to figure this all out. Thanks in advance
Alright, I got it fixed. Thanks to Mian_Khurram_ljaz for making me take a different look at the hierarchical structure of the file. I was assuming that since the js was calling the php file, by placing the php file in the same folder as the js, I could call the php by using the url: show_type.php but that was actually wrong. The structure is considered from the actual page invoking the js and php, and therefore the url should have been js/show_type.php since I had the show_type.php file in my js folder.
It's always the little mistakes that take you days to figure. For those in the future looking to find decent code for cascading select drop boxes, here is my functioning and fully expanded code (which also includes a tri-level cascade)
jQuery:
function project() {
$("select#model2").attr('disabled', 'disabled');
$("select#brand2").attr('disabled', 'disabled');
$("select#project").change(function(){
$("select#model2").attr('disabled', 'disabled'); // if changed after last element has been selected, will reset last boxes choice to default
$("select#model2").html('<option selected="selected">Choose...</option>');
$("select#brand2").html("<option>Please wait...</option>");
var pid = $("select#project option:selected").attr('value');
$.post("handler/project.php", {id:pid}, function(data){
$("select#brand2").removeAttr("disabled");
$("select#brand2").html(data);
});
});
$("select#brand2").change(function(){
$("select#model2").html("<option>Please wait...</option>");
var bid = $("select#brand2 option:selected").attr('value');
var pid = $("select#project option:selected").attr('value');
$.post("handler/projBrand.php", {proj: pid, bran: bid}, function(data){
$("select#model2").removeAttr("disabled");
$("select#model2").html(data);
});
});
}
Just call the function in the $(document).ready of your js.
Notice the comment, having this 'redundant' call to disable and force the last box to select the default is just in case the user makes a selection in all 3 boxes but goes back to the first box and changes the selection.
Here is the php handler file:
<?php
include_once('../includes/file.inc');
$request = $opt -> getModelvBrand();
echo $request;
?>
The other handler file for the jQuery is nearly exactly the same, only invoking a different method in the class file.
And lastly, the HTML:
<form action="" method="post">
<select id="project">
<option value="0">Choose...</option>
<?php echo $opt -> getProject();?> //populates first box on page load
</select>
<select id="brand2">
<option value="0">Choose...</option>
</select>
<select id="model2">
<option value="0">Choose...</option>
</select>
<br /><br />
<input class="like-button" type="submit" title="Submit" value="" />
</form>
Thanks again Mian for making me take a different look at my file(s).
Hope this code helps someone else in the near future.