Ajax+PHP to implement cascading select - php

I have a demo.html page, which contains two selections, the first one is "Type", and the second one is "Config", when I choose a certain type in the first selection, I want to use ajax to update the values in the second selection.
For example, Type may have values: VM, Server, DCA
and VM only has config "singe node", but DCA has Config "d0"-"d48". so if I select DCA in the first selection, I should have 49 options in the second one.
I searched online and did find some solutions, then I wrote some code by myself. The problem now is that whatever I select in the first selection, the second one will not be updated, it always return null.
Not sure where the prob is, the code looks fine :( Thanks for any help.
demo page
<html>
<head>
<meta charset="utf-8">
<title>Reservation System</title>
<link href="jquery/ui/css/sunny/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css">
<link href="jquery/datatables/css/mrbs-page.css" rel="stylesheet" type="text/css">
<link href="jquery/datatables/css/mrbs-table.css" rel="stylesheet" type="text/css">
<link href="jquery/datatables/css/ColReorder.css" rel="stylesheet" type="text/css">
<link href="jquery/datatables/css/ColVis.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="css/mrbs.css.php" type="text/css">
<link rel="stylesheet" media="print" href="css/mrbs-print.css.php" type="text/css">
<meta name="robots" content="noindex">
<script type="text/javascript" src="jquery/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="jquery/ui/jquery-ui-1.8.22.custom.min.js"></script>
<script type="text/javascript" src="jquery/ui/jquery-ui-i18n.js"></script>
<script type="text/javascript" src="jquery/ui/jquery-ui-datepicker-en.js"></script>
<script type="text/javascript" src="jquery/ui/jquery-ui-datepicker-en-US.js"></script>
<script type="text/javascript" src="jquery/datatables/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="jquery/datatables/js/ColReorder.min.js"></script>
<script type="text/javascript">
var xmlhttp;
var url;
function createXMLHttpRequest() {
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
function showConfig(str) {
url = "getOptions.php?type="+str;
createXMLHttpRequest();
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
xmlhttp.onreadystatechange = function() {handleStateChange()};
}
function handleStateChange() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var str = xmlhttp.responseText;
alert (url);
createConfig(str);
}
}
function createConfig(str) {
var configs = str;
var config = configs.split(",");
while (document.getElementById("config").options.lengt>0)
document.getElementById("config").options.remove(0);
for (var i=0; i<config.length; i++)
{
var ooption = document.createElement("option");
ooption.value = config[i];
ooption.text = config[i];
document.getElementById("config").add(ooption);
}
}
</script>
<form id="add_room" class="form_admin" action="add.php" method="post">
<fieldset>
<legend>Add DCA</legend>
<input type="hidden" name="type" value="room">
<input type="hidden" name="area" value="2">
<div>
<label for="room_name">Name:</label>
<input type="text" id="room_name" name="name" maxlength="50">
</div>
<div>
<label for="room_description">Description:</label>
<input type="text" id="room_description" name="description" maxlength="100">
</div>
<div>
<label for="room_type">Type:</label>
<select class="room_area_select" id="type_select" name="area" onchange="showConfig(this.value)"><option value="VM">VM</option><option value="Server">Server</option><option value="DCA-V1">DCA-V1</option><option value="DCA-V2">DCA-V2</option></select>
</div>
<div>
<label for = "config">config:</label>
<select id="config" ></select>
</div>
</fieldset>
</form>
getOptions.php file
<?php
$type = $_GET['type'];
echo $type;
$result = "";
if ($type == "DCA-V1") {
for ($i=0;$i<47;$++)
$result .= $i.",";
$result .= "48";
}
else if ($type == "Server")
$result .= "single node";
else if ($type == "VM") {
$result .= "single host";
}
echo $result;
?>

