Here's my scenario:
I have a drop down menu, with different values. When option 'A' is chosen, I want it to use JQuery to call a Php script. That Php script will make a database query which returns a record ID. When that record ID is returned to the javascript, javascript will direct the browser to a particular URL based on the returned ID (i.e. /products/$ID)
Right now, I have it so that the dropdown menu triggers a javascript function. I also have the Php script that does the database work. Im just not sure what should go in the javascript function, or how to make it connect with he Php script, and how I get the returned data (and how to deal it with the return type -- xml, html, etc)
Im using JQuery library, and Php 5.x.
A simple example would be to take a form like
Example.php
<form id="form" name="form">
<select name="dropdown" id="dropdown">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
<input type="submit" id="submit" name="submit" value="Submit!" />
</form>
Then link it with some JQuery to intercept the form, and send it to a PHP file
JQuery.js
$(document).ready(function(){
$("#dropdown").change(function(event) {
$.ajax({
type: "POST",
url: "query.php",
data: $('#form').serialize(),
datatype: "json",
success: function(data){
var ret = jQuery.parseJSON(data);
// Redirect to ret.link
}
});
event.preventDefault();
});
});
Then, create the PHP file to interpret it
query.php
$stmt = $sql->dbh->prepare("SELECT `Link` FROM `Links` WHERE `ID` = :id");
$stmt->bindValue(':id', $_POST['dropdown']);
$stmt->execute();
$link = $stmt->fetch()['Link'];
echo json_encode(array('link' => "{$link}"));
die();
$("#menu-item").click(function() {
jQuery.ajax({
type: "POST",
url: "yourScript.php",
data: "data=foo",
success: function(response){
//redirect to id using response
window.location.replace("http://yoursite.com/products/" + response);
}
});
});
Of course, this will need to be customized to your unique situation.
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
I have an HTML table that has a column with select options that submits using onchange event using ajax.
the code works perfectly for the first row of each page (since pagination is applied on the table) but any other row is useless.
I had submitted a question related to this matter earlier and I stumbled on this question by chance that thankfully helped me a lot but not for the entire table.
this is the original Q&A link:
Submit form on select change via AJAX
my customized HTML code
<td>
<form action="" method="POST">
<select class="changeStatus" name="changeStatus" style="margin-bottom:10px;">
<option value="<?php echo $row["STATUS"]; ?>" > <?php echo $row["STATUS"]; ?></option>
<option value="new">new</option>
<option value="checking">checking</option>
<option value="processing">processing</option>
<option value="done">done</option>
</select>
<input class="order_Id" type="hidden" name="order_Id" value="<?php echo $row["ORDER_ID"];?>"/>
</form>
</td>
ajax code
<script>
$(document).ready(function() {
$('select.changeStatus').change(function(){
$.ajax({
type: 'post',
url: 'test2.php',
data: {selectFieldValue: $('select.changeStatus').val(), order_Id: $('input[name$="order_Id"]').val()},
success: function(html){alert('Select field value has changed to' + $('select.changeStatus').val()); },
dataType: 'html'
});
});
});
</script>
note:the alert is only echoing the first row vlue as well.
php code
<?php
$connection = mysqli_connect('localhost' , 'root' ,'' ,'project_name');
$changeStatus=$_POST['selectFieldValue'];
$id=$_POST['order_Id'];
$sql='UPDATE new_order SET STATUS="'.$changeStatus.'" WHERE ORDER_ID ="'.$id.'"';
$result = mysqli_query($connection, $sql);
?>
I have searched for days and this was my one and only successful code so far.
thanks in advance
When handling an event for multiple objects, you need to be careful to handle only the object the event was fired on.
In your case you have an event callback on every select with the class .changeStatus. When any of those are changed, you post with the data
selectFieldValue: $('select.changeStatus').val()
Since $('select.changeStatus') gives you an array of all objects matching the selector, and .val() only returns the value for the first object in the array, you're effectively handling the first row only no matter which row was changed. Instead you need to use
selectFieldValue: $(this).val()
with this referring to the object the event was fired on.
Same goes for your alert; change $('select.changeStatus').val() to $(this).val().
Final script with those changes would be:
<script>
$(document).ready(function() {
$('select.changeStatus').change(function(){
$.ajax({
type: 'post',
url: 'test2.php',
data: {selectFieldValue: $(this).val(), order_Id: $(this).siblings(".order_Id").val()},
//***only select that rows .order_Id by using $.siblings() with selector
success: function(html){alert('Select field value has changed to' + $(this).val()); },
dataType: 'html'
});
});
});
</script>
I am trying to get the values for the next drop-down from a database, which will be dependent on two previous drop-downs. The values for first two drop-downs are listed in the file itself. I want the second drop-down to be enable after selecting values from first, and similarly for third after second. Kindly help.
HTML code below:
<form>
<select id="branch" name="branch" class="form-control" onchange="showUser(this.value)">
<option value="">Select</option>
<option value="1">Civil</option>
<option value="2">Computer</option>
<option value="3">Mechanical</option>
<option value="4">Electronics and Telecommunications</option>
<option value="5">Electrical and Electronics</option>
<option value="6">Information Technology</option>
</select>
<select id="semester" name="semester" class="form-control" disabled>
<option value="1">I</option>
<option value="2">II</option>
<option value="3">III</option>
<option value="4">IV</option>
<option value="5">V</option>
<option value="6">VI</option>
<option value="7">VII</option>
<option value="8">VII</option>
</select>
</form>
jquery is:
<script>
$(document).ready(function(){
document.cookie = "s =hello" ;
console.log('hello');
$("#semester").attr("disabled", true);
$("#branch").change(function(){
$("#semester").attr("disabled", false);
$b = $('#branch').val();
$("#semester").change(function(){
$s = $('#semester').val();
$("#sub_code").attr("disabled", false);
console.log($s);
if($s!=1||$s!=2)
$s = $b+$s;
<?php
$s= $_COOKIE['s'];
$sql = "SELECT * FROM subjects WHERE sem_code=`$s`";
?>
});
});
});
</script>
I did not run the query since it is not assigned properly yet.
You can't include php code in javascript , the first is executed on the server side, the second is executed on the client side which means that you can't re-execute only if you resend a request to the server, obviously this is usually done by submitting forms, BUT sometimes -like in your case- we don't want to reload the whole page for each request ! and for this purpose we use AJAX
ajax sends post/get request to a specified php page which does the desired server-side tasks (updating data in the database, selecting some results from database, dealing with sessions maybe, etc...)
try something like this:
var pathurl='/path/to/your/php/file';
var params={}; //the parameters you want to send
params['semester']=$s;
var requestData= $.ajax({
type: 'POST',
url: pathurl,
cache: 'false',
data: params,
dataType: "json",
beforeSend: function () {
//here you can begin an animation or anything...
},
complete: function () {
//here you can stop animations ...
},
success: function (response) {
console.log(response); //check your console to verify the response
//loop other elements inside response
$.each(response, function (index, resultArray) {
//do something : in your case append to dropdown a new option
});
}
});
requestData.error(function () {
alert("error");
});
you should create a php file with the path specified in the above code, and there you can extract what you need from the database table, store values in an array and finally use:
echo json_encode($resultArray);
hope this was helpful
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'm using jQuery Ajax function for populating my select box.
Here is the code:
$(function(){
$("#maker").change(function(){
var selected_value = $("#maker").val();
$.ajax({
type: "POST",
url: "search.php",
data: ({_maker: selected_value}),
success: function(response){
$("#models").html(response);
}
});
});
});
The problem is this replaces the div "models" by whole search.php page!!!
I only want to populate the option values within "models".
Here is the HTML:
<div id="models">
<select id="model" name="model" style="width:170px">
<option value="Any">Any</option>
<?php
foreach($current_models as $model) {
?>
<option value="<?php echo $model; ?>"><?php echo $model; ?></option>
<?php
}
?>
</select></div>
Any help is appreciated. Thanks in advance.
So it looks like you're returning the entire HTML page, and not searching through it to find the specific part of the page. Try something like this:
$(function(){
$("#maker").change(function(){
var selected_value = $("#maker").val();
$.ajax({
type: "POST",
dataType: "html",
url: "search.php",
data: ({_maker: selected_value}),
success: function(response){
$("#models").html($(response).find('#someDiv').html());
}
error: function(){
$("#models").html('Uh oh! Something went wrong and we weren't able to process your request correctly.');
}
});
});
});
You'll notice 2 things:
I specified a dataType property. This tell jQuery what to expect. Additionally the html data type, tells jQuery to execute any JavaScript on the loaded page before rendering the page into the response object.
I'm creating a jQuery object using the response, and then using jQuery's .find() method to get the inner HTML of a specific div in the response.
Here is an example JS Fiddle, with some slight modifications for proof of concept: http://jsfiddle.net/rvk44/1/
I also just wanted to note that you may want to add an error property so that if the page ever comes back as an error, the user knows that and isn't just sitting there staring at a blank screen expecting something to happen. (I've added a basic error message in the example, see the jQuery docs for further info on what the error property is returned).