Changing a PHP db_query parameter with AJAX - javascript

Let's say I have this piece of code:
$templatesf = $DB->query('SELECT * FROM templates WHERE category="something"');
Is there a way to change that "something" using javascript/AJAX? For example:
function changesomething(selse){
if (selse == '1'){
something = 'this'
}else{
something = 'that'
}
}

The following will be your input page from where you'll call your ajax handler to process something.
<html>
<head>
<script language="javascript" type="text/javascript">
//Browser Support Code
function ajaxFunction(){
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("Your browser broke!");
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('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value from user and pass it to
// server script.
var somedata = document.getElementById('something').value;
var queryString = "?something=" + somedata ;
ajaxRequest.open("GET", "ajax-example.php" +
queryString, true);
ajaxRequest.send(null);
}
</script>
</head>
<body>
<form name='myForm'>
Something: <input type='text' id='something' /> <br />
<input type='button' onclick='ajaxFunction()'
value='Query MySQL'/>
</form>
<div id='ajaxDiv'>Your result will display here</div>
</body>
</html>
Below is the php code to handle your request and process your something
<?php
$dbhost = "localhost";
$dbuser = "dbusername";
$dbpass = "dbpassword";
$dbname = "dbname";
//Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
//Select Database
mysql_select_db($dbname) or die(mysql_error());
// Retrieve data from Query String
$something = $_GET['something'];
// Escape User Input to help prevent SQL Injection
$something = mysql_real_escape_string($something);
//build query
$query = "SELECT * FROM ajax_example WHERE something = '$something'";
$qry_result = mysql_query($query) or die(mysql_error());
//Build Result String
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>Name</th>";
$display_string .= "<th>something</th>";
$display_string .= "<th>other</th>";
$display_string .= "<th>blahblah</th>";
$display_string .= "</tr>";
// Insert a new row in the table for each person returned
while($row = mysql_fetch_array($qry_result)){
$display_string .= "<tr>";
$display_string .= "<td>$row[name]</td>";
$display_string .= "<td>$row[something]</td>";
$display_string .= "<td>$row[other]</td>";
$display_string .= "<td>$row[blahblah]</td>";
$display_string .= "</tr>";
}
echo "Query: " . $query . "<br />";
$display_string .= "</table>";
echo $display_string;
?>

You'll need to place a variable instead of that SOMETHING, and then pass an ajax variable to that method.
You'll catch the variable with a $_POST and place it instead of the variable you had previously.
You could also use a default(in case nothing was passed, or wrong type of POST was passed).

Related

Run AJAX PHP example in NetBeans

I found what looks like a decent introductory tutorial on AJAX using PHP and MYSQL and followed it to the letter - this is my first attempt at AJAX and PHP and I wish to run this in NetBeans but don't know how to get it running. How do I make this run in NetBeans? I have set the main file to ajax.html and attempted to run using the Green arrow but when the HTML page appears it does nothing when I enter valid data and click the "Query MySQL" button
Here us the ajax.html file
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
// Browser support code
function ajaxFunction(){
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 wrong in creating XMLHttpRequest
alert("Browser didn't create XMLHttpRequest");
return false;
}
}
}
// Now get the value from user and pass it to
// server script
var age = document.getElementById('age').value;
var wpm = document.getElementById('wpm').value;
var sex = document.getElementById('sex').value;
var queryString = "?age=" + age;
queryString += "&wpm=" + wpm +"&sex=" + sex;
ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
ajaxRequest.send(null);
}
// -->
</script>
<form name='myForm'>
<br />
Max Age: <input type='text' id='age' /> <br />
<br />
Max WPM: <input type='text' id='wpm' />
<br />
<br />
Sex: <select id='sex'>
<option value="m">m</option>
<option value="f">f</option>
</select>
<input type='button' onClick='ajaxFunction()' value='Query MySQL' />
</form>
<div id='ajaxDiv'>Your result will be displayed here</div>
</body>
</html>
Here is the ajax-example.php file. The MySQL on my machine appears to be "localhost3306" and using the port number 7777
<?php
$dbhost = "localhost3306:7777";
$dbuser = "root";
$dbpass = "password";
$dbname = "web_prof_tracker";
// Connect to MySQL server
mysql_connect($dbhost, $dbuser, $dbpass);
// Select database
mysql_select_db($dbname) or die(mysql_error);
// Retrieve the data from Query String
$age = $_GET['age'];
$sex = $_GET['sex'];
$wpm = $_GET['wpm'];
// Escape user input to help prevent SQL injection
$age = mysql_real_escape_string($age);
$sex = mysql_real_escape_string($sex);
$wpm = mysql_real_escape_string($wpm);
// Build query
$query = "SELECT * FROM ajax_example WHERE sex = '$sex'";
if(is_numeric($age))
$query .= " AND age <= $age";
if(is_numeric($wpm))
$query .= " AND wpm <= $wpm";
// Execute query
$qry_result = mysql_query($query) or die (mysql_error());
// Build result string
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>Name</th>";
$display_string .= "<th>Age</th>";
$display_string .= "<th>Sex</th>";
$display_string .= "<th>WPM</th>";
$display_string .= "</tr>";
// Insert a new row in the table for each person returned
while($row = mysql_fetch_array($sql_result)){
$display_string = "<tr>";
$display_string .= "<td>$row[name]</td>";
$display_string .= "<td>$row[age]</td>";
$display_string .= "<td>$row[sex]</td>";
$display_string .= "<td>$row[wpm]</td>";
$display_string .= "</tr>";
}
echo "Query: " . $query . "<br />";
$display_string .= "</table>";
echo $display_string;
?>
On the officially net beans website netbeans.org they do show a tutorial on how to run php projects using netbeans
This are the steps,
I will skip the configuration of php environment as you have mentioned that you do have apache and you used to run php projects.
On your netbeans this is what you need to do :
Start the IDE, switch to the Projects window, and choose File > New
Project. The Choose Project panel opens.
In the Categories list, choose PHP.
In the Projects area, choose PHP Application and click Next. The New
PHP Project > Name and Location panel opens.
Make sure your source folder is inside htdocs in your xampp.
Then click next and select Run As a local website then specify the project url
Then you have done your setup configuration
you need to then open the projects files then when you done choose run from the menu
Then your project will display on your default netbeans projects browser.
Hope this will help, Good luck
Source : https://netbeans.org/kb/docs/php/quickstart.html