As you are already using jQuery in your page, I suggest jQuery's ajax option.
Following should work. Update it accordingly.
getOptions.php
<?php
$type = $_GET['type'];
$result = "";
if ($type == "DCA-V1") {
for ($i=0;$i<47;$i++)
$result .= $i.",";
$result .= "48";
} else if ($type == "Server") {
$result .= "single node";
} else if ($type == "VM") {
$result .= "single host";
}
echo $result;
?>
Demo Page
<html>
<head>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#type_select').change(function() {
//Get current item's value
var type = $(this).val();
$.ajax({
url : "getOptions.php?type=" + type,
success : function(data) {
var result, opts = "";
//We get comma separated data
result = data.split(',');
//Prepare options
for(var i = 0; i < result.length; i++) {
opts += "<option value='" + result[i] + "'>" + result[i] + "</option>";
}
//Populate second select
$('#config').html(opts);
},
error : function() {
alert("Error");
}
});
});
//By default populate options for currently selected item
$('#type_select').trigger('change');
});
</script>
</head>
<body>
<form id="add_room" class="form_admin" action="add.php" method="post">
<fieldset>
<legend>Add DCA</legend>
<input type="hidden" name="type" value="room">
<input type="hidden" name="area" value="2">
<div>
<label for="room_name">Name:</label>
<input type="text" id="room_name" name="name" maxlength="50">
</div>
<div>
<label for="room_description">Description:</label>
<input type="text" id="room_description" name="description" maxlength="100">
</div>
<div>
<label for="room_type">Type:</label>
<select class="room_area_select" id="type_select" name="area">
<option value="VM">VM</option>
<option value="Server">Server</option>
<option value="DCA-V1">DCA-V1</option>
<option value="DCA-V2">DCA-V2</option>
</select>
</div>
<div>
<label for = "config">config:</label>
<select id="config" ></select>
</div>
</fieldset>
</form>
</body>
</html>
Tried providing some comments.
Let us know if you need any help.

Related

How to destroy/reset a session with a Form Button in PHP

