Hi I am trying to pass values using 'post' from three drop down lists to the database using php script where I insert values into the database with values of the three lists
previously I retrieved a list from another page into a div time.php using jquery ajax call
code for which looks like this :-
//This script uses jquery and ajax it is used to set the values in
// the time field whenever a day is selected.
$(document).ready(function(){
$("#day").change(function(){
var day=$("#day").val();
var doctor=$("#doctor").val();
$.ajax({
type:"post",
url:"time.php",
data:"day="+day+"&doctor="+doctor,
success:function(data){
$("#time").html(data);
}
});
});
});
code for the html section looks something like this:-
<select id="doctor">some options</select>
<select id="day">some options</select>
<div id="time"> </div>
Now the values from the two lists are going through fine. But the one I retrieved into the div is not going through. Could you point me in the right direction?
Thanks in advance.
//The php script for insertion
<?php
session_start(); //Use this to include session variables
$con=mysqli_connect("localhost","clinic","myclinic","myclinic");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "INSERT INTO appointment(username, doctor, day, time) VALUES('$_SESSION[username]', '$_POST[doctor]', '$_POST[day]', '$_POST[time]')";
if (!mysqli_query($con,$query))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
header("location:login_success.php");
?>
If you want to retrive div content like input, select etc
You have to get it like
var time = $("#time").html();
Your code will be
Add a button to your page
<input type='button' value='Send' id='send'>
Then add
$(document).ready(function(){
$("#send").click(function(){
var day=$("#day").val();
var doctor=$("#doctor").val();
var time = $("#time").find("select").val();
$.ajax({
type:"post",
url:"time.php",
data:"day="+day+"&doctor="+doctor+"&time="+time, //add param
success:function(data){
}
});
});
});
Related
Basically, on my HTML display page, mainHTML.php I include a PHP file called phpFunctions.php with some of the PHP functions I made and call these functions. One of them in particular gets information from a SQL database and makes a table from it.
On mainHTML.php, I have an ajax script that gets the value from a select box that is on same page, on change.
<script>
$(document).ready(function() {
$('select[name="selectBox"]').change(function(){
var value = $(this).val();
$.ajax({
type: 'POST',
url: 'ajaxScript.php', //if bug change to ajaxScript.php
data: {valueChange: value },
dataType: 'html'
}).done(function(response){
$('.response-holder').html(response);
});
});
});
</script>
My ajaxScript looks like so. At the moment, all I can get it to do is echo something based on the value of the select box.
<?php
$status = $_POST['valueChange'];
if($status == 'height'){
echo "ORDER BY height";
}
if($status == 'weight'){
echo "ORDER BY weight";
}
?>
All of this works fine but then I come into a problem. I don't know how I can append the SQL string present in a function in phpFunctions.php so that it may be modified based on the ajaxScript.php condition.
Thanks in advance.
I'm coding a voting system for multiple uploads; each uploaded image is in a foreach statement with a form attached to each, with three buttons to vote up, down or none, each associated with an INT in my mysql database.
I got it to work by submitting the form data straight to the PHP function that 'UPDATE's the database. To avoid a page refresh, I attach ajax. I got the ajax to send the two variables needed for the PHP function to update the correct "image" row and INT in the db.
Question: The ajax function works, but the PHP function doesn't seem to update.
SUSPECTED PROBLEM: I'm pretty sure it's the way I'm defining the variables in ajax that I want to pass, I was trying to grab the ID of the "image" it's handling, but I don't know how to translate this data to the PHP function so that it UPDATE's correctly.
Here's the form, javascript, and php:
// IMAGE, and rest of foreach above this, and ending after form
// This form only shows one button, there are three, each
// I'll treat the same once I get one to work
<form action="feed.php" method="post" id="vote_form_1">
// If js isn't turned on in broswer, I keep this
// hidden input, to send unique ID
<input type="hidden" name ="input_id"
class="input_id" value="<?php echo $row['id']; ?>"/>
<input type="submit" name="post_answer1" onclick="sayHi(event);"
class="answer_L" id="<?php echo $row['id']; ?>"
value="<?php echo $row['post_answerL']; ?>"/>
</form>
// end of foreach
//AJAX
<script type="text/javascript">
function sayHi(e) {
var input_id = $(e.currentTarget).attr('id');
var post_answer1 = $("input[name='post_answer1']");
jQuery.ajax({
type: 'POST',
url: 'feed.php', //name of this file
data:input_id,post_answer1,
cache: false,
success: function(result)
{
alert ('It worked congrats');
}
});
e.preventDefault();
</script>
// PHP VOTE UPDATE FUNCTION
<?php>
if(isset($_POST['post_answer1'],$_POST['input_id'])){
$current_id = $_POST['input_id'];
$vote_1 = "UPDATE decision_post set " .
"post_answer1=post_answer1+1 WHERE id = '".$current_id."' ";
$run_vote1 = mysqli_query($conn2, $vote_1);
if($run_vote1){ echo 'Success'; }
}
?>
Here a simple answer, just serialize all your form data!
$('form').submit(function(){
$.post('feed.php', $(this).serialize(), function(data){
console.log(data);
}, 'json');
return false;
});
var post_answer1 = $("input[name='post_answer1']").val();
I have this codes below. It works when a filter parameter is presssed on keyup. but i need the content of the database to load via ajax as soon as the page is ready even when no filter search is initiated.
here are my codes
jquery
<script type="text/javascript">
$(document).ready(function(){
$('.autosuggest').keyup(function() {
var search_term = $(this).attr('value');
$.post('actionSessionsearch.php', {search_term: search_term}, function(data){
$('.divDisplay').html(data);
});
});
});
</script>
php
<?php
include_once('../includes/dc_conect.php');
if((!isset($_POST['search_term'])==true) and (!isset($_POST['search_term'])!=NULL)){
echo "hoho";
}
else
{ $search_term=$_POST['search_term'];
$sqlSession = "SELECT * FROM sessions WHERE session_name LIKE '%$search_term%'";
$resultSession=mysql_query($sqlSession, $link) or die (mysql_error());
$dbfieldSession=mysql_fetch_assoc($resultSession);
$countSession=mysql_num_rows($resultSession);
do{
echo $dbfieldSession['session_name'].'<br>';
}while($dbfieldSession=mysql_fetch_assoc($resultSession));
}
?>
it only retireves when i enter a value into the search box. I want to have my database details display even when the filter has not been initiated!
You could do following things:
PHP
if((!isset($_POST['search_term'])==true) and (!isset($_POST['search_term'])!=NULL)){
/* Load data from Database here, something like SELECT * FROM sessions;*/
}
else
{ $search_term=$_POST['search_term'];
$sqlSession = "SELECT * FROM sessions WHERE session_name LIKE '%$search_term%'";
$resultSession=mysql_query($sqlSession, $link) or die (mysql_error());
$dbfieldSession=mysql_fetch_assoc($resultSession);
$countSession=mysql_num_rows($resultSession);
do{
echo $dbfieldSession['session_name'].'<br>';
}while($dbfieldSession=mysql_fetch_assoc($resultSession));
}
JS
Call your AJAX function inside $(document).ready(function(){...}) and use $.get instead of $.post
I have some divs with class content-full which are created according to the data stored in a MySQL table. For example, if I have 3 rows there will be 3 divs.
When I click on any of the divs then the data associated with the ID for that div should be displayed inside div content-full. However, the content associated with the last div appears when I click on any of the divs because I am not passing any kind of variable ID that can be used to specify the clicked div.
<script type="text/javascript">
$(document).ready(function() {
$(".content-short").click(function() { //
$.ajax({
type: "GET",
url: "content.php", //
dataType: "text",
success: function(response){
$(".content-full").html(response);
}
});
});
});
</script>
content.php
<?php
include "mysql.php";
$query= "SELECT Content FROM blog limit 1";
$result=mysql_query($query,$db);
while($row=mysql_fetch_array($result))
{
echo $row['Content'];
}
mysql_close($db);
?>
Is there an alternate way to do this or something that I need to correct for it to work?
Thanks
First off, you will have to pass actual data to the your PHP script. Let's first deal with the JavaScript end. I am going to assume that your HTML code is printed using php and you are able to create something like the following: <div class=".content-short" data-id="2" />:
$(".content-short").click(function() {
// get the ID
var id = $(this).attr('data-id');
$.ajax({
type: "post",
url: "content.php",
data: 'id=' + id
dataType: "text",
success: function(response){
$(".content-full").html(response);
}
});
});
Next up is reading the value you passed in using the script:
<?php
include "mysql.php";
// Use the $_POST variable to get all your passed variables.
$id = isset($_POST["id"]) ? $_POST["id"] : 0;
// I am using intval to force the value to a number to prevent injection.
// You should **really** consider using PDO.
$id = intval($id);
$query = "SELECT Content FROM blog WHERE id = " . $id . " limit 1";
$result = mysql_query($query, $db);
while($row=mysql_fetch_array($result)){
echo $row['Content'];
}
mysql_close($db);
?>
There you go, I have modified your query to allow fetching by id. There are two major caveats:
First: You should not use the mysql_ functions anymore and they are deprecated and will be removed from PHP soon if it has not happened yet!, secondly: I cannot guarantee that the query works, of course, I have no idea what you database structure is.
The last problem is: what to do when the result is empty? Well, usually AJAX calls send and respond with JSON objects, so maybe its best to do that, replace this line:
echo $row['Content'];
with this:
echo json_encode(array('success' => $row['Content']));
Now, in your success function in JS, you should try to check if there a success message. First of, change dataType to json or remove that line entirely. Now replace this success function:
success: function(response){
$(".content-full").html(response);
}
into this:
success: function(response){
if(response.success) $(".content-full").html(response);
else alert('No results');
}
Here the deprecation 'notice' for the mysql_ functions: http://php.net/manual/en/changelog.mysql.php
You can look at passing a parameter to your script, generally like an id by which you can search in the db.
The easiest way to achieve this is by get parameters on the url
url: "content.php?param=2",
Then in php:
<?php $param = $_GET['param'];
...
I am trying to make a facebook style wall on my website. The goal is to insert form data, validate all forms as required, and store this data into a database. Simultaneously and separately I want all data stored in this database to be posted into a div that acts as the facebook wall.
I seem to have accomplished storing the data from the form. I can also retrieve all data in the database except it only does it when I submit the form. Which means no page content unless the user submits a post.
How can I populate my page with rows from my database when a user opens the page or before?
Please help!
Here is my php which stores and prints data when the html form is submitted.
<?php
// Create connection
$con=mysqli_connect("localhost","root","","test");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO test (school, confession)
VALUES
('$_POST[school]','$_POST[confession]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
// print $_POST['college']."-<br />".$_POST['confession'];
$result = mysqli_query($con,"SELECT * FROM test");
while($row = mysqli_fetch_array($result))
{
echo "#" . $row['ID'] . " " . $row['confession'];
echo "<br>" . "#" .$row['school'];
echo "<br>" . "<br>";
}
mysqli_close($con);
?>
Here is my JS which posts to a div called content.
$(document).ready(function(){
$("#subform").validate({
submitHandler: function(form) {
// do other stuff for a valid form
$.post('test.php', $("#subform").serialize(), function(data) {
$('#content').html(data);
});
}
});
});
Another approach is to load data on mouse scroll like:
//approx this
$(document).ready(function () {
var flg='1';
$(window).scroll(function () {
console.log($(document).scrollTop());
if ($(document).scrollTop() >299){
if(flg=='1')
{
$.post( 'link to server side code', function( data ) {
$('#morefrom').html(data.htmls);
},'json');
flg='0';
}
}
});});
This way you can load data on a specific mouse scroll value(like if a user gets on the bottom of the page you load new rows)
scrollTop docs
You can use a JavaScript Timer which will ticks after certain interval and load your Data, plus you must have to write a function that will just fetch the Data in your test.php file
function dataLoader()
{
//load Data with GET Request $.get(. . . );
}
dataLoader();
setInterval(dataLoader, 1000);
or the Second option will to be use jquery Timer Library to achieve performance
Thanks for the replies I solved the problem. I just called the php on load.
$(document).ready(function(){
$("#subform").validate({
submitHandler: function(form) {
// do other stuff for a valid form
$.post('test.php', $("#subform").serialize(), function(data) {
$('#subform').html(data);
});
}
});
});