Add a record to the database with XMLHttpRequest - javascript

I have the following form:
<form id="form" name="form">
<img id="close" src="images/3.png" onclick ="div_hide()">
<h2>Grade</h2>
<hr>
<input id="fn" name="fn" placeholder="Faculty number" type="number">
<select id="grade_type" name="grade_type">
<option value="test" selected="selected">Тест</option>
<option value="attendance">Attendance</option>
<option value="homework">Homework</option>
</select>
<input id="grade" name="grade" placeholder="Points" type="number">
Add record
</form>
When I click the submit button I want to add the points and the grade_type to the database. Therefore I am using JavaScript and PHP:
// Validating Empty Field
function check_empty() {
if (document.getElementById('grade').value == "") {
alert("Fill the fields!");
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
alert("xmlhttpreq");
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var grade = String(document.getElementById('grade').value);
var grade_type = document.getElementById('grade_type');
var grade_type_value = String(grade_type.options[grade_type.selectedIndex].value);
var fn = String(document.getElementById('fn').value);
xmlhttp.open("GET","getuser.php?grade="+grade+"grade_type="+grade_type_value+"fn="+fn,true);
xmlhttp.send();
document.getElementById('form').submit();
}
}
The contents of the getuser.php file are:
<?php
require "config.php";
$fn = $_GET["fn"];
$grade = $_GET["grade"];
$type = $_GET["grade_type"];
echo "<script type='text/javascript'>alert('$fn');</script>";
try {
$conn = new PDO("mysql:host=" . DB_SERVER . ";dbname=" . DB_NAME, DB_USERNAME, DB_PASSWORD);
}
catch(PDOException $e) {
die("Database connection could not be established.");
}
$sql = $conn->prepare("SELECT * FROM students WHERE fn = ?");
$sql->execute(array($fn));
if($sql->rowCount() > 0) {
$statement = $conn->prepare("INSERT INTO points (student_fn, type, grade, datetime)
VALUES (?, ?, ?, CURRENT_TIMESTAMP)");
$statement->execute(array($fn, $type, $grade));
}
else {
echo "<script type='text/javascript'>alert('No such fn');</script>";
}
$conn = null;
?>
However I think it never gets executed because I never see the result of the alert. I have never worked with XMLHttpRequest before so I don't even know whether my code is valid. I would greatly appreciate any help.

You can do this by using jquery.
$('#submit').click(function(){
$.ajax({
url: 'getuser.php',
type: 'GET',
data: $('#form1').serialize(),
success: function(result){
alert("Your data has been uploaded");
}
});
});
make sure that you need to add jquery file to your websitelike that

Related

How to get the selected value from dropdown list and past it to sql query

i have two dropdown list box,first one is sales area contain different kind of alphabet which get from cookie,second dropdown staff name is to change according to the selected value from first dropdown. How can i manage to pass the selected option value to my sql query so that it can be change according to the selected sales area.
This is the results that i want to get I insert my code to the snippet for easy to do edit and demonstration.
function fetch_select(val)
{
$.ajax({
type: 'post',
url: 'updateleave.php',
data: {
get_option:val
},
success: function (response) {
document.getElementById("slct2").innerHTML=response;
}
});
<table >
<tr>
<td> Sales Area
<select name="Area" id="area" >
<?php
$sarea = explode(",",$_COOKIE['cooAreaCode']);
foreach($sarea as $item){
?>
<option value="<?php echo strtolower($item); ?>"><?php echo $item; ?></option>
<?php
}
?>
</select >
</td>
<?
$var = $_POST['Area'];
$sql = "SELECT StaffName FROM tblStaff WHERE AreaCode= '$var'";
$rs = odbc_exec($link,$sql);
while ($row = odbc_fetch_array($rs)) {
$porr[] = $row;
}
odbc_free_result($rs);
odbc_close($link);
?>
<td> Staff Name
<select id="slct2">
?>
</select>
</td>
<label class="form_field">Your selected <span id="aggregator_name"></span></label>
(updateleave.php)
if (isset($_POST['get_option'])) {
$item=$_POST['get_option'];
$sql = "SELECT StaffName FROM tblStaff WHERE AreaCode= '$item'";
$rs = odbc_exec($link,$sql);
while ($row = odbc_fetch_array($rs)) {
$porr[] = $row;
}
for($i=0; $i < count($porr);$i++) {
echo "<option value="strtolower($porr[$i]['StaffName']);" >" .$porr[$i]['StaffName']."</option>";
odbc_free_result($rs);
odbc_close($link);
}
?>
Use append to add option tags with in select tag also do all the work in change event of the first drop down ("#area")
$(document).ready(function(){
$("#area").change(function()
{
var val =$(this).val();
$.ajax({
type: 'post',
url: 'updateleave.php',
data: {
get_option:val
},
success: function (response) {
$("#clct2").append(response);
}
});
});
});
I'm not a fan of jQuery, so you'll need to convert my Javascript to your needs, but what you need is to capture an onchange event for the first drop down and use it to dynamically process the SQL for the second dropdown.
<script>
document.getElementById('area').onclick = function(){
var xmlhttp;
var formData = new FormData();
formData.append('area_value', this.value);
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
alert(xmlhttp.responseText); // for DEBUGGING.
if(xmlhttp.responseText == 'false'){
alert(xmlhttp.responseText);
} else {
document.getElementById('slct2').innerHTML = xmlhttp.responseText;
}
}
}
xmlhttp.open("POST", 'build_slct2.php');
xmlhttp.send(formData);
xmlhttp.onerror = function () { console.error(xmlhttp.statusText); }
}
</script>
The build_slct2.php script would use $_POST['area_value'] to create the desired SQL query, process the query, and build the <option></option> list that will end up in the slct2 drop down. The build_slct2.php file would simply echo the new contents for slct2.

Send sql query parameters to function

TABLE wp_thesis TABLE wp_courses
Thesis_ID Thesis_Title Course_ID Thesis_ID Course
1 thesis1 1 1 course1
2 thesis2 2 1 course2
3 2 course1
4 2 course2
5 2 course3
I have a select that calls the showText function onchange.
$query = "SELECT * FROM wp_thesis";
$result = mysqli_query($conn,$query);?>
<select name="ThesisTitle" onchange="showText(x,y)" required="">
<option disabled='disabled' selected='selected' value=''></option>"; <?php
foreach ($result as $row)
{
echo "<option value= {$row[Thesis_ID]}>{$row[Thesis_Title]}</option>";
}
echo"</select><br />";?>
First thought was to send the value of the select (onchange="showText(this.value)") and then have an sql query inside showText function in order to get the two values i wanted. I read that you can't execute sql queries inside functions because Javascript is client-side, so I thought to do the sql query on php and then send the values to showText function. The query I want is this:
$query = "SELECT Course FROM wp_courses WHERE Thesis_ID={$row[Thesis_ID]} ";
$courses = mysqli_query($conn,$query);
$coursesNo = mysqli_num_rows($courses);
Tha values I want to send are $courses and $coursesNo. Is it possiple to get the value of select in the same php file, without using a button or anything like that?
Get X and Y co-ordinate before rendering option and provide it as data attribute.
<select name="ThesisTitle" onchange="showText(this)" required="">
<option disabled='disabled' selected='selected' value=''></option>"; <?php
foreach ($result as $row)
{
echo "<option data-x={$row[Thesis_X]} data-y={$row[Thesis_Y]} value= {$row[Thesis_ID]}>{$row[Thesis_Title]}</option>";
}
echo"</select><br />";?>
Just after that go to showText(this) function with this as parameter and get the attribute with
function showText(obj){
var x_val = $(obj).attr("data-x");
var y_val = $(obj).attr("data-y");
}
Hope this helps to you.
I finally found what I needed. I am posting the code.
<script language="javascript" type="text/javascript">
//Browser Support Code
function showCourses(str){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Problem with your browser!");
return false;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('courses'); // where it should be displayed
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value and pass it to server script.
var queryString = "?thesis_id=" + str ;
ajaxRequest.open("GET", "http://localhost/wordpress/get_thesis/" + queryString, true);
ajaxRequest.send(null);
}
From the select:
<select name="ThesisTitle" id="link_block" onchange="showCourses(this.value)" required="">
<option disabled='disabled' selected='selected' value=''></option>";<?php
foreach ($result as $row)
{
echo "<option value= {$row[Thesis_ID]}>{$row[Thesis_Title]}</option>";
}
echo"</select><br />";?>
I am sending the Thesis_ID to http://localhost/wordpress/get_thesis/ which is a php file that does the query I needed.

How to use AJAX to create/update radio buttons?

I currently have a setup where I use a PHP script to create a list of radio buttons by loading the required information from my database. This script is in the HTML structure rather than a separate file, so it requires a page refresh to update the list.
I'd like to figure out how to delete and reload the list upon pressing a button, the ID of which is 'btnDelete' (the actual deletion of items in the database is a separate point that I won't go into here). The current code that I have will delete the list of radio buttons, but when the next line is added, nothing happens (including list deletion).
PHP (delCom.php)
<?php
include_once('includes/conn.inc.php');
$query = ("SELECT comicID, comicName FROM comic WHERE username = '".$_SESSION['username']."'");
$result = mysqli_query($conn, $query);
while ($row = $result->fetch_assoc())
{
echo "<br><input name='comicList' id='".$row['comicID']."' type='radio' value='".$row['comicID']."'>".$row['comicName']." </option>";
}
?>
JavaScript
function delComic()
{
var ajaxRequest;
try
{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer Browsers
try
{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4)
{
$("#loadList").remove();
document.getElementById("divComics").innerHTML=xmlhttp.responseText;
}
}
ajaxRequest.open("GET", "delCom.php?t=", true);
ajaxRequest.send(null);
}
HTML
<div id="divComics">
<p><u>Uploaded Comics</u></p>
<!-- find comics in database -->
<div id="loadList">
<?php
include_once('includes/conn.inc.php');
$query = ("SELECT comicID, comicName FROM comic WHERE username = '".$_SESSION['username']."' ORDER BY comicName ASC");
$result = mysqli_query($conn, $query);
while ($row = $result->fetch_assoc())
{
echo "<br><input name='comicList' id='".$row['comicID']."' type='radio' value='".$row['comicID']."'>".$row['comicName']." </option>";
}
?>
</div>
<br>
<br>
<input type="button" onclick="delComic()" value="Delete Comic" name="deleteButton" id="btnDelete"/>
</div>
The code creates buttons correctly when run in the HTML, but not when in a separate php file.
Thanks in advance.
EDIT: Updated to fix a few misnamed things and to add the new line suggested. The loadList now empties but doesn't delete itself, as it should. The current problem is that the PHP file won't output the buttons again.
<?php
$username = $_GET['username'];
include_once('includes/conn.inc.php');
$query = ("SELECT comicID, comicName FROM comic WHERE username = '$username'");
$result = mysqli_query($conn, $query);
while ($row = $result->fetch_assoc())
{
echo "<br><input name='comicList' id='".$row['comicID']."' type='radio' value='".$row['comicID']."'>".$row['comicName']." </option>";
}
?>
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4)
{
document.getElementById('loadList').innerHTML="";
document.getElementById("divComics").innerHTML=xmlhttp.responseText;
}
}
ajaxRequest.open("GET", "delCom.php?username=MY_EXACT_NAME_I_KNOW_WORKS_HERE", true);
ajaxRequest.send(null);
There is no element with an id=comicList and you cannot remove it $("#comicList").remove(); in Javascript because it does not exist. Javascript is probably stopping execution at that point, and thereby not displaying your results from PHP.

