ajax get and insert with php and mysql - php

I have a page that has a form on it, when I click a button on the page it sends 3 variables to a layer(page_ref, template_ref, and box_id) via a javascript call.
Then with ajax I get some content from the mysql db with the variables and insert this into a text area on the layer.
The layer has a save button and when I click that I want to save the content of the textarea back to the db.
I can fill the textarea from the db no problem but am having problems pushing is back to the db.
The problem I have is sending the javascript variables to the ajax update page as they need to be passed to php varriables.
heres what I have
on the main page I call a javascript function
edit_box('show',i,'<? echo $page_ref; ?>','<? echo $template_ref; ?>');
in the layer I have this
<style type="text/css">
#popupbox
{
padding:0;
width: 99%;
height: auto;
margin: 0px auto;
position:absolute;
background: #FBFBF0;
border: solid #000000 2px;
z-index: 9000;
font-family: arial;
visibility: hidden;
}
</style>
<script type="text/javascript" src="http://js.nicedit.com/nicEdit-latest.js"></script>
<script>
//Browser Support Code
function get_edit_content(box_id,page_ref,template_ref)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("edit_content").innerHTML=xmlhttp.responseText;
var area1 = new nicEditor({fullPanel : true}).panelInstance("edit_content",{hasPanel : true});
}
}
var queryString = "?box_id=" + box_id + "&page_ref=" + page_ref + "&template_ref=" + template_ref;
xmlhttp.open("GET","get_content.php" + queryString,true);
xmlhttp.send();
}
$("#sub").click( function()
{
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info)
{
$("#result").html(info);
});
clearInput();
});
$("#myForm").submit( function()
{
return false;
});
function clearInput()
{
$("#myForm :input").each( function()
{
$(this).val('');
});
}
function edit_box(showhide,box_id,page_ref,template_ref)
{
if(showhide == "show")
{
get_edit_content(box_id,page_ref,template_ref);
document.getElementById('popupbox').style.visibility="visible";
}
else if(showhide == "hide")
{
document.getElementById('popupbox').style.visibility="hidden";
}
}
</script>
<div id="popupbox">
<form id="myForm" action="update_textarea.php" method="post">
<input type="hidden" name="page_ref" value="<? echo $page_ref; ?>" />
<input type="hidden" name="template_ref" value="<? echo $template_ref; ?>" />
<input type="hidden" name="box_id" value="<? echo $box_id; ?>" />
<textarea name="edit_content" id="edit_content" style="width: 500px; height:500px;"></textarea>
<center>close</center>
<button id="sub">Save</button>
</form>
</div>
then I have get_contents page
<?php
include("connect.php");
$page_ref = $_GET['page_ref'];
$template_ref = $_GET['template_ref'];
$box_id = $_GET['box_id'];
$sql = "SELECT * FROM site_content WHERE page_ref='$page_ref' AND template_ref='$template_ref' AND box_id='$box_id' AND box_type='text'";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result))
{
echo "<p>".$row['content']."</p>";
}
?>
and finally the update_textarea page
<?
include("connect.php");
$page_ref = $_POST['page_ref'];
$template_ref = $_POST['template_ref'];
$box_id = $_POST['box_id'];
$edit_content = $_POST['edit_content'];
if(mysql_query("UPADTE site_content SET content='$edit_content' WHERE page_ref='$page_ref' AND template_ref='$template_ref' AND box_id='$box_id' AND box_type='text'"))
{
echo "Successfully Inserted";
}
else
{
echo "Insertion Failed";
}
?>

I realised that i needed to set the values of the hidden inputs in the ajax call after
document.getElementById("edit_content").innerHTML=xmlhttp.responseText;
by adding
document.getElementById("box_id").value = box_id;
etc

Related

AJAX : Pass an image and data through Single AJAX [duplicate]

