form select with ajax - php

I'm building a bug tracker tool.
When you create a project, you can change the project status (open, in progress & finished) on the project page using this select form:
<form action="classes/projectStatus.class.php" method="post">
<label> Change Project Status </label>
<select name="status" id="status">
<option value="Open">Open</option>
<option value="In Progress">In Progress</option>
<option value="Finished">Finished</option>
</select>
<input type='hidden' name='hdnID' value="<?php echo $id;?>">
<input class="small button" value="Change Status" type="submit">
</form>
This is the projectStatus.class.php file:
$status = $_POST['status'];
$id = $_POST['hdnID'];
$sql="UPDATE projects SET status = '$status'";
$result = mysql_query($sql);
$result = mysql_real_escape_string($sql);
if($result){
header('Location: ../projectpage.php?id='.$id);
} else {
echo "There is something wrong. Try again later."; }
mysql_close();
How can I do this with AJAX?
Could anybody provide me with some right code?!
I know the form isn't sql injection proof and I don't use mysqli, I will change this, but first I'd like to have an answer :).
Thanks!

I would use jquery, which will solve a lot of compatibility issues.
There is example code here on the jquery site: http://api.jquery.com/jQuery.post/

You'll want to use jQuery's $.post() function. You should check out the docs here for a ton of examples. So what you could do is change
<form action="classes/projectStatus.class.php" method="post">
to
<form onsubmit="return submit();">
and then define submit as
function submit()
{
$.post('classes/projectStatus.class.php', {
"status": $('#status').val(),
"hdnID": $('#hdnID').val()
}, function(response) {
//your callback function
});
return false;
}
This code is untested and might not work, but it's just meant to give you an idea of what to do. Let me know if this makes sense or if you have any questions :)

Related

Popup on if statement in php

I have a html form which looks like this:
<form action="submitOrder.php" method="get">
<select name="orderForm">
<?php
echo '<option value=" "> </option>';
while($row = \mssql_fetch_array($employeeOrderResult))
{
echo '<option value="'.$row[EMPLOYEE].'">'.$row[EMPLOYEE].'</option>';
}
?>
<option value="Gæst">Gæst</option>
<option value="Praktikant-01">Praktikant-01</option>
<option value="Praktikant-02">Praktikant-02</option>
<option value="Praktikant-03">Praktikant-03</option>
</select>
<br>
Vare: <input type ="text" name="varenr"><br>
Antal: <input type="text" name="antal"><br>
<input type="submit" value="Bestil">
</form>
It fetches som data from a database and adds some special guests.
Now, when it confirms it redirects to a page which has this code in it:
<?php
$ofAntal = $_GET['antal'];
$ofMedarbejder = $_GET['orderForm'];
$ofDato = date('Y-m-d H:i:s');
$ofVareNr = $_GET['varenr'];
$sql = "INSERT INTO Bestillinger(bestillingsAntal,medarbejder,dato,vareNr) VALUES('$ofAntal','$ofMedarbejder','$ofDato','$ofVareNr')";
$validation = mysql_query($sql, $MySQLcon);
if(!$validation)
{
die('Couldnt enter data ' . mysql_error());
}
echo 'Entered data succesfully';
?>
Now, I need a confirmation popup of some kind, if the amount (ofAntal) is above 1, and Ive looked into several solutions. The problem is i started working with PHP tuesday morning, and i cant find a solution that works for me.
All it has to do, is submit the data is yes is clicked, and cancel it if the user clicks no/cancel. This is ofc done in an IF statement, thats not the issue, the issue is how to implement it properly.
ANY help is highly appreciated :)
Use javascript confirm box on onclick attribute for submit button. It will give you yes and cancel options.
<input type="submit" value="Bestil" onclick="confirm("Are you sure ?");">
Orelse
You can write a function in javascript to check that
<input type="submit" value="Bestil" onclick="myfunct();">
function myfunct(){
if(document.getElementById("antal").value > 1)
confirm("Are you sure");
return true;
}

shortcode Conditional Form - PHP