Output of drop down list in php mysql

I want the output of "cor_resp_template" where is nome and select that values for in next page do some operations like(sum, multiplication,...). I try the first time use JavaScript, but i don´t know if the code is correct. I try to analysis step by step and seems ok for that operation.
In next picture like you see the empty values. Don´t show the table with the values for after submit that values for next page.
The output of database of the table template where is all the values:
That is the output of that page:
http://localhost/dissertacao/conceptualization13.php?menuId=1
After we have the code where we use the JavaScript for get the values in next page where is the PHP query.
<script>
function showUser(str) {
if (str == "") {
document.getElementById("$option").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 (this.readyState == 4 && this.status == 200) {
document.getElementById("$option").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","template1.php?option="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
<?php
echo "<select name='template' class='form-control' onchange='showUser(this.value)'>";
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("teste") or die(mysql_error()); // selecciona a database do server escolhido
echo "<center>";
// Get the county names from database - no duplicates
$query = "SELECT DISTINCT nome FROM template";
{
// execute the query, $result will hold all of the Counties in an array
$resultado = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($resultado))
$option .="<option>" . $row['nome'] . "</option>";
echo $option;
}
echo "</select>";
echo "<br>";
?>
<input type="submit" value="Submit">
</form>
<br>
<div id="valores"><b>Os valores para este template são:</b></div>
template1.php
The following code is the PHP QUERY where is called for give the output of the table with the values where is nome in the SQL table.
<?php
$option = (isset($_POST['nome']) ? $_POST['nome'] : '');
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("teste") or die(mysql_error()); // selecciona a database do server escolhido
$query="SELECT * FROM template WHERE 'nome' = '".$option."'";
$resultado = mysql_query($query) or die(mysql_error());
echo "<table>
<tr>
<th>Valores</th>
</tr>";
while($row = mysql_fetch_array($resultado)) {
var_dump ($resultado);
echo "<tr>";
echo "<td>" . $row['corp_resp_template'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>**

How to save data which is inside a table dynamically created using JavaScript to database

function create(x) {
var field=document.createElement('fieldset');
var t=document.createElement('table');
t.setAttribute("id","myTable");
document.body.appendChild(t);
field.appendChild(t);
document.body.appendChild(field);
var row=document.createElement('th');
newHeader = document.createElement("th");
newHeader.innerText = x;
row.appendChild(newHeader);
var row1=document.createElement('tr');
var col1=document.createElement('td');
var col2=document.createElement('td');
var row2=document.createElement('tr');
var col3=document.createElement('td');
var col4=document.createElement('td');
var row3=document.createElement('tr');
var col5=document.createElement('td');
var col6=document.createElement('td');
col1.innerHTML="Name";
col2.innerHTML="<input type='text' name='stateactivityname' size='40' required>";
row1.appendChild(col1);
row1.appendChild(col2);
col3.innerHTML="Registration Applicable";
col4.innerHTML="<select name='regapp' required><option></option><option>Yes</option><option>No</option></select>";
row2.appendChild(col3);
row2.appendChild(col4);
col5.innerHTML="Registers Applicable";
col6.innerHTML="<select name='registers' required><option></option><option>Yes</option><option>No</option></select>";
row3.appendChild(col5);
row3.appendChild(col6);
t.appendChild(row);
t.appendChild(row1);
t.appendChild(row2);
t.appendChild(row3);
addrow('myTable');
}
PHP code for storing data to database is:
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
$conn=new mysqli("localhost","root","","newcomplyindia");
if($conn->connect_errno){
echo("connection error");
}
$actname=$_POST["actname"];
$industry=$_POST['industrytype'];
$centralorstate=$_POST["cors"];
$sql="insert into acts (actname,centralorstate) value ('".$actname."','".$centralorstate."')";
$regapp=$_POST["regapp"];
if($regapp=='Yes'){
$regapp=true;
}
else{
$regapp=false;
}
$registers=$_POST["registers"];
if($registers=='Yes'){
$registers=true;
}
else{
$registers=false;
}
$sub=$_POST["sub"];
if($sub=='Yes'){
$sub=true;
}
else{
$sub=false;
}
if($conn->query($sql)==true){
echo 'act name added ';
}
$lastid=$conn->insert_id;
$sql1="insert into actsstate (actid,registrationrequired,registersapplicable,sublocation)"
. "values('$lastid','$regapp','$registers','$sub')";
if($conn->query($sql1)==true){
echo '<br>name and central/state added';
}
$stateactivity=$_POST["stateactivityname"];
$activityname=$_POST["activityname"];
$activitymonth=$_POST["month"];
$activitydate=$_POST["date"];
$sql2="insert into activity (name,actid,activityname,activitymonth,activitydate)"
. "values('$stateactivity','$lastid','$activityname','$activitymonth','$activitydate')";
if($conn->query($sql2)){
echo 'activity added';
}
else{
echo 'no record';
}
$conn->close();
?>
i have a javascript like this. The table is created dynamically. And i want to store the data inside this table to database. am using mysqli for database connection
Am new to javascript. Can anyone help me to do this
Here's a way using Vanilla JS (pure js)
var xhttp = new XMLHttpRequest();
var url = "save.php";
xhttp.open("POST", url, true);
// uncomment this if you're sending JSON
// xhttp.setRequestHeader("Content-type", "application/json");
xhttp.onreadystatechange = function() { // Call a function when the state changes.
if(xhttp.readyState == 4 && xhttp.status == 200) {
// the 4 & 200 are the responses that you will get when the call is successful
alert(xhttp.responseText);
}
}
xhttp.send('the data you want to send');
And here's a way to save to the database (mysql in my case) with Flat PHP (pure php)
$servername = "localhost";
$username = "db_username";
$password = "db_password";
$dbname = "db_name";
// connect to the DB
$conn = new mysqli($servername, $username, $password, $dbname);
// check if you're connected
if ($conn->connect_error) {
echo "Connection failed: " . $conn->connect_error;
}
else {
// echo "connecting to DB succeeded <br> ";
}
// uncomment the following if you're recieving json
// header("Content-Type: application/json");
// $array = json_decode(file_get_contents("php://input"), true);
$sql = "INSERT INTO table_name (columns,names) VALUES (columns,values)";
if ($conn->query($sql) === TRUE) {
echo "Data was saved successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
to learn more about the sql commands I suggest the w3schools tutorials
Of course you can by using AJAX:
$.post("php_script.php",{javascript variables}, function(result) {
alert(result);
});

Sending data back from php

I tried this tutorial to send/retrieve data from my mysql database, using ajax and php.
This is the ajax part:
<script>
function showUser(str) {
if (str=="") {
document.getElementById("txtHint").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) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","suchen_ma.php?id="+str,true);
xmlhttp.send();
}
</script>
The .php file looks like this:
<?php
//Connection Details
$username = 'root';
$password = '';
$hostname = 'localhost';
$databasename = 'plzdb';
$id = ($_GET['id']);
//Connection-string
$con = mysqli_connect($hostname,$username,$password,$databasename);
//SQL Query
$sql = "SELECT per_vorname,per_nachname from plz_person
WHERE per_id = $id";
$result = mysqli_query($con,$sql);
echo "<table border='0'>
<tr>
<th></th>
<th></th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['per_vorname'] . "</td>";
echo "<td>" . $row['per_nachname'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
The data is formatted within the php file, but I want to send the "raw" data back to the html and display it inside a list and format it with css. Unfortunately I have no idea how to do this
Just give back the data as JSON:
$sql = "SELECT per_vorname,per_nachname from plz_person
WHERE per_id = " . mysqli_real_escape_string($con, $id);
$result = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($result)) {
$persons[] = array(
"vorname" => $row['per_vorname'],
"per_nachname" => $row['per_nachname']
);
}
echo json_encode($persons);
and then create a loop in javascript, to build the HTML.
NOTE: Avoid sql injection by escaping your string.

why readyState is NOT equal to 4?

I have tried to learn how to receive data from database using ajax, and i have some problem...
the problem is when I submit the query I dont see any thing...
i know that the problem is because the readyState is NOT equal to 4...but why?
I have this code on the index.html file:
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
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("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.myForm.time.value = ajaxRequest.responseText;
}
}
var age = document.getElementById('age').value;
var wpm = document.getElementById('wpm').value;
var sex = document.getElementById('sex').value;
var queryString = "?age=" + age + "&wpm=" + wpm + "&sex=" + sex;
ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
<form name='myForm'>
Max Age: <input type='text' id='age' /> <br />
Max WPM: <input type='text' id='wpm' />
<br />
Sex: <select id='sex'>
<option>m</option>
<option>f</option>
</select>
<input type='button' onclick='ajaxFunction()' value='Query MySQL' />
</form>
and this code on the ajax-example.php file:
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "*************";
$dbname = "*************";
//Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
//Select Database
mysql_select_db($dbname) or die(mysql_error());
// Retrieve data from Query String
$age = $_GET['age'];
$sex = $_GET['sex'];
$wpm = $_GET['wpm'];
// Escape User Input to help prevent SQL Injection
$age = mysql_real_escape_string($age);
$sex = mysql_real_escape_string($sex);
$wpm = mysql_real_escape_string($wpm);
//build query
$query = "SELECT * FROM ajax_example WHERE ae_sex = '$sex'";
if(is_numeric($age))
$query .= " AND ae_age <= $age";
if(is_numeric($wpm))
$query .= " AND ae_wpm <= $wpm";
//Execute query
$qry_result = mysql_query($query) or die(mysql_error());
//Build Result String
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>Name</th>";
$display_string .= "<th>Age</th>";
$display_string .= "<th>Sex</th>";
$display_string .= "<th>WPM</th>";
$display_string .= "</tr>";
// Insert a new row in the table for each person returned
while($row = mysql_fetch_array($qry_result)){
$display_string .= "<tr>";
$display_string .= "<td>$row[ae_name]</td>";
$display_string .= "<td>$row[ae_age]</td>";
$display_string .= "<td>$row[ae_sex]</td>";
$display_string .= "<td>$row[ae_wpm]</td>";
$display_string .= "</tr>";
}
echo "Query: " . $query . "<br />";
$display_string .= "</table>";
echo $display_string;
?>
The order of operations must be:
Create AJAX object
Open a connection
Set readystatechange handler
Send request.
You have items 2 and 3 in the wrong order, so the event handler is being cleared and is never called.
EDIT: It should also be noted that new XMLHttpRequest has been fully cross-browser since 2007, with the release of IE7. You don't need to use those ActiveXObjects now.
It looks like one of two things:
localhost is being used as the domain; it should be 127.0.0.1
ajax-example.php is running on localhost, but the associated HTML file is not
var queryString = "?age=" + age + "&wpm=" + wpm + "&sex=" + sex;
you should use double and(&&)
try it
var queryString = "?age=" + age + "&&wpm=" + wpm + "&&sex=" + sex;

Categories

Resources