I have a Jscript Query.
I have done a bit of reading and found out that AJAX is just a side server for a lfash script that can be used on Linux with php. (please correct me if I have interperated that wrong)
I have no knowledge on how scripts work so this is new, I have tried a couple of different tries but no luck.
I have one drop down box (Box1) (populated from Database)
I have another box (Box2) for a calculation to insert into my database for other uses on ohter parts of hte site.
I need the Box2 to change the figure when someone changes Box1 dropdown before hitting the submit button.
I think because I have the calcualtion this is getting me stuck... Code is as below... Can someone please help me figure out (I think I need some form of Script to do this.) the answer...
Box1
<td><p>selection 1</p>
<select id="t1_type" name="t1_type">
<?php $result = mysql_query("SELECT * FROM `t2` ORDER BY t2_value");
while($valuerow = mysql_fetch_array($result)){
echo '<option value="'.$valuerow['t2_name'].'">'.$valuerow['t2_name'].'</option>'; } ?>
Box2
<input name="t1_value" id="t1_value" value="
<?php
$var1 = $row_value['t2_value'];
$var2 = $row_dropdown['t1_number'];
$total = round ($var2 * $var1);
echo "" . $total . "";
?>" />
I hope this is all the code you need, (Let me know if more required)
What it needs to do is show new calculation whenever someone changes the box1 option BEFORE the submit button is clicked, so it submits the correct calculation to the database for future use.
I think it would need pretty much "t2_value" from box2 to change when ever "t2_name changed from box1.
And once again the best link to learn about the solution. (Learnt about Joins now from my last question!! Almost a intermediate user. ;-) )
Edit :
I saw that your second box was a textbox I believe, if thats the problem then you should do something like this
<select id="t1_type" name="t1_type" onchange="change(this);">
<?php
$result = mysql_query("SELECT * FROM `t2` ORDER BY t2_value");
while($valuerow = mysql_fetch_array($result))
{
echo '<option value="'.$valuerow['t2_name'].'">'.$valuerow['t2_name'].'</option>';
}
?>
</select>
This defines your <select> box like you did in your question.
Add an onChange event into your first <select> and then create a function to handle to onChange event. An onChange event fires whenever the user changes the item in the <select> element.
Javascript :
( put this part of the code above the </head> )
<script language="javascript" type="text/javascript">
function change(element)
{
// do here whatever you want
// you can change the value of the <input> box with :
// document.getElementById(element.id).value = your_value
// If you want to see if this part works, then try adding this :
// alert("It works!");
// If you want to get the text of the item which has been selected in Box1 use :
// $("#t1_type option:selected").text();
}
</script>
Note: because PHP is server side, you can't update your Box2 dynamically without a page refresh, Javascript however is Client Side and CAN do this.
Note : the $("#t1_type option:selected").text(); code requires you to include the jQuery library into your script. Be sure to convert this variable to a float, int or double if you want to calculate with it, else the outcome will give NaN (Not a Number)
Tutorial on including jQuery Libary :
http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery
If you're new to JavaScript, you should try some tutorials. The ones at w3Schools.com helpt me alot, but some people say they're not always correct, but anyhow, read some stuff about Javascript to actually know what you are doing, instead of copypasting code :)
Related
I would like to know if it would be possible to run an update query when an item is selected from a drop down list. The user makes a choice, a function is then called to update a particular field in a database. This will be achieved using a select box to store the options. Thanks.
echo '<td>';
echo '<select name="order_status[]" onChange = "update()">';
echo '<option value = "1" class ="pending">Pending</option>';
echo '<option value = "2" class = "approved">Approved</option>';
echo '<option value = "3" class ="disapproved">Disapproved</option>';
echo '</select>';
echo '</td>';
echo '</tr>';
Yes, it's possible. If you want the query to be run seamlessly (that is, without a submit button being pressed and the page refreshing), then you'll need to use Ajax to send the request asynchronously to your PHP script.
EDIT: The easiest thing to do is simply use jQuery's $.get() functionality in your onchange event. That way, each time someone chooses an option, jQuery will send the request to your PHP script with that option's value. The PHP script will run, and return the new data back to your jQuery, which will then use its DOM functionality to insert that data into your page.
You can do the same thing with a button. Just stick $.get() in the button's onclick event rather than in the select element's onchange event.
The jQuery site's documentation will give you relevant code examples.
EDIT 2: Okay, here's a very canned example.
First, let's think about the actual process you want to have happen on the back end. In the simplest terms, you want to take an id from user input and use that to run in a query. Pretty straight forward (using PDO for the database work):
// in a real app, you'd need to sanitize and validate the incoming id
$id = $_GET['id'];
$stmt = $dbh->prepare("SELECT * FROM table_name WHERE id = :id");
$stmt->bindParam(":id", $id);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
echo json_encode($row); // makes it jQuery friendly
Okay, so the back end is pretty simple. Now, for the font end, where the magic happens. Here's how I'd approach using both a select element and a button in order to pass the id back to the PHP script, and then handle the results:
<!-- Your HTML up to where the select and button are on your page -->
<select id="id" name="id">
<option value="1">Something</option>
<option value="2">Something Else</option>
<option value="3">Yet Another Thing</option>
</select>
<button id="btn" />
<!-- In your jQuery -->
$("#btn").click(function() {
$.get("path/to/your/back/end/script.php", { "id" : $("#id").value }, function(data) {
/* the data will be the json_encode($row) that was echoed from the PHP script.
* so, you'll need to drill into it, take the data you want, and use
* jQuery's/JavaScript's DOM manipulation tools to insert the data on your
* page
*/
}) // close $.get()
}); // close .click()
None of this is tested, and it's admittedly incomplete, but that should be more than enough to get started. Really, all you'll need to figure out is how to drill into the returned data (it's a JSON object, so it shouldn't be too bad... use a browser's web development tools to see how the data is actually formed) and insert it where you want. That, and any dumb errors I may have made above.
Hope this helps!
I have no idea where to begin, so if there is already an answer out there to a question like mine I would appreciate it! Basically the question says it all, Here is what I would like:
There is a drop down menu, simple drop down menu, nothing fancy. When a selection is made in that drop down menu, a php mysql query is ran where the database will be updated with that value. I have all the pieces, all I need is the code that would be able to kick it all off.
For instance when you hit submit on a form you would typically type out:
if (isset($_POST['submit']))
{
//grab information and insert into db
}
How would I do this for a drop down selection without having to click the submit button.
As has been said in the comments, you listen to the onchange event of the selectbox and either submit a form or use AJAX. This is not my point.
From a usability POV I recommend you reevaluate this proposition, if it really leads to a database update: Ever used the mouse wheel to scroll, while accidently having the focus on a selectbox? Jackpot! You just changed your DB settings without being aware of it.
So using onchange on a selectbox to kick off something, that is immediately visible is IMHO a good thing - you'll know, when you triggered it. Changing a DB setting with no feedback other than the select box changing value is IMHO a bad thing. Or an accident waiting to happen.
you should be looking for something like this
<form id="testform">
<select id="yourselect" name="yourselect" onChange="updateDb()">
<option value="somevalue">Please select</option>
<option value="somevalue1">Something</option>
</select>
</form>
you Javascript function will look like this
function updateDb() {
// I am using jquery for ajax
$.post("yourserverhandle.php", $("#testform").serialize());
}
and this is how your "yourserverhandle.php" looks like
<?php
$query = "update yourtable set something='".mysql_escape_string($_POST["yourselect"])."' where id='something'";
.... mysql connect, execute
?>
$("#DDL_ID").change(function(){
$.ajax({
url:'/some.php',
type:'POST',
data:{submit:$(this).val()},
success:function(data){
//do something here if the server return anything
},
error:function(){
console.log("something bad happened");
}
});
});
on the php side
if (isset($_POST['submit']))
{
//grab information and insert into db
}
P.S. always sanitize the input see mysql_real_escape_string
Ok I have a table that changes the displayed text once clicked on like the one displayed on http://www.w3schools.com/ajax/ajax_database.asp
I'm trying to update it based on each click.
For example.
Page Load > Load news article 1
onClick 1 > Load news article 2
onClick 2 > Load news article 3
All I want is for it to change based on each click, to a subsequent value. I have a php mysql database script that will pull the data from the database each time called.
The real question: Should I program the php to return a new table data cell with the new
oncLick="showNews($next_number)"
or should I leave that up to the AJAX, before it requests the information, just +1 it up.
I'm new to AJAX programming and not that experienced in PHP. I have searched everywhere and apologize if this is a redundant question. Just point me in the right direction.
write a php function to support to get the content by id. showNews(news ID). and then pass the newid with the ajax request. no need to change the newsid in the PHP.
I'm guessing something like this would be simplest:
var article = 0;
function showNews(){
get_article(article);
// magic
article+=1;
}
To be honest, just pick the way which seems more natural to you. Unless this is only a small part of something huge, it won't matter.
if I understood right, you want to get the next news when clicking on your button...
I suggest you to use jQuery for Ajax request...
It could be like this:
<script type="text/javascript">
$(document).ready(function(){
var result = 0;
$('#myButton').click(function(){
$.post('phpfunction.php',result,function(r){
$(document).append(r);
});
result ++;
});
});
</script>
And in PHP:
<?php
$result_id = $_POST['result'];
//SELECT * FROM WHERE id = $result_id;
?>
I have an HTML form which contains a drop down, a tinyMCE textarea, and a save button.
The dropdown is used to select a file to edit.
I load up the required file into the tinyMCE editor by making an ajax call when the jquery change() event is triggered from the dropdown. That works fine.
The problem I'm having is saving the file off. I am trying to do it by posting the form off to another php page which will write to the file and then send us back to the main page.
This is the php code within my writeFile.php page:
<?php
session_start();
if (!isset($_SESSION['id'])) {
header ('Location: index.php?error=0');
}
else {
if (isset($_POST['save'])) {
$text = $_POST['mceContent'];
$index = $_POST['files']; // << PROBLEM LINE!
$array = array('homeText.txt', 'anotherText.txt');
$fileName = $array[$index];
$path = '../txt/'.$fileName;
$length = strlen($text);
echo "INDEX: $index"; // TO TEST THE INDEX VARIABLE.
$fh = fopen($text,'w',true);
fwrite($fh,$text,$length) or die('Could not write');
fclose($fh);
header ('Location: admin.php');
}
}
?>
The $index variable is meant to be the selected index in the dropdown, however it is posted by my form as the selected string value in the dropdown.
I can think of three solutions (ordered from least likely to work to most likely)
There is some way to get the index from that php post?
I can make a change in the HTML form/select tag to tell it to post the index and not the value string
I change it to a jquery event, with the on-click, and pass in the index to a post manually with xhr.
If someone could help me with implementing one of these method that would be great.
If you have your own, better solution I would be happy to hear that as well.
Also note that I can't build the path from the value string, because my dropdown uses descriptive strings, not actual file names.
Thanks in advance, bear in mind I'm new to php and especially jquery.
I am not sure why you can't use the value attribute - the descriptive string would be the text portion of the option element, the filename to save could be the value:
<option value="path/to/file_to_save.php">Descriptive file name</option>
Doing it that way, the user sees the descriptive text, the server gets a useful bit of information it needs when the form posts.
If that is not an option, you could add an onSubmit event to the form in which you pass the selectedIndex property to a hidden form field, then return true and let the form submit normally.
Form snippet
<form onsubmit="return beforeSubmit()">
<input type="hidden" name="file_index" value="" id="file_index_fld" />
<select id="file_name_dropdown">
<option>...</option>
Javascript snippet
var beforeSubmit = function () {
$('#file_index_fld').val($('#file_name_dropdown').attr("selectedIndex"));
return true;
}
... now in PHP's $_POST variable, you'll see $_POST['file_index'] contains the selectedIndex of the select element.
The long and short of it is that the selectedIndex property is a DOM item and not part of the POST data. No matter what, you are either going to have to intervene with javascript to add the data to POST, or modify your option elements to pass the desired data. I would always lean toward the former route as it is less complex.
Another option I can think of: Before posting, catch the new index in the change-event and write it to a hidden input-field of your form. After that, you can serialize and post it with jQuery.
I have this webpage. It has a page called "services.php". I have several buttons (made of classes), that belong to different "package" prices i offer.
I want the links that say "Select" to autofill a form in another page, or alternativly in a popup form in the page..
I don't really know how to explain it, but as short as possible:
When link is pressed autofill form (in this or other page) with the type of package they chose. Only text autofill
What you seem to be asking is 'loading' a page pre-filled with specific information, you can do this a number of ways, either by utilizing javascript (like jQuery for instance). Or using your PHP, make links that pass variables (say a flag or a reference to pre-fill the fields -- if you want a popup or next page, etc).
Your url would like like the following for the button that a user presses (button would be a simple http link):
http://mywebsite.com/prefill.php?user=bob&package=2
This would have the values bob as the user that requests it (you can reference an id for user info here as well), and package=2 to designate your package options.
Then on the prefill.php page, you would have something that checks for:
$user = $_GET['user'];
$package = $_GET['package'];
Hope that helps
This will populate form fields with whatever you pass to the autoFill() function. This would be a same page example.
<html>
<body>
<form>
<input type="text" id="packageDescription">
<input type="text" id="packagePrice">
</form>
<script>
function autoFill(packageDescription, packagePrice) {
document.getElementById('packageDescription').value = packageDescription;
document.getElementById('packagePrice').value = packagePrice;
}
</script>
Premium Package<br>
Platinum Package
</body>
</html>
You could do something like this:
<select id="packages">
<option value="package1">Package 1</option>
<option value="package2">Package 2</option>
</select>
Submit
When the link is clicked, the following javascript will fire off:
function submitPackage()
{
var package = $("#package").val();
window.open("http://your-site.com/some-script.php?package=" + package);
}
The above will open a pop up window to a page such as this:
http://your-site.com/some-script.php?package=package1
In some-script.php you will do something like this:
You selected the package: <b><?php echo $_GET['package'];?></b>.
Or:
<?php
//Put the packages in an array:
$packages = array();
$packages['package1'] = 'Package 1';
$packages['package2'] = 'Package 2';
//...
?>
<select id="package">
<?php foreach ($packages as $name => $text):?>
<? $selected = ($name == $_GET['package']) ? 'selected' : '';?>
<option value="<? php echo $name;?>" <?php echo $selected;?>>
<?php echo $text;?>
</option>
<? endforeach;?>
</select>
The above will auto select the package they selected in a dropdown box.
if i understood your problem, you want to fill some input fields with information when the user clicks on some links
i can think of 2 ways of doing this : either have the links point to a page like services.php?req=package1 (or any other url you want) and on that page generate the input fields with the information you need (set the default values in the fields with the ones you want), or, use javascript to change the values of the forms without changing the actual page (either via ajax or predefined values)
for javascript you can use the jQuery framework, it has a pretty extensive community of enthusiasts and plenty of examples to get you started with it.
an example for your case would be
$('#btn1').bind('click', function() {
$('#input1').val("value");
$('#input2').val("value2");
});
replace btn1 with the id of the first button or link you have, input1 with the id of the first input in your form, and value with the value you want
I just did this myself. My solution was with jQuery. Just assign an id to your link. The first ID in the code is the link id and the second is the id for the input element you want to populate.
Here is the script:
<script>
$(document).ready(function() {
$('#link_id').click(function() {
$('#input_id').val( $(this).text() ).keyup();
return false;
});
});
</script>
Hope it works!
I've ran several time into the same issue, so I had to write my own script doing this. It's called Autofiller and its pretty simple but does great job.
Here is an example
http://example.com/?autofiller=1&af=1&pof=package&package=package1
So basically it takes several parameters to init the script:
autofiller=1 - init AutoFiller
af=1 - Autofill after page is loaded
pof=package - Find the parent form element of the select with name attribute package. Works also with input form elements.
package=package1 - Will set the select element's value to package1
Hope it helps you! :)