I am attempting to build a simple contact form inside of a function so that I may add it as a shortcode later. I wish to change the mailto address based on a "select" value.
function contact_form_function() {
switch($_POST['selectedValue']){
case 'webmaster':
$mailbox='webmaster#email.com';
break;
case 'careers':
$mailbox='careersk#email.com';
break;
case 'projects':
$mailbox='projects#email.com';
break;
case 'info':
$mailbox='info#hotmail.com';
break;
default:
// Something went wrong or form has been tampered.
}
?>
<form action="MAILTO:<?php echo($mailbox); ?>" method="post" enctype="text/plain">
<input type="text" name="name" required> Name(required)
<input type="text" name="mail" required> Mail(will not be published, required)
<input type="text" name="website"> Website
<select name="selectedValue">
<option value="webmaster">Website Comment</option>
<option value="careers">Careers Information</option>
<option value="projects">Project Opportunity</option>
<option value="info">Other</option>
</select>
<textarea></textarea>
<?php
echo($mailbox);
?>
<input type="submit"></submit>
</form>
<?php
}
?>
Its not echoing anything back and not changing the email address so I know I've done something wrong. I just don't know what. I'm a novice when it comes to coding so any advice is helpful.
You need to set the $mailbox value before you try to use it. I recommend using jQuery.
<script src="jquery.js"></script>
<script type="text/javascript">
jQuery.noConflict();
(function ($) {
function readyFn() {
$("#emailSelect").change(function(){
$("#your_form").attr('action', 'MAILTO:' + $("#emailSelect").val() + '#email.com');
});
}
$(document).ready(readyFn);
})(jQuery);
/*$(document).ready(function(){
$("#emailSelect").change(function(){
$("#your_form").attr('action', 'MAILTO:' + $("#emailSelect").val() + '#email.com');
});
});*/
</script>
...
<form action="" id="yoor_form" method="post" enctype="text/plain">
...
<select name="selectedValue" id="emailSelect">
<option value="webmaster">Website Comment</option>
<option value="careersk">Careers Information</option>
<option value="projects">Project Opportunity</option>
<option value="info">Other</option>
</select>
</form>
You need to set the $mailbox value before you try to use it.
And if you want something to happen in the browser when the user selects an option in the drop down, you have to use javascript, not PHP.
You are defining $mailbox after you try to use the value.
You have to have your $mailbox = ... stuff before your <form>.

PHP: change page action of a form by url in select