I'm trying to destroy/reset my session so it cleans the Logs div I created when I press on the Reset Button in my Form. I have assigned a method to my button (btnReset) from a .js file that clears the entire page. Now I just want to make so that it just clears the Logs div where all my calculations are stored at. I have no idea what to do.
Any help would be super much appreciated. SESSIONS is still very new to me so I'm trying my best to understand it. If anyone can explain to me how to properly clear the Logs div after the Reset button has pressed to destroy/reset my session, that would be very much appreciated!
Index.php
<?php
session_start();
if (!isset($_SESSION['results'])) {
$_SESSION["results"] = [];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Meta Tags -->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Calculator++ with PHP">
<!-- Title -->
<title>Calculator ++ | Calculator</title>
<!-- Favicon -->
<link rel="icon" type="image/png" sizes="16x16" href="Images/favicon-16x16.png">
<link rel="icon" type="image/png" sizes="32x32" href="Images/favicon-32x32.png">
<!-- Stylesheets -->
<link rel="stylesheet" type="text/css" href="CSS/Style.css">
<!-- PHP Files -->
<?php include 'PHP/Calculation.php';?>
</head>
<body>
<!-- Selection for Calculator & Converter -->
<div class="selection">
<div class="titleSelect">Options</div>
<a class="btn-selection" href="Index.php">Calculator</a>
<a class="btn-selection" href="Converter.php">Converter</a>
</div>
<!-- Calculator Container -->
<div class="container">
<div class="result">
<!-- Prints the result -->
<div class="result"><?php echo $Result; ?></div>
</div>
<div class="calculator">
<form action="Index.php" method="POST">
<ul>
<!-- First number -->
<li>
<label for="numberOne"><strong>Number one:</strong></label>
<input class="inputNumbers" type="number" name="numberOne" placeholder="Enter a number">
</li>
<!-- Operation -->
<li>
<label for="operation"><strong>Operation:</strong></label>
<select class="inputNumbers" name="operation" id="operator-list">
<option value="+">+</option>
<option value="-">-</option>
<option value="x">x</option>
<option value="/">/</option>
<option value="sqrt">^</option>
<option value="pow">√</option>
</select>
</li>
<!-- Second number -->
<li id="second-input">
<label for="numberTwo"><strong>Number two:</strong></label>
<input class="inputNumbers" type="number" name="numberTwo" placeholder="Enter a number">
</li>
<!-- Decimal Slider -->
<li>
<label><strong>Decimal: </strong><span id="value_slider"></span></label>
<input type="range" name="slidebar" min="0" max="10" value="0" id="slider" class="slider_style input">
</li>
<!-- Calculate & Reset button -->
<li>
<input class="btn-calculate" type="submit" name="btnCalculate" value="Calculate">
<button class="btn-reset" type="reset" name="resetForm" onclick="btnReset();" value="resetButton">Reset</button>
</li>
</ul>
</form>
</div>
<!-- Logs -->
<div class="logs-container">
<div class="logs-title">Logs</div>
<div class="logs">
<?php echo implode("<br>",$_SESSION["results"]); ?>
</div>
</div>
</div>
<!-- JavaScript -->
<script type="text/javascript" src="JS/HideSecondInput.js"></script>
<script type="text/javascript" src="JS/Slider.js"></script>
<script type="text/javascript" src="JS/Reset.js"></script>
</body>
</html>
Calculation.php
<?php
$Result = 0;
if (isset ($_POST['btnCalculate']) ) {
$numberOne = $_POST['numberOne'];
$operation = $_POST['operation'];
$numberTwo = $_POST['numberTwo'];
if ($operation == '+') {
$Result = ((int)$numberOne + (int)$numberTwo);
$_SESSION["results"][]="$numberOne + $numberTwo = $Result";
}
else if ($operation == '-') {
$Result = ((int)$numberOne - (int)$numberTwo);
$_SESSION["results"][]="$numberOne - $numberTwo = $Result";
}
else if ($operation == 'x') {
$Result = ((int)$numberOne * (int)$numberTwo);
$_SESSION["results"][]="$numberOne * $numberTwo = $Result";
}
else if ($operation == '/') {
if ($numberOne and $numberTwo > 0)
{
$Result = $numberOne / $numberTwo;
$_SESSION["results"][]="$numberOne / $numberTwo = $Result";
} else {
echo "<script>alert('Cannot divide by 0');</script>";
}
}
else if ($operation == 'sqrt') {
$Result = sqrt($numberOne);
$_SESSION["results"][]="sqrt($numberOne) = $Result";
}
else if ($operation == 'pow') {
if ($numberOne and $numberTwo > 0)
{
$Result = pow($numberOne, $numberTwo);
$_SESSION["results"][]="pow($numberOne, $numberTwo) = $Result";
} else {
echo "<script>alert('Please enter a number in both fields');</script>";
}
}
else $Result = 'Unknown';
}
?>
Reset.js
//Resets the entire page when reset button is pressed
function btnReset() {
const xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", false);
xmlhttp.send();
window.parent.location = window.parent.location.href;
}
you basically need to adjust your code in the following way:
btnReset should send specific flag for session to be destoryed
btnReset should wait for the request to finish, then do the redirect.
on PHP, you should check for the flag, and if found, delete the session.
function btnReset(event) {
const xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", '/index.php?reset=true', true);
xmlhttp.onreadystatechange = function() { // Call a function when the state changes.
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
window.parent.location = window.parent.location.href;
}
}
xmlhttp.send();
}
and In PHP (calucations.php):
if(#$_GET['reset'] == true) {
$_SESSION["results"] = [];
session_destroy();
}
of course, this is simple way to do it, you should consider using jQuery https://jquery.com/ which would help you with the AJAX request, and also instead of doing a redirect, you can simple delete the content of the div containing the logs.
Note some typos in your code, file was called "Index.php" it should be case sensitive, so always call it: index.php

Why My Code didn't display Date (dd-M-yy format) in the input field after selected?