This question already has answers here:
How to send image to PHP file using Ajax?
(5 answers)
jQuery AJAX file upload PHP
(5 answers)
jQuery / ajax upload image and save to folder
(3 answers)
Upload image using jQuery, AJAX and PHP
(2 answers)
Closed 4 years ago.
I want to pass some text data and file through one ajax code
Here is my code's index.php :-
<?php
session_start();
if (#$_SESSION['user']!=true) {
echo "<script>window.alert('You are not login.');</script>";
echo "<script>window.open('login.php','_self');</script>";
}
else {
include_once '../connection.php';
$uid=$_SESSION['id'];
$query=mysqli_query($conn,"SELECT * FROM `register` WHERE `id`='$uid'");
$row=mysqli_fetch_array($query);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="Karthikeyan K">
<title>POST</title>
<!-- Bootstrap CSS file -->
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
<style type="text/css">
body {
padding: 45px;
}
footer {
margin: 10px 0;
}
.photo {
margin-bottom: 10px;
}
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
<link rel="stylesheet" type="text/css" href="css/jquery.mentionsInput.css">
<style type="text/css">
#status-overlay {
height: 100%;
width: 100%;
background: rgba(0, 0, 0, 0.50);
position: fixed;
top: 0;
left: 0;
z-index: 99999;
overflow: hidden;
}
#highlight-textarea {
background: #fff;
}
.form-control:focus {
box-shadow: 0 0 0 2px #3399ff;
outline: 0;
}
h2 {
font-size: 20px;
}
</style>
<style>
#upload_button {
display: none;
border: 0px;
background: linear-gradient(180deg, #f44, #811);
border-radius: 5px;
color: #fff;
padding: 5px;
}
</style>
</head>
<body>
<div id="status-overlay" style="display: none"></div>
<form method="POST" class="form" enctype="multipart/form-data">
<div class="form-group">
<input type="text" name="title" id="title" class="form-control" placeholder="Post title..."><br>
<div id="highlight-textarea">
<textarea onclick="highlight();" name="postText" class="form-control postText mention" cols="10" rows="8" placeholder="What's going on?" dir="auto"></textarea>
</div><br>
<select class="form-control" name="type" id="type" required>
<option value="">Choose Post Type</option>
<option value="Closet">Closet</option>
<option value="Follower">Follower</option>
<option value="Group">Group</option>
</select><br>
<p><button id="upload_button">Click here to select file</button></p>
<p><input id="upload_input" name="upfile" type="file"/></p>
</div>
<input type="button" value="Post" class="btn btn-primary pull-right postMention">
</form>
<!-- Bootstrap Script file -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src='https://cdn.rawgit.com/jashkenas/underscore/1.8.3/underscore-min.js' type='text/javascript'></script>
<script src='js/lib/jquery.elastic.js' type='text/javascript'></script>
<script type="text/javascript" src="js/jquery.mentionsInput.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('textarea').on('click', function(e) {
e.stopPropagation();
});
$(document).on('click', function (e) {
$("#status-overlay").hide();
$("#highlight-textarea").css('z-index','1');
$("#highlight-textarea").css('position', '');
});
});
function highlight()
{
$("#status-overlay").show();
$("#highlight-textarea").css('z-index','9999999');
$("#highlight-textarea").css('position', 'relative');
}
$(document).ready(function(){
$('.postMention').click(function() {
$('textarea.mention').mentionsInput('val', function(text) {
var post_text = text;
if(post_text != '')
{
//post text in jquery ajax
var post_data = "text="+encodeURIComponent(post_text);
var val1 = $('#title').val();
var val2 = $('#type').val();
//var val3 = $('#upload_input');
//var post_title = $('#title').val();
var form = new FormData(document.getElementById('.postMention'));
//append files
var file = document.getElementById('upload_input').files[0];
if (file) {
form.append('upload_input', file);
}
$.ajax({
type: "POST",
data: post_data+'&title='+val1+'&type='+val2+'&upload_input='+form,
url: 'ajax/post.php',
success: function(msg) {
if(msg.error== 1)
{
alert('Something Went Wrong!');
} else {
$("#post_updates").prepend(msg);
//reset the textarea after successful update
$("textarea.mention").mentionsInput('reset');
}
}
});
} else {
alert("Post cannot be empty!");
}
});
});
//used for get users from database while typing #..
$('textarea.mention').mentionsInput({
onDataRequest:function (mode, query, callback) {
$.getJSON('ajax/get_users_json.php', function(responseData) {
responseData = _.filter(responseData, function(item) { return item.name.toLowerCase().indexOf(query.toLowerCase()) > -1 });
callback.call(this, responseData);
});
}
});
});
</script>
</body>
</html>
<?php } ?>
here's a code of my php file to insert data into database ajax/post.php
. . . .
<?php
session_start();
if (#$_SESSION['user']!=true) {
echo "<script>window.alert('You are not login.');</script>";
echo "<script>window.open('login.php','_self');</script>";
}
else {
include_once '../../connection.php';
$uid=$_SESSION['id'];
$query=mysqli_query($conn,"SELECT * FROM `register` WHERE `id`='$uid'");
$row=mysqli_fetch_array($query);
if(isset($_POST) && !empty($_POST['text']) && $_POST['text'] != '')
{
include '../config/config.php';
$user = $uid; //w3lessons demo user
$postid=mt_rand();
$text = strip_tags($_POST['text']); //clean the text
$title= $_POST['title'];
$type= $_POST['type'];
define('FIRST_MATCH_GROUP', 1);
preg_match_all("/#\[(.+)\]/U", $text, $tags); // Value under #[]
$tags = implode(',', $tags[FIRST_MATCH_GROUP]);
$upfile_name = $_FILES['upload_input']['name'];
$upfile_size =$_FILES['upload_input']['size'];
$upfile_tmp =$_FILES['upload_input']['tmp_name'];
$upfile_type=$_FILES['upload_input']['type'];
$upfile_t = explode(".", $_FILES["upload_input"]["name"]);
$upfile_name = mt_rand() . '.' . end($upfile_t);
if($upfile_type == "image/jpg" && $upfile_type == "image/png" && $upfile_type == "image/jpeg" && $upfile_type == "video/mp4"){
echo "<script>window.alert('extension not allowed, please choose a JPG or PNG or MP4 file.');</script>";
}
else {
if($upfile_size > 10485760){
echo "<script>window.alert('File size must be Less 10 MB');</script>";
}
else {
move_uploaded_file($upfile_tmp,"../../uploads/".$upfile_name);
$DB->query("INSERT INTO posts(post_id,title,content,user_id,type,tags,image) VALUES(?,?,?,?,?,?,?)", array($postid,$title,$text,$user,$type,$tags,$upload_input));
?>
<div class="media">
<div class="media-left">
<img src="https://cdn.w3lessons.info/logo.png" class="media-object" style="width:60px">
</div>
<div class="media-body">
<h4 class="media-heading">w3lessons</h4>
<p><?php echo getMentions($text); ?></p>
</div>
</div>
<hr>
<?php
} } } else {
echo "1"; //Post Cannot be empty!
}
function getMentions($content)
{
global $DB;
$mention_regex = '/#\[([0-9]+)\]/i'; //mention regrex to get all #texts
if (preg_match_all($mention_regex, $content, $matches))
{
foreach ($matches[1] as $match)
{
$match_user =$DB->row("SELECT * FROM register WHERE id=?",array($match));
$match_search = '#[' . $match . ']';
$match_replace = '<a target="_blank" href="' . $match_user['profile_img'] . '">#' . $match_user['first_name'] . '</a>';
if (isset($match_user['id']))
{
$content = str_replace($match_search, $match_replace, $content);
}
}
}
return $content;
}
}?>
When i submit form data was passing at my php page but images index is goes undefined...
change the way you pass data in request
try this
$(document).ready(function(){
$('.postMention').click(function() {
$('textarea.mention').mentionsInput('val', function(text) {
var post_text = text;
if(post_text != '')
{
var formData = new FormData($('.form')[0]);
formData.append('text',encodeURIComponent(post_text));
$.ajax({
url: 'ajax/post.php',
type: 'POST',
data: formData,
success: function (data) {
if(msg.error== 1)
{
alert('Something Went Wrong!');
} else {
$("#post_updates").prepend(msg);
//reset the textarea after successful update
$("textarea.mention").mentionsInput('reset');
}
},
cache: false,
contentType: false,
processData: false
});
} else {
alert("Post cannot be empty!");
}
});
});
and input name
<input id="upload_input" name="upload_input" type="file"/>

Can I select mysqli db rows using ajax?

I'm creating a program in php where the user chooses a letter and then in the screen are printed all the names starting with this letter which are stored in my mysql "presta_prova" database.
Here is my code (php file):
<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table,
td,
th {
border: 1px solid black;
padding: 5px;
}
th {
text-align: left;
}
</style>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "presta_prova.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Scegliete una lettera:</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
</form>
<br>
<div id="txtHint"><b>Vedi qui i tipi ti marche:</b>
</div>
<?php $q=i ntval($_GET[ 'q']); $con=m ysqli_connect( 'localhost', 'root', 'evolvia2016', 'presta_prova'); if (!$con) { die( 'Could not connect: ' . mysqli_error($con)); } mysqli_select_db($con, "presta_prova"); $sql="SELECT * FROM presta_prova WHERE marca LIKE '"
.$q%. "' "; $result=m ysqli_query($con,$sql); echo "<table>
<tr>
<th>Marca</th>
<th>Descrizione</th>
</tr>"; while($row=m ysqli_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row[ "marca"] . "</td>"; echo "<td>" . $row[ "descrizione"] . "</td>"; echo "</tr>"; } echo "</table>"; mysqli_close($con); ?>
</body>
</html>
But when I choose a letter this is my output. Instead of my rows of the database this program outputs the head of the table.Have I done something wrong with my code? Maybe this way doesnt work for mysqli database? Thanks!
Here is my database :
If the aim is to populate the table with new rows rather than appending the response into a div which is how it appears then you could restructure the code and use POST like this.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
/* Forgot to change this to POST! */
$q=intval($_POST[ 'q']);
$con=mysqli_connect( 'localhost', 'root', 'evolvia2016', 'presta_prova');
if (!$con)die( 'Could not connect: ' . mysqli_error($con));
mysqli_select_db($con, "presta_prova");
$sql="SELECT * FROM presta_prova WHERE marca LIKE '".$q."%' ";
$result=mysqli_query($con,$sql);
$html=array("<tr><th>Marca</th><th>Descrizione</th></tr>");
while( $row=mysqli_fetch_array($result) ) {
$html[]="<tr><td>" . $row[ "marca"] . "</td><td>" . $row[ "descrizione"] . "</td></tr>";
}
mysqli_close($con);
exit( implode(PHP_EOL,$html) );
}
?>
<!DOCTYPE html>
<html>
<head>
<title>gotta have a title</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table,
td,
th {
border: 1px solid black;
padding: 5px;
}
th {
text-align: left;
}
</style>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("results").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("POST", location.href, true );/*"presta_prova.php"*/
/* send the content-type header */
xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
/* my mistake here, this should be like this rather than object literal. */
xmlhttp.send( 'q='+str );
}
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser( this.value )">
<option value="">Scegliete una lettera:</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
</form>
<br>
<div id="txtHint"><b>Vedi qui i tipi ti marche:</b>
</div>
<table id='results'>
<tr>
<th>Marca</th>
<th>Descrizione</th>
</tr>
</table>
</body>
</html>
Fully working example without database interaction but to show the selection mechanism working.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
$q=intval( $_POST[ 'q'] );
$t=$_POST['text'];
/* emulated database search and results being generated */
$html=array('<tr><th>Marca</th><th>Descrizione</th></tr>');
for( $i=0; $i < 10; $i++ ) $html[]='<tr><td>Marca:'.$i.' q='.$q.'</td><td>Descrizione:'.$i.' text='.$t.'</td></tr>';
header( 'Content-Type: text/html' );
exit( implode( PHP_EOL, $html ) );
}
?>
<!DOCTYPE html>
<html>
<head>
<title>gotta have a title</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table,
td,
th {
border: 1px solid black;
padding: 5px;
}
th {
text-align: left;
}
</style>
<script>
function showUser(o) {
if (o.value == '') {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("results").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open( "POST", location.href, true );
xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xmlhttp.send( 'q='+o.value+'&text='+o.options[o.options.selectedIndex].text );
}
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser( this )">
<option value="">Scegliete una lettera:</option>
<?php
/* Generate each letter of the alphabet as an option */
for( $i=0; $i<26; $i++ ){
$char=chr( $i + 65 );
$int=$i+1;
echo "<option value='$int'>$char";
}
?>
</select>
</form>
<br>
<div id="txtHint"><b>Vedi qui i tipi ti marche:</b>
</div>
<table id='results'><!-- results will overwrite the table innerHTML -->
<tr>
<th>Marca</th>
<th>Descrizione</th>
</tr>
</table>
</body>
</html>

jQuery is not working in AJAX loaded div

This is my slider.php page in which content of ajax.php file is loaded through ajax.
var xmlhttp;
function showtemplate(temp)
{
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState===4 && xmlhttp.status===200) {
var div = document.getElementById('contain');
div.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'ajax.php?section='+temp, true);
xmlhttp.send();
}
The content of ajax.php file is loading into the contain div.
This is my ajax.php file where I am using jquery to slideshow images.
<?php
$final=$_REQUEST['section'];
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js?ver=1.4.2"></script>
<script type="text/javascript">
$(function()
{
var currentIndex = 0,
var items = $('.container div'),
var itemAmt = items.length;
function cycleItems()
{
var item = $('.container div').eq(currentIndex);
items.hide();
item.css('display','inline-block');
}
var autoSlide = setInterval(function()
{
currentIndex += 1;
if (currentIndex > itemAmt - 1)
{
currentIndex = 0;
}
cycleItems();
}, 3000);
$('.next').click(function() {
clearInterval(autoSlide);
currentIndex += 1;
if (currentIndex > itemAmt - 1)
{
currentIndex = 0;
}
cycleItems();
});
$('.prev').click(function() {
clearInterval(autoSlide);
currentIndex -= 1;
if (currentIndex < 0) {
currentIndex = itemAmt - 1;
}
cycleItems();
});
});
</script>
<section class="demo">
<button class="next" id="next">Next</button>
<button class="prev" id="prev">Previous</button>
<div class="container">
<div style="display: inline-block;">
<img src='images/<?php echo $final;?>/image1.jpg'/>
</div>
<div>
<img src='images/<?php echo $final;?>/image2.jpg'/>
</div>
<div>
<img src='images/<?php echo $final;?>/image3.jpg'/>
</div>
<!--<span u="arrowleft" class="jssora12l" style="width: 41px; height: 50px; top: 110px; left: 2px;"> </span>
<span u="arrowright" class="jssora12r" style="width: 41px; height: 50px; top: 110px; right: 5px"> </span>-->
</div>
but when I clicked on next and previous button it doesn't work. Please help me out.
My code is working now. I simply request section and display it as thumbs without using jquery.
<?php
$final=$_REQUEST['section'];
include "slider/relatedcat.php";
?>
<div style="margin-bottom: 10px; font-size: 18px;font-family: 'Roboto Slab',serif;margin-top: -7px">Choose <?php echo ucwords($final);?> Card Template.</div>
<?php
for($i=1;$i<=count($template);$i++)
{
?>
<div id="thumb<?php echo $i;?>" onclick='showimage("template<?php echo $i; ?>","<?php echo $final;?>");' style='box-shadow: rgba(34, 25, 25, 0.4) 0px 1px 3px;border-radius: 15px;width: 150px !important;height: 150px !important;top: 0px;float:left;margin-right: 20px;margin-bottom:15px;overflow: hidden;transform: perspective(2000px);background: white;cursor: pointer;'>
<img alt='<?php echo ucwords($final);?>' u='image' src='images/<?php echo $final;?>/template<?php echo $i?>.jpg' style='width:100%;height:100%;' />
</div>
<?php
}
?>
If you want to use jquery in ajax loaded div then you have to redefine jquery function on success of ajax function like below code :
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState===4 && xmlhttp.status===200) {
var div = document.getElementById('contain2');
div.innerHTML = xmlhttp.responseText;
$('#resize').draggable({containment: '#main'}).resizable({maxWidth:350, maxHeight:333});
$('#msgvisible').draggable({containment: '#main'});
//alert(xmlhttp.responseText);
document.getElementById('stylepart').style.display="block";
}
}

