Run AJAX PHP example in NetBeans - javascript

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

Related

Loading dynamic PHP echo in webpage without reloading the page

I have the PHP code where I get echo as my postgres database table fields I want to display these fields in my html and JavaScript based web application.for now I can load them in my webpage but I have to reload the webpage to get newly updated values. I want to get them automatically in a textbox without reloading application.i read that an ajax request would be helpful
given is the php code i am using with html to show case records but i have to reload page every time to get it updated
<?php
$host = "host = localhost";
$port = "port = 5432";
$dbname = "dbname = geoserver";
$credentials = "user = postgres password=password";
$db = pg_connect( "$host $port $dbname $credentials" );
$sql =<<<EOF
SELECT * from audit.logged_actions
ORDER BY action_tstamp_tx DESC
LIMIT 5;
EOF;
$ret = pg_query($db, $sql);
if(!$ret) {
echo pg_last_error($db);
exit;
}
while($row = pg_fetch_row($ret)) {
// echo "e = ". $row[1] . "\n";
echo "<input type='text' value='$row[14] '/>";
echo "<input type='text' value='$row[13] '/>";
}
echo "Operation done successfully\n";
pg_close($db);
?>
The problem is that after your browser renders the output of your php script, it is not connected to your php anymore. This is how HTTP works.
To be able to show the output without refreshing the whole page, you need to use javascript to make another HTTP request to your PHP script.
Something like this:
<?php
$host = "host = localhost";
$port = "port = 5432";
$dbname = "dbname = geoserver";
$credentials = "user = postgres password=password";
$db = pg_connect( "$host $port $dbname $credentials" );
$sql =<<<EOF
SELECT * from audit.logged_actions
ORDER BY action_tstamp_tx DESC
LIMIT 5;
EOF;
$ret = pg_query($db, $sql);
if(!$ret) {
echo pg_last_error($db);
exit;
}
?>
<div id='content'>
<?php while($row = pg_fetch_row($ret)) { ?>
<input type='text' value='<?= $row[14] ?>'/>
<input type='text' value='<?= $row[13] ?>'/>
<?php } ?>
Operation done successfully
<script>
(function() {
const secondsToRefresh = 5;
const Http = new XMLHttpRequest();
const url='#YOUR_PHP_SCRIPT_URL#';
setTimeout(function() {
Http.open("GET", url);
Http.send();
}, secondsToRefresh * 1000);
Http.onreadystatechange=(e)=>{
document.getElementById('data').innerHTML = Http.responseText;
}
})()
</script>
</div>";

JAVA SCRIPT var with Double Quotes to PHP and back for Auto fill

I have an HTML/PHP form that uses JAVA SCRIPT function to send (POST) an input content to a PHP code which performs a query and gets back to the JAVA SCRIPT function with data to Auto fill additional inputs in the form.
It all works great when the input content i send is plain text, even if there is a single quote in the content it works.
BUT, as soon as double quotes are included in the input content it fails to return the Auto fill results.
Appreciate your help with indicating where do i fail with passing the quotes.
Thanks
Just to make it clearer, the code works if customer name is "Intel" or "Int'el" , but it fails when customer name is "Int"el"
Here is the JAVA SCRIPT function that sends and receive the data from the PHP:
!--Script Auto fill ltd by customer -->
<script type="text/javascript">
function updatefrm() {
setTimeout(function(){
var customer = $('#customer').val();
if ($.trim(customer) !='') {
$.post('customerfill.php', {customer: customer}, function(data) {
$('#customerupdate').val(data['customer']);
$('#ltdupdate').val(data['ltd']);
});
}
}, 10);
}
</script>
Here is the PHP code that gets the POST data , performs the query, and sends back the array for the JAVA SCRIPT auto fill:
<?php
if (!empty($_POST['customer'])) {
$DB_Server = "localhost"; // MySQL Server
$DB_Username = "XXXX"; // MySQL Username
$DB_Password = "XXXX"; // MySQL Password
$DB_DBName = "XXXXXXXX"; // MySQL Database Name
$Connect = #mysql_connect($DB_Server, $DB_Username, $DB_Password) or die("Failed to connect to MySQL:<br />" . mysql_error() . "<br />" . mysql_errno());
// Select database
$Db = #mysql_select_db($DB_DBName, $Connect) or die("Failed to select database:<br />" . mysql_error(). "<br />" . mysql_errno());
mysql_query('SET NAMES utf8');
mysql_query('SET CHARACTER SET utf8');
$safe_name = mysql_real_escape_string(trim($_POST['customer']));
$query = mysql_query(" SELECT * FROM customers WHERE customer = '". $safe_name ."' LIMIT 1 ");
if (mysql_num_rows($query) > 0) {
$row = mysql_fetch_assoc($query);
json($row);
} else {
json(null);
}
}
function json ($array) {
header("Content-Type: application/json");
echo json_encode($array);
}
i think your js code is fine and i think error in your php code and in that line
$query = mysql_query(" SELECT * FROM customers WHERE customer = '". $safe_name ."' LIMIT 1 ");
so you should use PDO Prepared Statements for security and not face problem with double quote
$dsn = "mysql:host=localhost;dbname=your_database;charset=utf8mb4";
try {
$pdo = new PDO($dsn, "database_username", "database_password");
} catch (Exception $e) {
echo "no connection";
exit();
}
$stmt = $pdo->prepare("SELECT * FROM customers WHERE customer = :customer LIMIT 1");
$stmt->execute(array(":customer"=>$safe_name));
$row = $stmt->fetch();

