jQuery and JavaScript AJAX Database Queries - php

I seem to have no luck with these darn AJAX MySQL queries...
I'm trying to query the database when a selection from a drop-down menu is made, and fill a div with the results from the script. I've tried two different ways, with no luck either time.
METHOD 1
Javascript
var ajaxRequest;
var create_url = "create_script.php";
var process_url = "process.php";
try{
ajaxRequest = new XMLHttpRequest();
} catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
alert("Your browser broke!");
}
}
}
function races(id)
{
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
document.getElementById('race_info').innerHTML = ajaxRequest.responseText;
}
}
var params = "mode=race&id="+id;
ajaxRequest.open("POST", create_url, true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.setRequestHeader("Content-length", params.length);
ajaxRequest.setRequestHeader("Connection", "close");
ajaxRequest.send(params);
}
function classes(id)
{
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
document.getElementById('class_info').innerHTML = ajaxRequest.responseText;
}
}
var params = "mode=classes&id="+id;
ajaxRequest.open("POST", create_url, true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.setRequestHeader("Content-length", params.length);
ajaxRequest.setRequestHeader("Connection", "close");
ajaxRequest.send(params);
}
the page body:
<div id="contentwrapper">
<div id="contentcolumn">
<div class="innertube">
<?php
if($step == 0)
{
?>
<form action="<?php echo $u_create; ?>" method="post">
<h2>Races</h2>
<select id="race_select" name="race_select">
<?php
$sql = 'SELECT * FROM '.RACES_TABLE;
$result = $db->sql_query($sql);
while($row = $db->sql_fetchrow($result))
{
echo '<option onfocus="races('.$row['race_id'].');" value="'.$row['race_id'].'">'.$row['race_name'].'</option>'."\n";
}
?>
</select>
<h2>Classes</h2>
<select id="class_select" name="class_select">
<?php
$sql = 'SELECT * FROM '.CLASSES_TABLE;
$result = $db->sql_query($sql);
while($row = $db->sql_fetchrow($result))
{
echo '<option onfocus="classes('.$row['race_id'].');" value="'.$row['class_id'].'">'.$row['class_name'].'</option>'."\n";
}
?>
</select>
<br />
<input type="submit" value="Select" name="submit" />
</form>
<br />
<div id="race_info"></div>
<br />
<hr />
<br />
<div id="class_info"></div>
<?php
}
?>
</div>
</div>
</div>
METHOD 2
AJAX
$(document).ready(function() {
$("#race_select").change(function() {
var race = $("#race").val();
$.ajax({
url: 'create_script.php',
data: 'mode=race&id=' + race,
dataType: 'json',
success: function(data)
{
$("#race_info").html(data);
}
});
});
$("#class_select").change(function() {
var class = $("#class").val();
$.post("create_script.php", { mode: "class", id: class }, function(data) {
$("#class_info").html(data);
});
});
});
The page body:
<div id="contentwrapper">
<div id="contentcolumn">
<div class="innertube">
<?php
if($step == 0)
{
?>
<form action="<?php echo $u_create; ?>" method="post">
<h2>Races</h2>
<select id="race_select" name="race_select">
<?php
$sql = 'SELECT * FROM '.RACES_TABLE;
$result = $db->sql_query($sql);
while($row = $db->sql_fetchrow($result))
{
echo '<option id="race" value="'.$row['race_id'].'">'.$row['race_name'].'</option>'."\n";
}
?>
</select>
<h2>Classes</h2>
<select id="class_select" name="class_select">
<?php
$sql = 'SELECT * FROM '.CLASSES_TABLE;
$result = $db->sql_query($sql);
while($row = $db->sql_fetchrow($result))
{
echo '<option id="class" value="'.$row['class_id'].'">'.$row['class_name'].'</option>'."\n";
}
?>
</select>
<br />
<input type="submit" value="Select" name="submit" />
</form>
<div id="race_info"></div>
<hr />
<div id="class_info"></div>
<?php
}
?>
</div>
</div>
</div>
None of the attempts have worked at all. I'm not sure what I'm doing wrong. There's not even a POST request being made on the select option change, according to firebug.

well for starters, in method two, all of your select options have the same ids. therefore, when querying:
var race = $("#race").val();
you will always get the first option.
instead, within the change function, this will refer to the selected element. so:
var race = $(this).val();
will get what you want
EDIT
Here is a simplified example using your code demonstrating your desired behavior in jsfiddle form: http://jsfiddle.net/7Xtqv/1/
hope that helps