Below is my code.
Firstly, run the index.php Then there is a dropdown list will display and need to select a value from the dropdown. so far, dropdown will display value 1 or 2. If you select 2 it will display the value that has been selected together with the "date" field called from the display-date.php and from the "date" field, you may choose the date from calendar which called using datepicker plugin.
Now.. the problem is...I had select the date from calendar but the date selected didn't appear in the date input field. where am I wrong?
Hope anyone could help me please... :)
Thanks.
Here is index.php
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
</head>
<body>
<script>
function getData(str){
var xhr = false;
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
xhr = new XMLHttpRequest();
}
else {
// IE5/IE6
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xhr) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("results").innerHTML = xhr.responseText;
}
}
xhr.open("GET", "display-date.php?q="+str, true);
xhr.send(null);
}
}
</script>
<div>
<?php
echo '<select title="Select one" name="selectcat" onChange="getData(this.value)">';
echo '<option value="None">-- Select Option --</option>';
echo '<option value="1">One</option>';
echo '<option value="2">Two</option>';
echo '</select>';
?>
</div>
<br/><br/>
<p>You selected: <span id="results"></span></p>
</body>
</html>
Here is display-date.php
<?php
$Q = $_GET["q"];
echo $Q;
?>
<?php
if ($Q == '2'){
?>
<html>
<head>
<style>
#date_input{
text-indent: -500px;
height:25px;
width:200px;
}
</style>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>
<input id ="date_input" dateformat="dd-M-yy" type="date"/>
<span class="datepicker_label" style="pointer-events: none;"></span>
<script type="text/javascript">
$("#date_input").on("change", function () {
$(this).css("color", "rgba(0,0,0,0)").siblings(".datepicker_label").css({ "text-align":"center", position: "absolute",left: "10px",
top:"14px",width:$(this).width()}).text($(this).val().length == 0 ? "" :
($.datepicker.formatDate($(this).attr("dateformat"), new Date($(this).val()))));
});
</script>
</body>
</html>
<?php
}
?>
Modify the display-date.php . Html base structure is no longer needed.
<?php
$Q = $_GET["q"];
echo $Q;
?>
<?php
if ($Q == '2'){
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>
<input id ="date_input" dateformat="dd-M-yy" type="date"/>
<span class="datepicker_label" style="pointer-events: none;"></span>
<script type="text/javascript">
$("#date_input").on("change", function () {
$(this).css("color", "rgba(0,0,0,0)").siblings(".datepicker_label").css({ "text-align":"center", position: "absolute",left: "10px",
top:"14px",width:$(this).width()}).text($(this).val().length == 0 ? "" :
($.datepicker.formatDate($(this).attr("dateformat"), new Date($(this).val()))));
});
</script>
<?php
}
?>
There is no need to use ajax in your case, Ajax must not be used the way you showed in your question.
Ajax not used to draw html in DOM
No need to use ActiveXObject , It is insecure and I don't think we should support IE 5 or IE 6 anyways in modern development.
If you need to use ajax, Use JQuery's ajax function instead of XMLHttpRequest, As i see you are already using it.
Here is the code which works without ajax and works as it should be.
function getData(str){
$('.showInput').hide();
$('.showText').text('');
if(str != ""){
str = parseInt($.trim(str));
if(str == 2){
$('.showInput').show();
}else{
$('.showText').text(str);
}
}
}
$(document).ready(function(){
$("#date_input").datepicker({ dateFormat: 'dd-M-yy' });
});
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css">
</head>
<body>
<style>
.showInput{
display:none;
}
</style>
<div>
<select title="Select one" name="selectcat" onChange="getData(this.value)">
<option value="">-- Select Option --</option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
</div>
<br/><br/>
<p>You selected: <span id="results">
<span class="showText"></span>
<span class="showInput">
<input id="date_input" dateformat="dd-M-yy" type="text"/>
</span>
</p>
</body>
</html>

Retrieve and print data to textboxes from mysql DB using ajax