Show 'All Records' Option

I've put together the form below that allows a user to retrieve database records from the date they select from a drop down menu.
<html>
<head>
<script type="text/javascript">
function ajaxFunction(name)
{
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer")
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else
{// code for IE6, IE5
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("my_div").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getrecords.php?dateoftrip="+name,true);
xmlhttp.send();
}
function getquerystring() {
var form = document.forms['frm1'];
var word = form.word.value;
qstr = 'w=' + escape(word); // NOTE: no '?' before querystring
return qstr;
}
</script>
<style type="text/css">
<!--
.style1 {
font-family: Calibri;
font-size: 14px;
}
-->
</style>
</head>
<body>
<form action="getrecords.php" method="get" name="frm1">
<table width="148" border="0">
<tr>
<td width="152"><p class="style1">Select a date from below</p>
<div align="center">
<?php
include("db.php");
$query="select * from finds group by dateoftrip";
echo '<select onchange="ajaxFunction(this.value)">';
$result=mysql_query($query);
while($rows=mysql_fetch_array($result)){
echo "<option name='name' value=".$rows['dateoftrip'].">".$rows['dateoftrip']."</option>";
}
echo "</select>";
?>
</div></td>
</tr>
</table>
</form>
<div id="my_div"></div>
</body>
</html>
and this is the php script which retrieves the records.
<?php
include("db.php");
$dateoftrip= $_GET['dateoftrip'];
$findname= $_GET['findname'];
$finddescription= $_GET['finddescription'];
$query="select * from finds where dateoftrip='$dateoftrip'";
echo "<table>";
$result=mysql_query($query);
while($rows=mysql_fetch_array($result)){
echo "<tr>";
echo "<td>Find Name : </td>";
echo "<td>".$rows['findname']."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Find Description : </td>";
echo "<td>".$rows['finddescription']."</td>";
echo "</tr>";
}
echo "</table>";
?>
I'd like to extend the functionality a little if at all possible, by adding a 'All Records' option to the drop down menu which obviously returns all the records for the current user.
I've been searching for this for a few days now, and I haven't found an example where there is this added functionality.
I just wondered whether someone could perhaps provide some guidance on how I may go abut this please.
Amended Form Code
<html>
<head>
<script type="text/javascript">
function ajaxFunction(name)
{
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer")
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else
{// code for IE6, IE5
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("my_div").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getrecords.php?dateoftrip="+name,true);
xmlhttp.send();
}
function getquerystring() {
var form = document.forms['frm1'];
var word = form.word.value;
qstr = 'w=' + escape(word); // NOTE: no '?' before querystring
return qstr;
}
</script>
<style type="text/css">
<!--
.style1 {
font-family: Calibri;
font-size: 14px;
}
-->
</style>
</head>
<body>
<form action="getrecords.php" method="get" name="frm1">
<table width="148" border="0">
<tr>
<td width="152"><p class="style1">Select a date from below</p>
<div align="center">
<?php
include("db.php");
$query="select * from finds group by dateoftrip";
echo '<select onchange="ajaxFunction(this.value)"><OPTION name="name" value="ALLRECORDS">';
$result=mysql_query($query);
while($rows=mysql_fetch_array($result)){
echo "<option name='name' value=".$rows['dateoftrip'].">".$rows['dateoftrip']."</option>";
}
echo "</select>";
?>
</div></td>
</tr>
</table>
</form>
<div id="my_div"></div>
</body>
</html>
Create an option for the 'ALL' thing
echo '<select onchange="ajaxFunction(this.value)"><OPTION name="name" value="ALLRECORDS">All Records</option>';
Handle your query for the 'ALL' thing
if ($dateoftrip=="ALLRECORDS") {
$query="select * from finds";
} else {
$query="select * from finds where dateoftrip='$dateoftrip'";
}
On a side note you should look about SQL Injection, not using the '*' selector but typing the explicit name of attributes you search

Why am I unable to get sever time?

<html>
<head>
<title>Ajax Demonstration</title>
<style>
.displaybox {
width:150px;
background-color:#ffffff;
border:2px solid #000000;
padding:10px;
font:24px normal verdana, helvetica, arial, sans-serif;
}
</style>
<script language="JavaScript" type="text/javascript">
//<%=new java.util.Date()%>
function getXMLHTTPRequest() {
alert("Hello! I am an alert box!");
try {
req = new XMLHttpRequest();
} catch (err1) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (err2) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (err3) {
req = false;
}
}
}
return req;
}
var http = getXMLHTTPRequest();
function getServerTime() {
var myurl = 'http://localhost/csp 2/telltimeXML.php';
myRand = parseInt(Math.random() * 999999999999999);
// var modurl = myurl+"?rand="+myRand;
http.open("GET", myurl, true);
http.onreadystatechange = useHttpResponse;
http.send(null);
}
function useHttpResponse() {
if (http.readyState == 4) {
if (http.status == 200) {
var timeValue = http.responseXML.getElementsByTagName("timenow")[0];
alert(timeValue);
document.getElementById('showtime').innerHTML = timeValue.childNodes[0].nodeValue;
}
}
}
</script>
</head>
<body style="background-color:#cccccc"
onLoad="getServerTime()">
<center>
<h1>Ajax Demonstration</h1>
<h2>Getting the server time without page refresh</h2>
<form>
<input type="button" value="Get Server Time"
onClick="getServerTime()">
</form>
<div id="showtime" class="displaybox"></div>
</center>
</body>
</html>
Code for the PHP file:
<?php header('Content-Type: text/xml'); echo "<?xml version=\"1.0\" ?><clock1><timenow>" .date('H:i:s')."</timenow></clock1>"; ?>
Could be lots of things, since as others have pointed out we'd like to know what you are seeing. But one guess is that the url you are requesting is not hosted on the same server as the html file. That is, the html page you are one should be on http://localhost/.

Categories