View:
<div class="col-sm-6">
<input type="text" class="form-control timepicker" name="shiftStartTime" id="shiftStartTime" required parsley-maxlength="6" placeholder="Shift Start Time" />
</div>
Script
<script type="text/javascript">
$(document).ready(function(){
$('.timepicker').wickedpicker();
});
</script>
Controller code :
$shiftstarttime = $this->input->post('shiftStartTime');
But it is inserting into database as "00:00:12".How to change it to the H:m:s format (ie 12:05:10)
Try this
it give's you currect value
<input type="text" class="form-control timepicker" name="shiftStartTime" id="shiftStartTime" required placeholder="HH:MM:SS" />
script
<script type="text/javascript">
$('.timepicker').timepicker({
'timeFormat': 'H:i:s',
});
</script>
Controller code
$shiftstarttime = $this->input->post('shiftStartTime');
make sure column type in the database is time
First you need to confirm that in post you are getting correct value if yes then following would work for you
$input = $this->input->post('shiftStartTime');
$input = str_replace(" : ", ":", $input);
$shiftstarttime = date('H:i:s', strtotime($input));
First, check when you getting time form date picker, it's coming in which form.
Otherwise, you can specifically change format on the controller side then assign that value to the database object.
Try this, I hope it will work for you.
<script>
$(document).ready(function(){
$('.timepicker').timepicker({});
});
</script>
Related
I'm learning AJAX and want to create a really simple web app to use my knowledge in the "real world".
I'm trying to calculte different percentages of a user input value, and make it appears on the webpage, without refreshing, thanks to AJAX.
Here is my HTML form:
<form id="warmupForm" class="form">
<label for="userWorkLoad">Work load (in kgs)</label><br>
<input type="text" name="userWorkLoad" id="userWorkLoad">
<button type="submit">Calculate</button>
</form>
<div id="#output">This is where I want the result to be shown with AJAX</div>
Here is some of my PHP code, for you to get the idea:
# Get the user input (work load in kgs)
if (isset($_POST['userWorkLoad'])) {
$workload = $_POST['userWorkLoad'];
# Avoid JS hacking
$workload = htmlspecialchars($workload);
}
# CALCULATION #
# Calculate 55% of the work load (1st warm up set)
$FirstWarmupSet = ($workload * 0.55);
# Calculate 70% of the work load (2nd warm up set)
$SecondWarmupSet = ($workload * 0.7);
# First Warmup set #
echo "<li>Do 8 reps with " . $FirstWarmupSet . " kgs, then take 1 minute rest.</li>";
echo "<br>";
# Second Warmup set #
echo "<li>Do 5 reps with " . $SecondWarmupSet . " kgs, then take 1 minute rest.</li>";
echo "<br>";
// etc etc...
I'd like the different variables values from PHP to be shown in my "#output" div when the user click on the submit button.
I've tried a lot of different things (AJAX without jQuery, AJAX with jQuery), but didn't manage to get what I want.
I'm sure I'm doing something wrong, but I don't know what. I'm sure my PHP script is working, since I used it without AJAX without any problem.
I would be very grateful if someone could help me on that.
As mentioned above, the easiest way to make an AJAX request for you is probably to try jQuery:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<!-- Add jQuery on your HTML page -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<!-- Add some custom JavaScript file -->
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<form id="warmupForm" class="form">
<label for="userWorkLoad">Work load (in kgs)</label><br>
<input type="text" name="userWorkLoad" id="userWorkLoad">
<button id="btn" type="submit">Calculate</button>
</form>
<div id="output">This is where I want the result to be shown with AJAX</div>
</body>
</html>
The script.js content:
$(function() {
// Process a button click
$("#btn").click(function() {
event.preventDefault();
// Get input field
var userWorkLoadInput = $("#userWorkLoad");
// Build some request parameters
var params = {
userWorkLoad: userWorkLoadInput.val()
};
// Let's name your PHP script file as "server.php"
// And send POST request with those parameters
$.post("server.php", params, function(response) {
// Response text we're going to put into the `output`
$("#output").html(response);
});
});
});
You can simply do it using Jquery instead of using Ajax (using PHP you should add method="POST" to the form).
Here's an example:
$(document).ready(function(){
$("#send").click(function(){
// your calculates
$("#output").html(...);
});
});
...
<button type="submit" id="send">Calculate</button>
I am having a bit of trouble figuring out how exactly to make a certain connection. It's a project I thought might be simple enough for me to do on my own without help, but I've hit a wall unfortunately. It's an 'exercise generator' that basically asks a few basic questions, and based on your answers, it outputs a recommended workout routine. I've constructed the MySQL database with plenty of exercises, have successfully connected the database, and have made the form.
What I am having trouble though, however, is storing those form results into variables, and based on those variables (if workout days is 3, for example, there would only be 3 groups of workouts printed instead of 5) output a routine into the same div as the form, effectively replacing it with the answer instead of placing it underneath the submitted form.
Index.php
<!DOCTYPE html>
<html>
<?php $page_title = "Workout Generator"; ?>
<link rel="stylesheet" type="text/css" href="style.css">
<head>
<script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" ></script>
</head>
<body>
<?php include("header.php"); ?>
<?php include("connect.php"); ?>
<div id="appWindow">
<h3>Please answer the following questions and click 'Submit' to generate your workout routine.</h3>
<form id="homeForm" method="post" >
<label for="name">Name: </label>
<input type="text" name="name"><br>
<label for="age">Age: </label>
<input type="number" name="age"><br>
<label for="workoutdays">How many days a week can you workout?</label>
<select name="workoutdays">>
<option value="1">3</option>
<option value="2">5</option>
</select><br>
<label for="workoutstyle">Do you prefer a gym, or bodyweight exercises?</label>
<select name="workoutstyle">>
<option value="1">Gym</option>
<option value="2">Bodyweight</option>
</select><br>
<button type="submit" name="submit">Submit</button>
<button type="reset" name="reset">Reset</button>
<div class="form_result"></div>
</form>
<?php
$age = $_POST['age'];
$workoutdays = $_POST['workoutdays'];
$workoutstyle = $_POST['workoutstyle'];
?>
</div>
<br><br><br>
<?php include("footer.php"); ?>
</body>
</html>
I don't necessarily want an answer giving me the exact code to enter, but would appreciate being pointed in the right direction to get that form pulling data from MySQL, and using AJAX to print in the same window without refreshing.
THANK YOU
First of all, you need to post your request. With $.ajax this
//Do this thing on page load
$(function() {
//handle submit
$("#homeForm").submit(function(e) {
//customize your submit
e.preventDefault();
$.ajax({
type: "POST",
url: youURL, //maybe an url pointing to index.php
data: yourData, //attach everything you want to pass
success: function(response) {
$("#appWindow").html(response);
}
});
});
});
code should help. You need to make sure you pass the necessary elements and you provide the correct url. On server side, generate the desired html and send back as response.
In the script file
$(document).ready(function(){
$(document).on('click','#submit_btn',function(){
var url = '/xyz.php'; //full path of the function where you have written the db queries.
var data = '';//any data that you would like to send to the function.
$.post(url,{data: data}, function(result){
var arr = JSON.parse(result);
});
});
});
in your php file once your database query has been executed and you get the result. for example
$result = //result of your mysql query.
echo json_encode($result);
exit;
I need to use AJAX to save user input comments instantly to the database.
This is the comment box.
<div class="comment">
<form action="comment.php">
<textarea cols="35" name="comments"> Give us comment </textarea>
<input type="button" value="comment" onclick="ajaxFunction()">
</form>
</div>
This is the php code
<?php
$link = mysql_connect("localhost","root","");
mysql_select_db("continental_tourism");
$comments = $_POST['comments'];
if($comments == "")
echo "Please type your comment";
else
{
$query = "insert into comment(comment) values('$comments') ";
mysql_query($query);
}
return;
?>
I need to know how this should be changed.
Thank You
I would chnage your HTML like this
<textarea cols="35" id="comments"> Give us comment </textarea>
<input type="button" value="comment" id="btnSave" />
And the script
$(function(){
$("#btnSave").click(function(e){
e.preventDefault();
$.post("yourphpfile.php", { comments : $("#comments").val() } ,function(data){
alert(data);
});
});
});
The above script will send an ajax request to yourphpfile.php with the value present in the textarea with id comment. Then once it gets some data back from the server page. it justs alerts it ( you may show this in a seperate div if you want ). You should echo the response from your php file after saving the data to database.
As bracketworks already mentioned, you should be careful about SQL injections while saving data which is being read from the querystring value. do proper sanitization before putting it in a query. Sorry i am not a php guy. so not sure how to do that.
Don't forget to include the jQuery library to your page.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
You may use firebug console for debugging your script error if you run into any.
My code is as follows:
<html>
<input type="datetime" name="datepicker" id="datepicker" />
<P id=firstp></P>
<button id="button" onClick="test_function();" type="button">View</button>
<script type="text/javascript">
function test_function(){
$("#firstp").load("view_calls_sort.inc.php?datepicker="+ $("#datepicker").val());}
</script>
</html>
view_calls_sort.inc.php:
$datepicker=$_GET['datepicker'];
echo $datepicker;
im trying to get the datepicker value to view_calls_sort.inc.php, Above code doesn't seem to work,as an example when I input datetime like this
2005-04-19 12:00:00.000 it is not shown in view_calls_sort.inc.php, Can any one help me with this. Thanks
Try encoding it:
var value = $("#datepicker").val();
$("#firstp").load("view_calls_sort.inc.php", { datepicker: value });
or:
$("#firstp").load("view_calls_sort.inc.php?datepicker=" + encodeURIComponent(value));
Also make sure that your script tag is inside your <html> tag and not as it is currently shown in your question.
First, make sure that the function is called.
<script type="text/javascript">
function test_function(){
alert($("#datepicker").val());
$("#firstp").load(
"view_calls_sort.inc.php?datepicker="+$("#datepicker").val());
}
</script>
If the alert shows up, the method is called. And you get to see which value is sent to the server.
You also could change the php script and have it return a fixed value (echo 'Foo';) so you can see if the script is called.
Have a form that is not being read by serialize() function.
<script type="text/javascript">
function submitTrans1(){
var formData = $('form1').serialize();
var options = {
method:'post',
postBody:'formData',
onCreate: function(){alert(formData)},
onSuccess: function(transport){alert("onSuccess alert \n" + transport.responseText);},
onComplete: function(){alert('complete');},
onFailure: function(){alert('Something went wrong...')}
}
new Ajax.Request('/clients/addTrans/<?=$clientID123?>/',options);
}
</script>
<?php
$datestring = "%Y-%m-%d";
$time = time();
$clid1 = $this->uri->segment(3);
?>
<form name="form1" id="form1">
<div id="addTransDiv" style="display:none">
<div class="">
<label for="transDesc" id="transDesc" value="sadf" class="preField">Description</label>
<textarea cols="40" rows="3" id="transDesc" value="" name="transDesc" class=""></textarea>
</div>
<div class="">
<label for="date" class="preField">Date</label>
<input type="date" id="transDate" name="date" value="<?=mdate($datestring, $time);?>" size="40" class=""/><br/>
</div>
<div class="">
<label for="userfile" class="preField">File</label>
<input type="file" name="transFile" id="userfile" size="20" /><br>
</div>
<input type="button" id="submitTrans" name="submitTrans" value="Submit" onclick="submitTrans1()">
</div>
</form>
Uh, I have an alert in the onSuccess parameter of the Ajax.Request that would ideally alert the variable assigned to the serialized form. However, when it alerts, it alerts nothing. I also have the processing url printing out the $_POST data just in case, but that as well returns an empty array in the responseText, so indeedidly nothing is being posted to the form.
Thx.
Edit1
it seems that the problem might be related to the fact that the form is inside a div. If I remove everything on the page except for the form and js, it works ok. But the form is in a div that is hidden by default and uses another function to be displayed. Is there some kind of magic needed to get form data via serialize if it's in a div?
Edit 2
Tried adding quotes and pound signs and all that other jazz. I am using web developer toolbar, firebug, etc... it isn't throwing any js errors and doesn't afraid of anything.
Try removing the quotes from around the variable name formData in the postBody field.
The web developer toolbar in Firefox is as useful as anything for debugging client-side javascript.
BTW, the snippet contains a few undefined items, like the JS function showTransAdd(), several PHP variables, the PHP function mdate(), and the inclusion of the prototype library.
Change this line:
var formData = $('form1').serialize();
to this:
var formData = $('#form1').serialize();
I had to change several other things to make a working copy, but I'm not sure about what all code you withheld or how your environment may differ. If that doesn't work, I can send you the full code snippet I used.
Erroneous table does the breaking.
I had the form within a table with no tr's or td's (not sure if the last part matters) and upon removing the table tags, everything is working.
The relevant js now looks like:
var formData = $('form1').serialize();
var options = {
method:'post',
postBody:formData,
[...]
I'd like to thank the Academy, and all those that helped me.