hy, i have a problem with a form. i know the question is simple but i can not have a solution. Well, this is my form:
<form id="search" method="post" action="cerca_redirect2.php" >
<select id="tipo" name="tipo"class="chzn-select" style="width:165px;" tabindex="1" >
<option value="http://case.vortigo.it/vendita-immobili/index.php"> Vendita</option>
<option value="http://case.vortigo.it/affitto-immobili/index.php">Affitto</option>
</select>
<input id="field" name="field" type="text" value=""/>
<input id="submit" type="submit" value="" />
</form>
my goal is when i select "Vendita" and i submit the form i have to go to the url in the select "Vendita", for each select. someone can help me? thanks
In the server side php code, do something like this
if (isset($_POST['tipo']) && !empty($_POST['tipo']))
{
header('Location: ' . $_POST['tipo']);
}
Note: This is a very basic version, you will want to ensure the url is valid by either maintaining a list of urls on the server, or something similar.
There are many different ways, but you can for example use following:
See the onsubmit part in the form definition
<form id="search" method="post" action="cerca_redirect2.php" onsubmit="this.action=document.getElementById('tipo')[document.getElementById('tipo').selectedIndex].value" >
If I understan your question correctly, you need a way to change the action value to the selected option's value
this is how to do that
$(document).ready(function(){
$("#tipo").on("change", function(){
$("#search").attr("action", $(this).val());
});
});
DEMO: http://jsfiddle.net/6ybMP/
You want to change the action of the form based on the select? The following should be along the lines of what you want.
$('#tipo').on('change', function() {
var newAction = this.val();
$('#search').prop('action', newAction);
}
UPDATE
You will want to wrap this code in $(document).ready() so that the event will be registered after the DOM has been loaded.
Like so:
$(document).ready(function() {
$('#tipo').on('change', function() {
var newAction = this.val();
$('#search').prop('action', newAction);
}
});

how to select option to submit different php page

drop down select "sales" go to sales.php, other options selected go to addFund.php...
<form name='searform' method='post' action='<?php echo $home;?>addFund.php'>
Search : <input type='text' id='sear' name='sear'> by
<select id='psel' name='psel' onchange='change()'>
<option value='email'>Email</option>
<option value='name'>Username</option>
<option value='domain'>Domain name</option>
<option value='sales'>Sales</option>
</select>
<input type='submit' name='sub' id='sub' value='Go' onclick='gopage()'>
<input type='submit' name='dir' id='dir' value='Direct'>
</form>
How to submit different pages
You could use some Javascript nastiness to achieve this with the change() function, but the usual way to do this is to route all requests through a controller and include() the appropriate page. For example, point your form to action.php, and in that file, do this:
action.php
<?php
if (isset($_POST['psel']) && $_POST['psel'] == 'sales') {
include 'sales.php';
} else {
include 'addFund.php';
}
...or you could just put roughly that code into addFund.php, since you only seem to have one other script that you would want to send requests to.
You could do this with javascript:
function change(el) {
if(el.value === 'sales') {
el.form.action = 'sales.php';
} else {
el.form.action = 'addFund.php';
}
}
Change the onchange to onchange="change(this)". A better way would be to check the variable on serverside and include the right file.
Change your select to this:
<select name="vote" onChange="document.forms['searForm'].submit()">
And make your form action go to something like pageChange.php where it returns a different page depending on the $_POST value.

updating mysql records based on option selection

Hello I cannot figure out what is wrong with my code. Have not much experience with php yet. Can someone please tell me what am I doing wrong??
Here is my code:
<?php
include 'mysql_connect.php';
if (!isset($_POST['submit'])) {
$fuelQuery2 = sprintf("UPDATE fuel_price SET `Price` = '%s' WHERE FuelType = '%s' LIMIT 1",
mysql_real_escape_string($_POST['inputPrice']),
mysql_real_escape_string($_POST['fueltype']));
$Result = mysql_query($fuelQuery2);
if($Result){
echo 'Price has been updated!';
} else{
echo 'Failed to update price!';
}
} else{
echo 'No form submitted';
}
?>
<h1>Update Oil Price</h1>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Oil Price:<input name="inputPrice" type="text" value=""/>
Product
<select name="fueltype">
<option value="Oil">Kero</option>
<option value="Diesel">Diesel</option>
<option value="RedDiesel">Red Diesel</option>
</select>
<input type="submit" name="submit" value="Modify" />
</form>
It's really simple, change
if (!isset($_POST['submit'])) {
to
if(isset($_POST['submit'])) { //Only execute the query when the form is submitted
Your original code told PHP to execute the query when the form wasn't submitted (notice that I removed the !) instead of when it was. The notices you were getting were telling you that the $_POST variables you grabbed for your query didn't exist (because the code ran before the form was submitted).
Also, do look into PDO. The mysql_ family of functions is no longer the preferred method for interacting with the database layer.
PHP
In mysql_connect.php please ensure that you call mysql_connect() and mysql_select_db().
Then you can adjust your code to the following:
<?php
include 'mysql_connect.php';
if ('POST' == $_SERVER['REQUEST_METHOD'] and
isset($_POST['fuel_type']) and
isset($_POST['oil_price'])) {
$fuel_type = mysql_real_escape_string($_POST['fuel_type']);
$oil_price = mysql_real_escape_string($_POST['oil_price']);
$SQL = "UPDATE `fuel_price`
SET `Price` = '$oil_price'
WHERE `FuelType` = '$fuel_type'";
if(mysql_query($SQL)) {
echo 'Price updated.';
} else {
echo 'Failed to update.';
}
}
?>
HTML Form
You don't need PHP_SELF in the action and you can just leave it blank to submit onto the same page.
<form action="" method="post">
<label for="oil_price">Oil Price</label>
<input name="oil_price" id="oil_price" type="text" value="" />
<label for="fuel_type">Product</label>
<select name="fuel_type" id="fuel_type">
<option value="Oil">Kerosene</option>
<option value="Diesel">Diesel</option>
<option value="RedDiesel">Red Diesel</option>
</select>
<input type="submit" name="submit" value="Modify" />
</form>

Categories