jQuery XMLHttpRequest calling External PHP form not submiting

I recently had a friend who specializes in ladder logic and not web programming, come to me requesting help with a project from her employer. While I use more traditional coding languages, I am far from an expert in jquery and php myself. The problem that we are having is that a php page with a jquery / html form inserted into a parent page via XMLHttpRequest, is not executing its "post" action from the parent page. The thing that makes this problem more difficult is that when page is run by itself outside of the parent page (loaded directly into the browser), it executes its "post" action fine. I have done many hours of searching and trial and error at this point but am stumped and now come to you for help. Below are the relevant bits of code. Any help you could provide would be greatly appreciated as nothing we've tried seems to work when it comes to executing the submit of the form when it is inserted via XMLHttpRequest.
Javascript Code From Parent Page inserting external form:
function showUser(str)
{
if (str=="")
{
document.getElementById("insertUserHere").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp2=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp2.onreadystatechange=function()
{
if (xmlhttp2.readyState==4 && xmlhttp.status==200)
{
document.getElementById("insertUserHere").innerHTML=xmlhttp2.responseText;
}
}
xmlhttp2.open("GET","ajax-userForm.php?q="+str,true);
xmlhttp2.send();
}
Code of External PHP page Inserted By xhmlhttprequest (ajax-userForm.php):
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript">
// JQUERY: Plugin "autoSubmit"
(function($) {
$.fn.autoSubmit = function(options) {
return $.each(this, function() {
// VARIABLES: Input-specific
var input = $(this);
var column = input.attr('name');
// VARIABLES: Form-specific
var form = input.parents('form');
var method = form.attr('method');
var action = form.attr('action');
// VARIABLES: Where to update in database
var where_val = form.find('#where').val();
var where_col = form.find('#where').attr('name');
// ONBLUR: Dynamic value send through Ajax
input.bind('blur', function(event) {
// Get latest value
var value = input.val();
if (input.attr('type') == "checkbox")
{
if (input.attr('checked') )
{
value = 1;
}
else
{
value = 0;
}
}
// AJAX: Send values
$.ajax({
url: action,
type: method,
data: {
val: value,
col: column,
w_col: where_col,
w_val: where_val
},
cache: false,
timeout: 10000,
success: function(data) {
// Alert if update failed
if (data) {
alert(data);
}
// Load output into a P
else {
$('#notice').text('Updated');
$('#notice').fadeOut().fadeIn();
}
}
});
// Prevent normal submission of form
return false;
})
});
}
})(jQuery);
// JQUERY: Run .autoSubmit() on all INPUT fields within form
$(function(){
$('#ajax-userForm INPUT').autoSubmit();
});
</script>
<!-- STYLE -->
<style type="text/css">
INPUT { margin-right: 1em }
</style>
</head>
<body>
<!-- CONTENT -->
<?php
$q = intval($_GET['q']);
/*
* DATABASE CONNECTION
*/
// DATABASE: Connection variables
$db_host = "localhost";
$db_name = "DBNAME";
$db_username = "root";
$db_password = "DBPWD";
// DATABASE: Try to connect
if (!$db_connect = mysql_connect($db_host, $db_username, $db_password))
die('Unable to connect to MySQL from ajax-form.');
if (!$db_select = mysql_select_db($db_name, $db_connect))
die('Unable to select database');
/*
* DATABASE QUERY
*/
// DATABASE: Get current row
//$result = mysql_query("SELECT * FROM user");
$result = mysql_query("SELECT * FROM user where Project_ID = '".$q."' ");
$row = mysql_fetch_assoc($result);
?>
<form id="ajax-userForm" class="autosubmit" method="post" action="ajax-updateUser.php">
<fieldset>
<legend>Update user information</legend>
<label>First Name:</label>
<input name="FirstName" value="<?php echo $row['FirstName'] ?>" />
<label>Last Name:</label>
<input name="LastName" value="<?php echo $row['LastName'] ?>" />
<label>Hometown</label>
<input name="Hometown" value="<?php echo $row['Hometown'] ?>" />
<label>Married</label>
<input type = "checkbox" id = "chkMarried" name="Married" <?php echo $row['Married'] == 1 ? 'checked':'unchecked' ?>/>
<label>Employed</label>
<input type = "checkbox" id = "chkEmployed" name="Employed" <?php echo $row['Employed'] == 1 ? 'checked':'unchecked' ?> />
<input id="where" type="hidden" name="Project_ID" value="<?php echo $row['Project_ID'] ?>" />
</fieldset>
</form>
<p id="notice"></p>
</body>
</html>
Code for Page (ajax-updateUser.php) Called by "post" Action in Code Above (ajax-userForm.php):
/*
* DATABASE CONNECTION
*/
// DATABASE: Connection variables
$db_host = "localhost";
$db_name = "DBNAME";
$db_username = "root";
$db_password = "DBPWD";
// DATABASE: Try to connect
if (!$db_connect = mysql_connect($db_host, $db_username, $db_password))
die('Unable to connect to MySQL from ajax-update.');
if (!$db_select = mysql_select_db($db_name, $db_connect))
die('Unable to select database');
$message = "Connection Successful";
//echo "<script type='text/javascript'>alert('$message');</script>";
// DATABASE: Clean data before use
function clean($value)
{
return mysql_real_escape_string($value);
}
/*
* FORM PARSING
*/
// FORM: Variables were posted
if (count($_POST) > 0)
{
$message = count($_POST);
//echo "<script type='text/javascript'>alert('$message');</script>";
// Prepare form variables for database
foreach($_POST as $column => $value)
${$column} = clean($value);
// Perform MySQL UPDATE
$result = mysql_query("UPDATE user SET ".$col."='".$val."'
WHERE ".$w_col."='".$w_val."'")
or die ('Unable to update row.');
}
else
{
$message = "Nothing in Post";
echo "<script type='text/javascript'>alert('$message');</script>";
}
?>
Couple things:
Missing a close quote on your
DBPWD
Your check for status 200 uses:
xmlhttp // whereas the rest is xmlhttp2
My theory, without more context -
You're not using a var keyword when declaring:
xmlhttp2=new XMLHttpRequest();
Which means that the request is attached to the window like this: window.xmlhttp2 = ... - could you be accidentally modifying the same identifiers elsewhere on the "parent" page? That would explain a shared state error and why it works only in isolation (you would have no other code implicitly modding window.xmlhttp2)
You could also be doing bad things with:
xmlhttp2.open("GET","ajax-userForm.php?q="+str,true);
Since I don't know what this path means.
Another one could be, do you have CORS headers set for the request from the external domain?
Cheers,
Andrew

ajax call to populate form fields from database query when select value changes

I have been looking through the questions on here and cant find an exact answer to what i am after :( but i have managed to get something.
i have a form select field which i populate from a db query
<select style="width:100%;" class="quform-tooltip chosen-select" id="company_select" name="company_select" title="Company Select" onChange="showUser(this.value)">
<option value="">Please select</option>
<?php
$userID = $user->getUserID();
$query = $user->database->query("SELECT * FROM tbl_businesses as business LEFT JOIN tbl_user_businesses as biz_user ON business.businessID = biz_user.businessID WHERE biz_user.userID ='$userID'");
while($row=$user->database->fetchArray($query))
{
$bizID = $row['businessID'];
$bizName = $row['businessName'];
echo "<option value='$bizID'>$bizName</option>";
}?>
</select>
and then there are currently 2 other textboxes (might increase eventually) which i want to populate when the above select box value is changed/selected
<input id="company_name" type="text" name="company_name" value="" />
<input id="company_email" type="text" name="company_email" value="" />
so i have an onchange function on my select box which is this
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("company_name").innerHTML="";
return;
}
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)
{
var data = JSON.parse(xmlhttp.responseText);
for(var i=0;i<data.length;i++)
{
document.getElementById("company_name").innerHTML += data[i].id + ' - ' + data[i].name + ' - ' + data[i].web;
}
}
}
xmlhttp.open("GET","formdata.php?q="+str,true);
xmlhttp.send();
}
</script>
and my formdata.php file is like so
<?php
include("include/user.php");
$q = intval($_GET['q']);
$sql="SELECT * FROM tbl_businesses WHERE businessID = '".$q."'";
$result = $user->database->query($sql);
$info = array();
while($row=$user->database->fetchArray($result))
{
$cID = $row['bussinessID'];
$cName = $row['businessName'];
$cWeb = $row['businessWebsite'];
$info[] = array( 'id' => $cID, 'name' => $cName, 'web' => $cWeb );
}
echo json_encode($info);?>
which is making the ajax call correctly and returning the data expected but i now need help to populate the textbox values?
can anyone please help me with this, have literatly spent ages trying to figure it out, im not familiar with javascript/json so not sure where to begin
i want the company_name textbox value to be set to $cName; and
company_email textbox value to be set to $cWeb;
appreciate any help
Luke
ok the solution that i used, for anyone else wanting to know how i solved it is
my index.php which contains the javascript and the form code
javascript code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("company_name").value="";
return;
}
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)
{
var data = JSON.parse(xmlhttp.responseText);
for(var i=0;i<data.length;i++)
{
document.getElementById("company_name").value = data[i].name;
document.getElementById("company_email").value = data[i].web;
}
}
}
xmlhttp.open("GET","formdata.php?q="+str,true);
xmlhttp.send();
}
</script>
and the form code
<select style="width:100%;" class="quform-tooltip chosen-select" id="company_select" name="company_select" title="Company Select" onChange="showUser(this.value)">
<option value="">Please select</option>
<?php
$userID = $user->getUserID();
$query = $user->database->query("SELECT * FROM tbl_businesses as business LEFT JOIN tbl_user_businesses as biz_user ON business.businessID = biz_user.businessID WHERE biz_user.userID ='$userID'");
while($row=$user->database->fetchArray($query))
{
$bizID = $row['businessID'];
$bizName = $row['businessName'];
echo "<option value='$bizID'>$bizName</option>";
}?>
</select>
<input id="company_name" type="text" name="company_name" value="" />
<input id="company_email" type="text" name="company_name" value="" />
then my formdata.php
$q = intval($_GET['q']);
$sql="SELECT * FROM tbl_businesses WHERE businessID = '".$q."'";
$result = $user->database->query($sql);
$info = array();
while($row=$user->database->fetchArray($result))
{
$cID = $row['businessID'];
$cName = $row['businessName'];
$cWeb = $row['businessWebsite'];
$info[] = array( 'id' => $cID, 'name' => $cName, 'web' => $cWeb );
}
echo json_encode($info);?>
thats it, thanks to charlietfl for your help!
hope this helps someone :)
Here's an example with PHP and JQuery. If you are not familiar with JQuery, I suggest you take some time to digg into that before going on with your ajax, it's definitely gonna worth it. JQuery have methods like get and ajax to do async request to the server.
Now, heres some jquery we used to get JSON data from the server.
var title = '.....'
$.getJSON('getActivite.php?title=' + title, null,
function(data){
$("#currentId").val(data.ID);
$("#nomActivite").val(data.Nom);
$("#Description").val(data.Description);
$("#DateEvent").val(data.Date);
});
$("#currentId").val(data.ID); , this says : find the element with the id currentId in the DOM, and change it's value to the property ID of the data received from the ajax call.
On the PHP side, they had
<?php
header('Content-Type: application/json');
mysql_connect("localhost","root") or die (" NOPE . [" . mysql_error() . "]");
mysql_select_db("garderie");
$title = $_GET["title"]; // we received this from the json call
$query = " select a.ActiviteID as ActiviteID , rtrim(a.Nom) as Nom, a.Description from activites a inner join .....' ";
$result = mysql_query($query);
$ligne = mysql_fetch_array($result);
$data = array(
'ID' => $ligne["ActiviteID"],
'Nom' => $ligne["Nom"],
'Description' => $ligne["Description"],
'Date' => $date
);
mysql_close();
echo (json_encode($data));
?>

Categories