Changing a PHP db_query parameter with AJAX

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).

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;

Send data from javascript to a mysql database

I have this little click counter. I would like to include each click in a mysql table. Can anybody help?
var count1 = 0;
function countClicks1() {
count1 = count1 + 1;
document.getElementById("p1").innerHTML = count1;
}
document.write('<p>');
document.write('Count');
document.write('</p>');
document.write('<p id="p1">0</p>');
Just in case anybody wants to see what I did:
var count1 = 0;
function countClicks1() {
count1 = count1 + 1;
document.getElementById("p1").innerHTML = count1;
}
function doAjax()
$.ajax({
type: "POST",
url: "phpfile.php",
data: "name=name&location=location",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
}
document.write('</p>');
document.write('Count');
document.write('</p>');
document.write('<p id="p1">0</p>');
This is phpfile.php which for testing purposes writes the data to a txt file
<?php
$name = $_POST['name'];
$location = $_POST['location'];
$myFile = "test.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $name);
fwrite($fh, $location);
fclose($fh);
?>
JavaScript, as defined in your question, can't directly work with MySql. This is because it isn't running on the same computer.
JavaScript runs on the client side (in the browser), and databases usually exist on the server side. You'll probably need to use an intermediate server-side language (like PHP, Java, .Net, or a server-side JavaScript stack like Node.js) to do the query.
Here's a tutorial on how to write some code that would bind PHP, JavaScript, and MySql together, with code running both in the browser, and on a server:
http://www.w3schools.com/php/php_ajax_database.asp
And here's the code from that page. It doesn't exactly match your scenario (it does a query, and doesn't store data in the DB), but it might help you start to understand the types of interactions you'll need in order to make this work.
In particular, pay attention to these bits of code from that article.
Bits of Javascript:
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
Bits of PHP code:
mysql_select_db("ajax_demo", $con);
$result = mysql_query($sql);
// ...
$row = mysql_fetch_array($result)
mysql_close($con);
Also, after you get a handle on how this sort of code works, I suggest you use the jQuery JavaScript library to do your AJAX calls. It is much cleaner and easier to deal with than the built-in AJAX support, and you won't have to write browser-specific code, as jQuery has cross-browser support built in. Here's the page for the jQuery AJAX API documentation.
The code from the article
HTML/Javascript code:
<html>
<head>
<script type="text/javascript">
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","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>
<br />
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>
PHP code:
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'peter', 'abc123');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ajax_demo", $con);
$sql="SELECT * FROM user WHERE id = '".$q."'";
$result = mysql_query($sql);
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
echo "<td>" . $row['Job'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
You will have to submit this data to the server somehow. I'm assuming that you don't want to do a full page reload every time a user clicks a link, so you'll have to user XHR (AJAX). If you are not using jQuery (or some other JS library) you can read this tutorial on how to do the XHR request "by hand".
The other posters are correct you cannot connect to MySQL directly from javascript.
This is because JavaScript is at client side & mysql is server side.
So your best bet is to use ajax to call a handler as quoted above if you can let us know what language your project is in we can better help you ie php/java/.net
If you project is using php then the example from Merlyn is a good place to start, I would personally use jquery.ajax() to cut down you code and have a better chance of less cross browser issues.
http://api.jquery.com/jQuery.ajax/

Categories

Resources