I have the following text fields:
<input type="text" name="empid" id="empid" tabindex="1" onblur="getname()">
<input type="text" name="name" id="name" tabindex="2"/>
<input type="text" name="city" id="name" tabindex="3"/>
<input type="text" name="state" id="name" tabindex="4"/>
and database table is:
empid name city state
EMP471 BBB bbbbb cccccc
EMP444 AAA xxxx yyyyyy
I'm new to php. I found some code on internet to retrieve data. but its not working.
Ajax code is:
function getname() {
var id=$("#id").val();
$.ajax({
type:"post",
dataType:"text",
data:"id="+id,
url:"getinsdata.php",
success:function(response)
{
$("#name").val(response.name);
$("#city").val(response.city);
$("#state").val(response.state);
}
});
}
and php code is
<?php
include 'connection.php';
$id=$_POST['id'];
$id=$_POST['id'];
$query=mysql_query("select name,city,state from ins_master where id=$id");
$result=mysql_fetch_row($query);
echo $result[0];
exit;
?>
when we select the empid then the respective name, city, state should be shown in textboxes when onblur event fires in PHP using AJAX.
What are you trying to achieve? Send the datas and get the response according to a query? Get some datas?
I'd go
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
</head>
<body>
<form id="test" method="POST">
<input type="text" id="name" required minlength="5" name="name"/>
<input type="password" id="pw" required name="pw"/>
<input id ="sub" type="submit"/>
</form>
<div id="answer"></div>
</body>
<script>
$("#sub").click(function(event){
event.preventDefault();
query = $.post({
url : 'check_ajax.php',
data : {'name': $('input[name=name]').val(), 'pw': $('#pw').val()},
});
query.done(function(response){
$('#answer').html(response);
});
});
</script>
This is check_ajax.php :
<?php
var_dump($_POST);
?>
in the second file but that's where you're supposed to do your query and insert/select
As people said we don't write code but give clues and since it's basics/fundamentals I can't help more cause you have to understand. Copy paste ain't a great idea
Try this html
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script type="text/javascript">
function getname(val) {
$.ajax({
url: 'getinsdata.php',
type: 'POST',
data: 'state_id='+val,
dataType: 'json',
success:function(data){
var len = data.length;
if(len > 0){
var id = data[0]['id'];
var name = data[0]['name'];
var city = data[0]['city'];
var state = data[0]['state'];
document.getElementById('name').value = name;
document.getElementById('city').value = city;
document.getElementById('state').value = state;
}
}
});
}
</script>
</head>
<body>
<form method="post">
<input type="text" name="empid" id="empid" tabindex="1" onblur="getname(this.value);">
<input type="text" name="name" id="name" tabindex="2"/>
<input type="text" name="city" id="city" tabindex="3"/>
<input type="text" name="state" id="state" tabindex="4"/>
</form>
</body>
</html>
and getinsdata.php is
<?php
include('connection.php');
$id = $_POST['state_id'];
$sql = "SELECT * FROM ins_master WHERE id='$id'";
$result = mysqli_query($conn,$sql);
$users_arr = array();
while( $row = mysqli_fetch_array($result) ){
$id = $row['id'];
$name = $row['name'];
$city = $row['city'];
$state = $row['state'];
$users_arr[] = array("id" => $id, "name" => $name, "city" => $city, "state" => $state);
}
// encoding array to json format
echo json_encode($users_arr);
exit;
?>
And your connection.php
<?php
$username = "";
$password = "";
$dbname = "";
$conn = mysqli_connect("localhost",$username,$password,$dbname);
if(!$conn){
die("Error in Connecation");
}
?>
put $dbname= your database name

Inserting comment to database using ajax