In your jQuery AJAX request, you're setting dataType to JSON. So jQuery attempts to parse the JSON once received. If it fails, nothing happens. Not even the request shown in Firebug.
If you're using html in your AJAX return, you should set the dataType to HTML.
EDIT
Oh and in the second request in your jQuery file, you're doing var class = $("#class").val();. You might want to avoid naming your vars with reserved names: http://www.quackit.com/javascript/javascript_reserved_words.cfm
EDIT2
As #pthurlow noticed, there's a big fail with your IDs names. You're trying to get #race select, but there's no race ID in your HTML. There's a #race_select but it's different from #race.
It also fails with your #class stuff.

Related

Unexpected end of JSON input - Retrieving Data from server issue

I am trying to create a page whereby you can submit some text and then retrieve it on button press, I have managed to get it to submit to my server, however on retrieval I keep getting the error "unexpected end of JSON input" and have no idea what to do about it, my knowledge of PHP/JSON is very limited, any criticism / pointers are greatly appreciated.
JS:
function writeDoc() {
var xhttp = new XMLHttpRequest();
var url = "gethint.php";
var input = document.getElementById("text").value;
var clicker = document.getElementById("submit");
xhttp.open("POST", "gethint.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
alert("DataSubmitted");
}
}
xhttp.send("input= " + input);
}
function readDoc() {
var xxhttp = new XMLHttpRequest();
xxhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
var data = JSON.parse(this.responseText);
alert(data);
}
}
xxhttp.open("GET", "gethint2.php", true);
xxhttp.send();
}
PHP/HTML:
<php? session_start(); ?>
<html>
<script type="text/javascript" src="main.js"></script>
<head>
</head>
<body>
<label>Text Input To Save: </label>
<br></br>
<textarea rows="6" cols="20" id="text" name="textInput"></textarea>
<input type="submit" id="submit" onclick="writeDoc()">
<br></br>
<label>Retrieve Text :</label> <input type="button" id="getText"
onclick="readDoc()">
</body>
</html>
Sending Data:
<?
$_SESSION["input_data"] = $_POST;
echo $_POST["input"];
?>
Retrieving Data:
<?php
$_SESSION["input_data"] = json_encode($_POST);
?>

Can`t take value from html textarea to php variable

I made a blogging platform and I have an ajax updated page where I can select which article to display and his comments and add comments. When I leave a comment it takes the logged user info, the article on which the comment has been made but the comment value is not taken to store it in the database. This is the code :
<div align="center">
<h3>Comentarii:</h3>
<form method="POST">
<textarea rows="4" cols="50" name="comentariu" placeholder="Comenteaza">
</textarea><br>
<input type="submit" name="submit"><br>
<hr>
</form>
</div>
<?php
$comnou = $_POST['comentariu'];
$comuser = $_SESSION['user'];
$conadaugacom = mysqli_connect("localhost", "root", "", "blog");
$sqladaugacom = "insert into comentarii (continut_comentarii,
user_comentarii, articol_comentarii) values ('$comnou', '$comuser', '$ta')";
mysqli_query($conadaugacom, $sqladaugacom);
mysqli_close($conadaugacom);
?>
AJAX Code ->
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "getuser.php?q=" + str, true);
xmlhttp.send();
}
}
Make sure that before POST request serialize the data from form.
html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div align="center">
<h3>Comentarii:</h3>
<form method="POST">
<textarea rows="4" cols="50" name="comentariu" placeholder="Comenteaza">
</textarea><br>
<input type="submit" name="submit"><br>
<hr>
</form>
</div>
Jquery
<script>
$('input').submit(function(e){
e.preventDefault();
var data = $('form').serialize();
$.ajax({
url: 'your_url_to_post.php',
data: data,
success: function(response){
},
type: 'POST'
});
});
</script>
php file
add this line to check comentariu not empty
if(isset($_POST['comentariu'])){
$comentariu = $_POST['comentariu];
}

How to submit a form on SUBMIT or ENTER button

I am trying to follow a tutorial and demo. But when I press SUBMIT or ENTER button, it is not submitting, it is just refreshing the page :( and showing an error.
It shows an alert
There was a problem with the request.
And the page refreshes.
My form
<form class="well-home span6 form-horizontal" name="ajax-demo" id="ajax-demo"> <div class="control-group">
<label class="control-label" for="book">Book</label>
<div class="controls">
<input type="text" id="book" onKeyUp="book_suggestion()">
<div id="suggestion"></div>
</div> </div> <div class="control-group">
<div class="controls">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
And my Javascript
<script>
function book_suggestion()
{
var book = document.getElementById("book").value;
var xhr;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "book_name=" + book;
xhr.open("POST", "book-suggestion.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = display_data;
function display_data() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
//alert(xhr.responseText);
document.getElementById("suggestion").innerHTML = xhr.responseText;
} else {
alert('There was a problem with the request.');
}
}
}
}
</script>
book-suggestion.php
<?php
include('../includes/dbopen.php');
$book_name = $_POST['book_name'];
$sql = "select book_name from book_mast where book_name LIKE '$book_name%'";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result))
{
echo "<p>".$row['book_name']."</p>";
}
?>
The submit button used there is not participating in the demo. The purpose of the demo is to show how to fetch data with ajax when user types data in the text box. It may, for sure be extended so that the submit button acts upon and adds some more functions, but for now, that has not been added to the demo.

listbox not being populated in IE works in FF and Chrome

Hello I am working in php and javascript and have code where a admin can select a name in a dropdown box and it pulls up the locations that name is associated with these are sales guys. Well it works fine in FF and Chrome but in IE the list box just goes blank. hopefully someone can help me out bosses here use IE
Brent
DROPDOWN and LIST code
<label for="firstname"><?php echo ADD_EDIT_SALESREP;?><span class="required">*</span></label>
<select name="sales_rep" id="sales_rep" onChange="findLocation2(this.value)">
<option value="">Select</option>
<?php
$sqlQry1 = "SELECT * FROM ".TABLE_PREFIX."_employee WHERE status='t' AND is_Deleted='N' ORDER BY employee_Id";
$sql_Show1 = $DBObject->db_query($sqlQry1);
while($catArr = $DBObject->db_fetch_array($sql_Show1)){
?>
<div align="center"><br />
<option value="<?php echo $catArr['employee_Id'] ?>"><?php echo SafeOutput($catArr['first_Name']) ?> <?php echo SafeOutput($catArr['last_Name']) ?></option>
</div>
<?php
}
?>
</div>
</div>
</div>
<br />
<p>
</select>
<div id="salesrloc">
<select name="salesr_loc" id="salesr_loc" title="Sales Rep Loc" size="5" multiple="multiple">
<option value="">Select</option>
</select>
<br />
Javascript
<script language="javascript">
dv = document.createElement('div'); // create dynamically div tag
dv.setAttribute('id',"details");
function findLocation2(category)
{
dv.innerHTML='<div id="salesrloc" style="width:auto; height:200px;"><img src="image/loading.gif"></div> <br>';
var url11 = "salesrep2.php";
var qry11="?sales_rep=" + category ;
var result1='salesr_loc';
var ajaxRequest; // The variable that makes Ajax possible!
try{
ajaxRequest = new XMLHttpRequest();
} catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){ //alert(ajaxRequest.responseText);
var a=ajaxRequest.responseText;
try{
document.getElementById('salesr_loc').innerHTML=ajaxRequest.responseText;
}catch(e){
dv.innerHTML=ajaxRequest.responseText;
}
}
}
ajaxRequest.open("POST", url11+qry11, true);
ajaxRequest.send(null);
} </script>
and Finally populate listbox php
<?php
include("mastersecure.php");
$emp_id = $_GET['sales_rep'];
$qry= "select * FROM ".TABLE_PREFIX."_location ls, ".TABLE_PREFIX."_customer cs WHERE loc_Salesrep = ".$emp_id." AND ls.customer_Id = cs.customer_Id";
$res = $DBObject->db_query($qry);
?>
<body onLoad="document.getElementById('salesr_loc').focus();">
<select name="salesr_loc[]" id="salesr_loc" title="Sales Rep Loc" size="5" multiple="multiple">
<?php
while($row=$DBObject->db_fetch_array())
{
?>
<option value="<?=$row["location_Id"]?>"><?=$row["customer_Name"]?>, <?=$row["location_Name"]?></option>
<?php
}
?>
</select>
</body>
the IE does not support .innerHTML for < select> elements!!
<select name="salesr_loc" id="salesr_loc"
...
document.getElementById('salesr_loc').innerHTML=ajaxRequest.responseText;
instead, you must do it in a loop:
var d = document.getElementById('salesr_loc');
for(...) {
d.options[x] = new Option(..);
}

how to catch post variable when i post my submit form php ajax

I'm posting on this forum because I don't manage to received my information that I posted by my submit form into my showidz.php page. I don't know how to catch my $_POST["numversion"] which generated my ajax script in my docversion.php.
to sum up, I have a form page docversion.php where I enter the document name and I catch on the same page the "linked" versions which are possible for this document entered by using an ajax script. This works fine.
My problem is when I click on the submit to throw information from docversion.php to showidz.php I cannot catch the numversion.
Here's my source code :
docversion.php
<script type='text/javascript'>
function getXhr(){
var xhr = null;
if(window.XMLHttpRequest) // Firefox
xhr = new XMLHttpRequest();
else
if(window.ActiveXObject) { // Internet Explorer
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
}
else { // XMLHttpRequest non supporté par le navigateur
alert("Browser not compatible with XMLHTTPRequest...");
xhr = false;
}
return xhr;
}
/**
* catch on click
*/
function go(){
var xhr = getXhr();
// do when we have the answer
xhr.onreadystatechange = function(){
// do if the server answer is OK
if(xhr.readyState == 4 && xhr.status == 200){
leselect = xhr.responseText;
// use innerHTML
document.getElementById('numeroversion').innerHTML = leselect;
}
}
// post to rep_PhpAjax.php to have version
xhr.open("POST","rep_PhpAjax.php",true);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
sel = document.getElementById('course');
iddocument = sel.value;
xhr.send("idDoc="+iddocument);
}
</script>
<form name="test1" method="post" action="showidz.php" >
Nom du document <label>:</label><br>
<input type="text" name="course" id="course" size="40" onclick='go()'/><br/>
<label>Version</label>
<div id='numeroversion' style='display:inline'>
<select name='numeroversion'>
<option value='-1'>Choose a version</option>
</select>
</div>
<input type="submit" name="OK" value="OK">
</form>
rep_PhpAjax.php
<?php
echo "<select name='numeroversion'>";
if(isset($_POST["idDoc"])){
$res = mysql_query("SELECT `NumeroVersion`
FROM `version`, document
WHERE document.idversion = version.idversion
and document.NomDocument ='".$_POST["idDoc"]."'");
while($row = mysql_fetch_assoc($res)){
echo "<option value='".$row["idversion"]."'>".$row["NumeroVersion"]."</option>";
}
}
echo "</select>";
?>
showidz.php : The page with the problem where i cannot have the numeroversion which has been posted for docversion.php:
<?php
$docname = $_POST["course"];
$idversion = $_POST["numeroversion"];
echo "$docname</br>";
echo $idversion;
?>
Hope that someone could help me on my problem.
there seems to be nothing wrong with the form data that gets sent to showidz.php
but a problem might be the fact that you are calling that ajax on click. maybe you should chnage
onclick="go();"
to
onkeyup="go();"
in docversion.php at line 54 so that the ajax is called every time you type a letter
I rewrited what you want to do using jQuery. You can see it in action here.
Folder Structure:
site -+- displayDocument.php
|- ajaxGetVersions.php
|- ajaxGetVDocument.php
|- queries.php
displayDocument.php:
<?php
require_once 'queries.php';
$documents = getDocuments();
?>
<form id="myform" method="post" action="" >
<label for="documents">Choose a document</label>
<select id="documents" name='documents[]'>
<option value='0'>Choose a document</option>
<?php foreach ($documents as $document) : ?>
<option value='<?php echo $document ?>'><?php echo $document ?></option>
<?php endforeach; ?>
</select>
<br/>
<label for="versions">Version </label><span id="refreshVersions"></span>
<select id="versions" name='versions[]'>
</select>
<br/>
<input type="submit" name="OK" value="OK">
</form>
<div id="refreshDocument"></div>
<div id="document"></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
$("#documents").change(function() {
$("#refreshVersions").text("refreshing...");
$.post("ajaxGetVersions.php", { documentId: $(this).val() },
function(data) {
$("#versions").html(data);
$("#refreshVersions").text("");
});
});
$("#myform").submit(function(e) {
$("#refreshDocument").text("refreshing...");
$.post("ajaxGetDocument.php", { documentId: $("#documents").val(), version: $("#versions").val() },
function(data) {
$("#document").html(data);
$("#refreshDocument").text("");
});
e.preventDefault();
});
</script>
ajaxGetVersions:
<?php
require_once 'queries.php';
if (!isset($_POST['documentId'])) {
die('missing post parameter: documentId');
}
$versions = getVersionsOfDocument($_POST['documentId']);
?>
<?php foreach ($versions as $version): ?>
<option value='<?php echo $version ?>'><?php echo $version ?></option>
<?php endforeach; ?>
ajaxGetDocument:
if (!isset($_POST['documentId']) || !isset($_POST['version'])) {
die('missing post parameter: documentId or version');
}
$doc = getDocument($_POST['documentId'], $_POST['version']);
?>
<h1><?php echo $doc["documentId"] ?></h1>
<h2><?php echo $doc["version"] ?></h2>
<h3><?php echo $doc["author"] ?></h3>
<p>
<?php echo $doc["content"] ?>
</p>
queries.php:
<?php
// little database replace
$documents = array("Book1" => array("beta", "1.0", "1.1", "2.0"), "Book2" => array("1.0", "1.1"), "Book3" => array("beta"));
function getVersionsOfDocument($documentId) {
// replace with database fetch
global $documents;
return $documents[$documentId];
}
function getDocuments() {
// replace with database fetch
global $documents;
return array_keys($documents);
}
// get a document by id and version
function getDocument($documentId, $version) {
//implement your own
return array("documentId" => $documentId,
"version" => $version,
"author" => "...",
"content" => "bla bla");
}

Categories