I know this has been mentioned many times in this thread but I still couldn't figure out how to solve my problem. I'm having difficulty on how to send and fetch my data from the comment.php to the insert.php
Here is my code for my comment.php:
(Notice the comments in javascript the method part [there's three of them], I've tried experimenting with them so that I could insert my data to the database but to no avail they didn't work. I'm still learning after all).Could someone help me. I'm still a beginner so I might find it difficult to understand an advance but i'll do my best.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax Comment</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
<link rel="stylesheet" type="text/css" href="bootstrap.min" />
<script type = "text/javascript" >
<!-- method 1-->
//$(document).ready( function() {
// $('#submit').click( function() {
//
// $('#getResponse').html('<img src="bootstrap/images /loading.gif">');
// $.post( 'insert.php', function(sendRequest) {
// var xmlhttp = new XMLHttpRequest();
// xmlhttp.onreadystatechange = function()
// (
// if(xmlhttp.onreadystatechange == 4 && xmlhttp.status == 200)
// (
// document.getElementbyId("getResponse").innerHTML = xmlhttp.responseText;
// )
// )
// xmlhttp.open("GET","insert.php?name="+document.getElementbyId("name").value+" &email="+document.getElementbyId("email").value+"&web="+document.getElementbyId("url").value+"& comment="+document.getElementbyId("body").value+,true);
// xmlhttp.send();
// $('#getResponse').html(sendRequest);
// });
// });
//});
<!-- -->
<!-- method 2-->
//function sendRequest() (
// var xmlhttp = new XMLHttpRequest();
// xmlhttp.onreadystatechange = function()
// (
// if(xmlhttp.onreadystatechange == 4 && xmlhttp.status == 200)
// (
// document.getElementbyId("getResponse").innerHTML = xmlhttp.responseText;
// )
// )
// xmlhttp.open("GET","insert.php?name="+document.getElementbyId("name").value+" &email="+document.getElementbyId("email").value+"& web="+document.getElementbyId("url").value+"& comment="+document.getElementbyId("body").value+,true);
// xmlhttp.send();
//)
<!-- -->
<!-- method 3-->
// function sendRequest()
//{
// var xmlhttp = new XMLHttpRequest();
// xmlhttp.open("GET","insert.php?name="+document.getElementbyId("name").value+" &email="+document.getElementbyId("email").value+"& web="+document.getElementbyId("url").value+"& comment="+document.getElementbyId("body").value+,false);
// xmlhttp.send(null);
// document.getElementbyId("getResponse").innerHTML = xmlhttp.responseText;
//}
<!-- -->
</script>
</head>
<body>
<form method = "post" action="">
<div id="main">
<div class="comment" style="display: block;">
<div class="avatar">
<img src="img/default_avatar.gif">
</div>
<div class="name">Avatar</div>
<div class="date" title="Added at 02:24 on 20 Feb 2015">20 Feb 2015</div>
<p>Avatar</p>
</div>
<div id="addCommentContainer">
<p>Add a Comment</p>
<form id="addCommentForm" method="Get" action="">
<div>
<label for="name">Your Name</label>
<input type="text" name="name" id="name">
<label for="email">Your Email</label>
<input type="text" name="email" id="email">
<label for="url">Website (not required)</label>
<input type="text" name="url" id="url">
<label for="body">Comment Body</label>
<textarea name="body" id="body" cols="20" rows="5"> </textarea>
<input type="submit" name="submit" id="submit" value="Submit" >
</div>
</form>
<div id = "getResponse"></div>
</div>
</div>
</form>
</body>
</html>
Here is my code for the insert.php my php file where I perform the insertion of data to my database.
<?php
mysql_connect("localhost","root");
mysql_select_db("comment");
$name = $_GET['name'];
$email = $_GET['email'];
$web = $_GET['web'];
$comment = $_GET['comment'];
mysql_query("INSERT INTO demo (c_name,c_email,c_web,c_comment) VALUES ('$name','$email','$web','$comment')");
echo "Inserted Successfully";
?>
In your comment.php file , use Button,not submit.
And on click event of that button , call jQuery ajax
$('#button_id').click(function(){
//Get values of input fields from DOM structure
var params,name,email,url,body;
name=$("#name").val();
email=$("#email").val();
url=$("#url").val();
body=$("#body").val();
params = {'name':name,'email':email,'web':url,'comment':body};
$.ajax({
url:'insert.php',
data:params,
success:function(){
alert("hello , your comment is added successfully , now play soccer :) !!");
}
});
});
Update
I dont know whether you used button or submit. So I am specifying for you.
<input type="button" name="submit" id="button_id" value="Submit" >
you can use this to submit the record to insert.php action in the form should be action = "insert.php"
$('form#addCommentForm').on('submit', function(){
$("#response").show();
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value ){
$('#response').html('<img src="images/loadingbar.gif"> loading...');
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
console.log(response);
$(".ajax")[0].reset();
$("#response").hide();
}
});
return false;
});
form the db connection script use this
<?php
$connect_error = 'sorry we\'re experiencing connection problems';
mysql_connect('localhost', 'root', '') or die($connect_error) ;
mysql_select_db('comment') or die($connect_error);
?>
you can also use the form serialize function, its good approach.
$('#addCommentForm').submit(function(form){
$.ajax({
url:'insert.php',
data: $(form).serialize(),
success:function(){
alert("hello , your comment is added successfully , now play soccer :) !!");
}
});
});

Phonegap ajax and php

I am new to jquery and phonegap and i am un able to find an answer to my question anywhere.
This is my index.html
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Auth Demo 2</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/latest/jquery.mobile.min.css" />
<script type="text/javascript" charset="utf-8" src="cordova-2.2.0.js"></script>
<script src="jquery.mobile/jquery-1.7.2.min.js"></script>
<script src="jquery.mobile/jquery.mobile-1.1.0.min.js"></script>
<script src="main.js"></script>
</head>
<body onload="init()">
<div id="launcherPage" data-role="page">
<!-- I'm just here waiting for deviceReady -->
</div>
<div id="loginPage" data-role="page">
<div data-role="header">
<h1>Auth Demo</h1>
</div>
<div data-role="content">
<form id="loginForm">
<div data-role="fieldcontain" class="ui-hide-label">
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="" placeholder="Username" />
</div>
<div data-role="fieldcontain" class="ui-hide-label">
<label for="password">Password:</label>
<input type="password" name="password" id="password" value="" placeholder="Password" />
</div>
<input type="submit" value="Login" id="submitButton">
</form>
</div>
<div data-role="footer">
<h4>© Camden Enterprises</h4>
</div>
</div>
</body>
</html>
And my Js.
function init() {
document.addEventListener("deviceready", deviceReady, true);
delete init;
}
function checkPreAuth() {
console.log("checkPreAuth");
var form = $("#loginForm");
if(window.localStorage["username"] != undefined && window.localStorage["password"] != undefined) {
$("#username", form).val(window.localStorage["username"]);
$("#password", form).val(window.localStorage["password"]);
handleLogin();
}
}
function handleLogin(){
var form = $("#loginForm");
var u = $("#username", form).val();
var p = $("#password", form).val();
//remove all the class add the messagebox classes and start fading
if(u != '' && p!= '') {
$.post("http://www.myaddress.com/loginlogin.php",{ user_name:$('#username', form).val(),password:$('#password', form).val(),rand:Math.random() } ,function(data)
{
if(data=='yes') //if correct login detail
{
//store
window.localStorage["username"] = u;
window.localStorage["password"] = p;
// $.mobile.changePage("some.html");
$.mobile.changePage( "some.html", { transition: "slideup"} );
}
else
{
navigator.notification.alert("Your login failed", function() {});
}
});
} else {
//Thanks Igor!
navigator.notification.alert("You must enter a username and password", function() {});
$("#submitButton").removeAttr("disabled");
}
return false;//not to post the form physically
}
function deviceReady() {
console.log("deviceReady");
$("#loginPage").on("pageinit",function() {
console.log("pageinit run");
$("#loginForm").on("submit",handleLogin);
checkPreAuth();
});
$.mobile.changePage("#loginPage");
}
Non of this is my own work but from here
http://www.raymondcamden.com/index.cfm/2011/11/10/Example-of-serverbased-login-with-PhoneGap
I changed the the example to work with php. This is very simple and only for testing purposes
php here
<?//get the posted values
require_once("backend/functions.php");
dbconn(true);
$username = $_POST['user_name'];
if ($username=='Steven'){
echo "yes";
}else{
echo "no";
}
?>
Now this all works and when the conditions are met the page some.html opens.
Now my question is .
How would i send the username of the logged in person to the page some.html?
once confirmed from the php file.
You should be able to access
window.localStorage["username"]
on your some.html page

Categories