Need help submitting my form data into database - php

OK, let me start off by saying im an amateur, so all your help is really appreciated.
OK, I have a form, called 'skills.php' and on this form, you enter the following fields 'Skills_ID, Employee_ID, First_name, Last_name and Skill'. I have used java so when you select employee_ID, the name fields change to what employee that is (linked to employee table).
HOWEVER, since i have added this function, i can not save my form data into my database. Maby i accidently deleted a line of code when implementing the java function. Can someone help me figure it out? below is my form 'Skill.php':
<html>
<?php
// Connecting to database
$pdo = new PDO("mysql:host=localhost;dbname=hrmwaitrose;charset=utf8", "root", "");
?>
<html>
<head>
<link type="text/css" rel="stylesheet" href="style.css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <!-- Online Jquery -->
<title>Skill</title>
</head>
<body>
<div id="content">
<h1 align="center">Add Employee Skill</h1>
<form action="insertskill.php" method="post">
<div>
<p>
Skill ID:
<input type="text" name="Training_ID">
</p>
<p>
Employee ID:
<select id="Employee_ID">
<option value="">Select one</option>
<?php
$st = $pdo->prepare("SELECT Employee_ID FROM Employee");
$st->execute();
$rows = $st->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
?><option value="<?php echo $row ['Employee_ID']; ?>"><?php echo $row ['Employee_ID']; ?></option><?php
}
?>
</select>
<p>
First name:
<input type="text" name="First_name" id="First_name">
</p>
<p>
Last name:
<input type="text" name="Last_name" id="Last_name">
</p>
<p>
<p>Skill: <select name="Skill">
<option value="">Select...</option>
<option value="Checkouts">Checkouts</option>
<option value="Fresh goods">Fresh goods</option>
<option value="Dry goods">Dry goods</option>
<option value="Fruit & Veg">Fruit & Veg</option>
<option value="Operations">Operations</option>
</select>
</p>
<input type="submit">
<INPUT Type="BUTTON" VALUE="Back" ONCLICK="window.location.href='index.html'">
</form>
</div>
<script type="text/javascript">
$(function() { // This code will be executed when DOM is ready
$('#Employee_ID').change(function() {
var $self = $(this); // jQuery object with the select inside
$.post("insertskill.php", { Employee_ID : $self.val()}, function(json) {
if (json && json.status) {
$('#First_name').val(json.name);
$('#Last_name').val(json.lastname);
}
})
});
})
</script>
</body>
</html>
And here is the code used when the submit button is pressed 'insertskill.php':
<?php
$pdo = new PDO("mysql:host=localhost;dbname=hrmwaitrose;charset=utf8", "root", "");
header("Content-Type:application/json; Charset=utf-8");
$st = $pdo->prepare("SELECT First_name, Last_name FROM Employee WHERE Employee_ID = :employee_id");
$st->execute(array ('employee_id' => $_POST['Employee_ID']));
$data = $st->fetch(PDO::FETCH_ASSOC);
echo json_encode(array ('status' => true, 'name' => $data ['First_name'], 'lastname' => $data ['Last_name']));
?>
Just by looking at this code imn pretty sure i might of accidently deleted the coding to insert it into database, HOWEVER i dont know how to fix it :( can someone help? much appreciated! Thanks in advance

in "insertskill.php" line 6:
$st = $pdo->prepare("SELECT First_name, Last_name FROM Employee WHERE Employee_ID = :employee_id");
You're performing a SELECT query (read), sounds to me more like you wanted an INSERT query (write).
An INSERT statement in your case would be something similar to:
$st = $pdo->prepare("INSERT INTO Employee (Training_Id,Employee_Id,First_Name,Last_Name,Skill) VALUES (:training_id,:employee_id,:first_name,:last_name,:skill)")
$st->execute(array(':training_id' => $training_id, ':employee_id' => ...));

First, watch out. Java is not JavaScript!
And you're right, you removed the INSERT lines. There are several articles on the web about how to do that. Here is one. Just google PDO Insert for more results.
You should put these INSERT commands in your insertskill.php file and create another one, maybe fetchName.php or something like that, with the code that you presented to return first and last name for an employee based on its id, and use that in your JavaScript $.change() function. It doesn't make sense for a file called insertskill.php to fetch data.
And your forgot to specify that you're expecting a JSON in your $.post() command. Do that instead:
$.post("insertskill.php", { Employee_ID : $self.val()}, function(json) {
if (json && json.status) {
$('#First_name').val(json.name);
$('#Last_name').val(json.lastname);
}
}, 'json'); // Here!

First thing to say is that you are NOT using Java. You are using JavaScript (actually ECMAScript which is VERY VERY different from Java.
Next, you are correct, that there is now no INSERT statement there at all, you will need to write one to insert whatever data you want to insert.
HOWEVER, you also need to somehow tell the difference between when insertskill.php is called for an Ajax request (to get the names for the form) and when it is called to insert the data. So on your Javascript (jQuery I guess) request, you could change the url to:
$.post("insertskill.php?ajax"
and then in insertskill.php do:
if(isset($_GET['ajax'])) {
header("Content-Type:application/json; Charset=utf-8");
$st = $pdo->prepare("SELECT First_name, Last_name FROM Employee WHERE Employee_ID = :employee_id");
$st->execute(array ('employee_id' => $_POST['Employee_ID']));
$data = $st->fetch(PDO::FETCH_ASSOC);
echo json_encode(array ('status' => true, 'name' => $data ['First_name'], 'lastname' => $data ['Last_name']));
}
else {
// Do the insert statement stuff...
}

Related

Display Data from a dependent dropdown in php

i need help, i'm new to php and jquery
i created a two tier dependent dropdown list populated from mysql database,which uses two tables products and fieldo with pid as the foreign key.
//code for dropdown.php
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
</head><?php include "connectdb.php"; ?>
<script>
function getState(val) {
$.ajax({
type: "POST",
url: "states.php",
data:'pid='+val,
success: function(data){
$("#state-list").html(data);
}
});
}
function showMsg()
{
$("#msgC").html($("SELECT name, email from fieldo where state = '#state-list option:selected'").text());
return false;
}
</script>
<body >
<form>
<label style="font-size:20px" >Products:</label>
<select name="product" id="product-list" class="demoInputBox" onChange="getState(this.value);">
<option value="">Select Products</option>
<?php
$sql="SELECT * FROM `Products` WHERE TYPE = 'BULK'";
$results=$dbhandle->query($sql);
while($rs=$results->fetch_assoc()) {
?>
<option value="<?php echo $rs["pid"]; ?>"><?php echo $rs["Name"]; ?></option>
<?php
}
?>
</select>
<label style="font-size:20px" >State:</label>
<select id="state-list" name="state" >
<option value="">Select State</option>
</select>
<button value="submit" onclick="return showMsg()">Submit</button>
</form>
Result: <span id="msgC"></span><br>
</body>
</html>
//code for states.php
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<script type="text/javascript">//alert("sdfsd");</script>
<body>
<?php
require_once("connectdb.php");
//$db_handle = new DBController();
$query ="SELECT oid,state FROM fieldo WHERE pid = '".$_POST["pid"]."'";
$results = $dbhandle->query($query);
?>
<option>Select State</option>
<?php
while($rs=$results->fetch_assoc()) {
?>
<option value="<?php echo $rs["oid"]; ?>"><?php echo $rs["state"]; ?></option>
<?php
}
?>
</body>
</html>
this list is working correctly but i want to display the other columns of stated (email , name and contact) upon selection of the state.
its not working
Have you tried running the while loop without breaking the PHP script? It seems you are almost trying to run a for loop.
<?php
$sql="SELECT * FROM `Products` WHERE TYPE = 'BULK'";
$results=$dbhandle->query($sql);
while($rs=$results->fetch_assoc()) {
echo '<option value="' . $rs["pid"] . '">' . $rs["Name"] . '</option>';
}
?>
UPDATE
Okay, so I heard your comment, and I have used an ajax call to get the full display of the content; I was not really sure as to what you were trying to do with your showMsg() function. I was assuming you were wanting to create a new query request.
So I changed the function to create an Ajax call that would look something along these lines:
<script>
function showMsg()
{
var val;
val = $("#state-list").val();
$.ajax({
type: "POST",
url: "table.php",
data: "state_id="+val,
success: function(data){
$("#msgC").html(data);
}
});
}
</script>
And then table.php would be along these lines...
<?php
// check to see if state_id has been submitted
if(isset($_POST['state_id']))
{
$state_id = $_POST['state_id'];
}
// if it is not set, add something in place.
else
{
$state_id = "1";
}
// query goes here - ask for the ID
$query = "SELECT name, email from fieldo where state = " . $state_id;
$results = $dbhandle->query($query);
while($rs=$results->fetch_assoc()) {
//... create table with all content;
}
?>
PHP cannot react to what is happening in the browser. Once PHP has processed the page and the web server has sent it to the browser, JavaScript takes over.
This means that if a customer selects a new state, it will not automatically get PHP to populate the rest of the page with the matching email, name and contact. You need to change your approach a bit.
One approach is to use Ajax. It would work like so:
In jQuery, register an onChange event handler for the states dropdown.
When customer selects a new state, the event handler will be triggered. Within the handler, make an Ajax request that sends the PHP the selected state.
the PHP document that receives the request would query for the matching email, name and contact from the DB and send the results, perhaps as a JSON
Back in the jQuery handler, when data comes back from the PHP server (in the response callback), use that data to populate the page with the right email, name and contact.
An alternative, even simpler approach (if you don't have a lot of data) is to have PHP send all data at once in a multi-dimensional array when the page loads. This time when the user selects a new state, the jQuery event handler will look up the data under that state within the big array, and fill the form with the data.

Show price from DB

The user goes change the nm_peca, will select tipo_preco and then find the price in MySQL database to complete the textbox vlr_peca.
What do I need to do to get the value of products?
<?php>
$query = mysql_query("SELECT id, nm_peca, vlr_original,
vlr_paralelo, fabricante
FROM peca
ORDER BY nm_peca");
<select id="nm_peca" name="nm_peca"
title="Selecione um status."
class="form-control" size="1">
<option value="">Status</option>
<option value="N/A">N/A</option>
<option value="S">S - Substituir</option>
</select>
</div>
</div>
<select id="tipo_preco" name="tipo_preco"
class="form-control" size="1">
<option value="">Tipo</option>
<option value="Peça Original">Original</option>
<option value="Peça Paralela">Paralela</option>
</select>
</div>
</div>
<div class="col-md-1">
<div class="input-group btn-group">
<input type="text" value="????????" name="vlr_peca"
class="form-control" readonly>
</div>
</div>
Well your code is a little confusing because what you really want is not clear to me, maybe it doesn't help that it's in a different language. What is the $query for? You are not using this in the code, so you'll need to do this to access it:
$rows = array();
while ($row = mysql_fetch_assoc($query)) {
$rows[] = $row;
}
print '<pre>'. print_r($rows, true) . '</pre>';
Then you'll need to use an ajax request OR setup javascript vars on the front end to make changes. I'm just going to go ahead and use the latter since it's more illustrative.
So I would add the cdn of jQuery which is https://code.jquery.com/jquery-2.1.4.min.js to the top of your file in a tag like:
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
Then you'll need to add an input id to that input tag like <input id="dynamic-variable" type="text" value="????????" name="vlr_peca"> and then use something like:
<script type="text/javascript">
$(document).ready(function() {
$('#tipo_preco').change(function() {
if ($(this).val() == 'Peça Original') {
$('#dynamic-variable').val('$5,000,000,000.00');
} else if ($(this).val() == 'Peça Paralela') {
$('#dynamic-variable').val('$300 billion trillion dollars');
} else {
$('#dynamic-variable').val('Bro. Choose one.');
}
});
});
</script>
I'm not going to program this whole thing for you since I don't know what kind of data you are getting from your DB, but this should be good enough to get you started. You need to be able to access the data in the mysql query, and you may just want to use the <?= $db_variable ?> or <?php echo $db_variable?> in your javascript where I have the amount variables. This should be good enough to get you started. Read up on php mysql_query and jQuery
AJAX
If you were to do this via AJAX, you would need a second page that accesses the database, you'd have to $_GET or $_POST variables and then print back the amount.
So your JavaScript would be something like this:
$.get('/the/page.php?tipo_preco=' + $('#tipo_preco').val(), function(response) {
if (response != '') {
$('#dynamic-variable').val(response);
}
});
And your second page would be something like this:
<?php
// code that sets up the database
// .... //
// now your code
$selected_value = $_GET['tipo_preco'];
$result = mysql_query("SELECT price FROM table WHERE column_val = '" . mysql_real_escape_string($selected_value) . "'");
$row = mysql_fetch_assoc($result); // assuming you're only fetching one row
print $row['price'];
?>
I would suggest you just go with the first suggestion, it's faster, less moving parts.

Implementing AJAX into a PHP page with multiple selections

very new coder here.
I have a page with four select inputs each with two possible options, and when all of the selections have a value and a submit button is clicked a certain song (1 of 16 based on the selections made) will echo out into an audioplayer.
In its current state I have been able to connect to my database which echos out the links and titles for the audio tracks.
My issue is that I want all of the selections to visually retain their option values once the submit button is clicked so that users can see what options they have selected for the current song that is playing.
I've found lots of examples online of implementing AJAX into a page with one selection that activates via an onchange event such as this one from W3 Schools http://www.w3schools.com/php/php_ajax_database.asp, but nothing with multiple selections and a submit button.
Someone from this community helped me out the other day so that the code for the W3 schools example could accommodate a submit button onclick event instead of the onchange on the select input, but with my lack of much fluency with PHP/Javascript I don't really have an idea of how to include multiple selections.
I was hoping someone could take a look at how far I got in my page with multiple selections but no AJAX implemented and explain to me in very simple terms how I could go about including AJAX so that the select options are visible once the submit button has been clicked. If one could even show me a version of my page with AJAX placed with comments to explain the process would be absolutely golden.
Here is my page...
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="styles.css">
<link rel="shortcut icon" href="favicon.ico"/>
<title>MoodTunes -- Tunes for your mood</title>
<script src="prefixfree.min.js"></script>
</head>
<body>
<?php
$myDatabase = mysql_connect("localhost","root","root");
if (!myDatabase) die ('Oh dear.' . mysql_error());
if(isset($_GET['submit'])){
mysql_select_db("tunes",$myDatabase);
$volume = $_GET['volume'];
$tempo = $_GET['tempo'];
$complexity = $_GET['complexity'];
$key = $_GET['key'];
$query = "SELECT * FROM music WHERE volumeOption='".$volume."' AND tempoOption='".$tempo."' AND complexityOption='".$complexity."' AND keySignatureOption='".$key."'";
$mydata = mysql_query($query, $myDatabase) or die(mysql_error());
while($row = mysql_fetch_array($mydata)){
echo "<div id='submitContent'>";
echo "<h3><span>Now Playing:</span> " . $row['title'] . "</h3>";
echo "<figure id='audioplayer' style='display:inline-block;'>";
echo "<audio id='audiotrack' controls loop>";
echo "<source src='" . $row['link'] . "'type='audio/mpeg'>";
echo "</audio>";
echo "</figure>";
}
mysql_close($myDatabase);
}
?>
</div>
<header>
<div>
<h1>
<img src="assets/images/logo.png" alt="">
</h1>
<h2>Tunes for <span>your</span> mood</h2>
</div>
</header>
<main>
<h4>Choose your tune criteria</h4>
<form>
<label for="volume"></label>
<select name="volume" id="volume">
<option>Select One</option>
<option value="0" id="loud">heavy</option>
<option value="1" id="quiet">soft</option>
</select>
</label>
<label for="tempo"></label>
<select name="tempo" id="tempo">
<option>Select One</option>
<option value="0" id="fast">fast</option>
<option value="1" id="slow">slow</option>
</select>
</label>
<label for="complexity"></label>
<select name="complexity" id="complexity">
<option>Select One</option>
<option value="0" id="complex">complex</option>
<option value="1" id="simple">simple</option>
</select>
</label>
<label for="key"></label>
<select name="key" id="key">
<option>Select One</option>
<option value="0" id="minor">minor key</option>
<option value="1" id="major">major key</option>
</select>
</label>
<div id="submitDiv">
<input type="submit" name="submit" id="submit" value="Get My Tune!">
</div>
</form>
</main>
</body>
</html>
Any help would be greatly appreciated. Like I said, I'm still very new to much coding so please answer simply if you can help me out. Thanks.
I suggest splitting into 2 files: an HTML file and a PHP file. Keep the PHP separate and call it with an XHR object (Ajax).
music.html
<!-- skipped top stuff -->
<body>
<!-- replace your PHP code with straight HTML -->
<div id='submitContent'>
<h3><span>Now Playing:</span> <span id="musictitle"></span></h3>
<figure id='audioplayer' style='display:inline-block;'>
<audio id='audiotrack' controls loop>
<source id="musiclink" src='' type='audio/mpeg'>
</audio>
</figure>
</div>
<!-- skipped middle stuff -->
<form id="musicform"> <!-- give your form an id -->
<!-- skipped form stuff -->
</form>
<!-- add script tag to bottom of body -->
<script>
// function to handle music selection
function get_selection () {
// instantiate music url
var url = 'music.php'
// get form values or defaults
var musicform = document.getElementById('musicform')
url += ('Select One' == musicform.volume.value)? '?volume=1': '?volume=' + musicform.volume.value
url += ('Select One' == musicform.tempo.value)? '&tempo=1': '&tempo=' + musicform.tempo.value
url += ('Select One' == musicform.complexity.value)? '&complexity=1': '&complexity=' + musicform.complexity.value
url += ('Select One' == musicform.key.value)? '&key=1': '&key=' + musicform.key.value
// set up XHR object
var xhr = new XMLHttpRequest()
xhr.open('GET', url, true)
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
// handle response
xhr.onload = function () {
//console.log(this.responseText)
var music = JSON.parse(this.responseText)
document.getElementById('musictitle').innerHTML = music.title
var audio = document.getElementById('audiotrack')
document.getElementById('musiclink').src = music.link
audio.load()
audio.play()
}
xhr.send()
}
// hook up music selection function to form submit
document.getElementById('musicform').addEventListener('submit', function(evt){
evt.preventDefault()
get_selection()
})
// execute music selection function at least once
get_selection()
</script>
</body>
</html>
music.php
<?php
$myDatabase = mysqli_connect("localhost","root", "root", "tunes");
$stmt = mysqli_prepare($myDatabase
, "SELECT title, link FROM music WHERE volumeOption = ? AND tempoOption = ? AND complexityOption = ? AND keySignatureOption = ?"
) or die(mysqli_error($myDatabase));
mysqli_stmt_bind_param($stmt, 'ssss', $_GET['volume'], $_GET['tempo'], $_GET['complexity'], $_GET['key']);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $title, $link);
mysqli_stmt_fetch($stmt); // assuming only one result
echo '{"title": "' . $title . '", "link": "' . $link . '"}';
mysqli_close($myDatabase);
?>
And I'm using PHP MySQLi prepared statements for database access for security and the fact plain old PHP MySQL functions are deprecated.
Disclaimer The sessionStorage object will only be available while the browser is OPEN. If you wish to retain the information regardless of the browser being closed, please change to the localStorage object instead.
Here's your working jsFiddle example
One of the easiest and quickest ways to retain form input information without even bothering with serverside language is using the sessionStorage functions.
We can capture all of the change events on the form elements and push their values into the sessionStorage. We can then retrieve and apply them to each of the respective inputs on the page reload with very minimal code.
//First, we need to make sure our users support the Storage object.
if(typeof(Storage) !== "undefined") {
/**
| -----------------------
| All of your elements can be selected by the :input selector in jQuery
| We will bind to the change function and push to the sessionStorage whenever they are altered.
| -----------------------
*/
$(':input').change(function(){
sessionStorage.setItem($(this).prop('name'), $(this).val());
});
}
Basically, if the storage is available, we create an event handler that binds to the change event of all of our form elements. Now when they change, we'll have a bunch of keys we can retrieve from the sessionStorage element.
Now, we need to apply those values to our elements on page load.
//make sure we still have Storage available.
if (typeof (Storage) !== "undefined") {
/**
| -----------------------
| We capture each of the input elements below and then check if
| we previously had values saved for them.
| If not, the default is left selected.
| -----------------------
*/
$('form *').filter(':input').each(function () {
if(sessionStorage.getItem($(this).prop('name'))){
$(this).val(sessionStorage.getItem($(this).prop('name')));
}
});
}
Now in the above code we're simply looping over all of our form elements and applying the values that were stored in the sessionStorage to those elements.
Additionally
Let's get you away from the mysql_ library as it's deprecated, and will be completely removed in future versions of PHP. Let's also focus on sanitizing user input, so you don't have SQL injection vulnerabilities which could have catastrophic side effects.
$myDatabase = new mysqli('localhost', 'username', 'password', 'database');
Users can still bypass the if(isset($_GET['submit'])){ conditional, so let's add some more sanity checking.
$volume = isset($_GET['volume']) ? $_GET['volume']: null;
$tempo = isset($_GET['tempo']) ? $_GET['tempo'] : null;
$complexity = isset($_GET['complexity']) ? $_GET['complexity'] : null;
$key = isset($_GET['key']) ? $_GET['key'] : null;
Now we should check if all those are set at the same time.
if(isset($volume, $tempo, $complexity, $key)){
}
Inside of this conditional, we can then apply our database logic using mysqli's object oriented approach. We'll also use prepared statements to avoid the SQL injection.
$stmt = $mysqli->prepare('SELECT * FROM music WHERE volumeOption=? AND tempoOption=? AND complexityOption=? AND keySignatureOption=?');
$stmt->bind_param('ssss', $volume, $tempo, $complexity, $key);
if($stmt->execute()){
while($row = $stmt->fetch()){ ?>
<div id="submitContent">
<h3><span>Now Playing:</span> <?php echo $row['title']; ?> </h3>
<figure id="audioplayer" style='display:inline-block;'>
<audio id="audiotrack" controls loop>
<source src="<?php echo $row['link']?>" type="audio/mpeg"/>
</audio>
</figure>
<?php }
}

Loading data from MySQL and populating dropdown select with jQuery Mobile, PHP

I am developing a PhoneGap application that gets some information from MySQL Database. I am struggling when I try to open a HTML page that contains two select input that need to be populated on page load, each one with data from two different tables. I don't why, but they are not getting populated. Please, any help will be very welcome.
HTML CODE
<div data-role="content">
<p></p>
<form id="cname" align="left" action="post" data-ajax="false" >
<label for "id">Employee's Name:</label><br/>
<select name="id" id="id"></select><br/>
<label for "job_id">Job's Name:</label><br/>
<select name="job_id" id="job_id"></select><br/>
<input type="hidden" name="latitued" id="latitued" value="">
<input type="hidden" name="longitude" id="longitude" value="" >
<input type="hidden" name="goo_map_api" id="goo_map_api" value="">
<input type="submit" value="Clock-In" id="enviar_in" data-inline="true">
</form>
</div
Jquery Script both SELECTS
<script type="text/javascript">
$(document).ready(function(e){
var items="";
$.getJSON("get_emp.php",function(data){
$.each(data,function(index,item)
{
items+="<option value='"+item.id+"'>"+item.fullName+"</option>";
});
$("#id").html(items);
});
});
</script>
<script type="text/javascript">
$(document).ready(function(e){
var items="";
$.getJSON("get_job.php",function(data){
$.each(data,function(index,item)
{
items+="<option value='"+item.id+"'>"+item.job_name+"</option>";
});
$("#job_id").html(items);
});
});
</script>
PHP file get_emp.php
<?php
$mysqli = new mysqli($mysql_hostname,$mysql_user, $mysql_password, $mysql_database);
$q = "select id, fullName from employees";
$sql = $mysqli->query($q);
$data = array();
while($row = mysqli_fetch_array($sql, true)){
$data[] = $row;
};
echo json_encode($data);
?>
PHP file get_job.php
<?php
$mysqli = new mysqli($mysql_hostname,$mysql_user, $mysql_password, $mysql_database);
$q = "select id, job_name from jobs";
$sql = $mysqli->query($q);
$data = array();
while($row = mysqli_fetch_array($sql, true)){
$data[] = $row;
};
echo json_encode($data);
?>
One more time, I appreciate your time taking a look at this code trying to give me a hand.
Thank you.
Code looks okay to me. Have you set the correct header?
header('Content-Type: application/json');
echo json_encode($data);
At first glimpse the code looks all right. What did you have in the console? Is all the json data there? Otherwise try
$.each(data,function(index,item)
{
$('<option>').val(item.id).html(item.job_name).appendTo("#job_id");
});
Updates:
can you please try adding
error_log(print_r($data,1));
before
echo json_encode($data);
in get_emp.php and check the php_error.log to see if the data is populated on the server side when you load the page
I think it has todo with timing between DOM ready and executing the Jquery script.
In this case your script executes before the DOM is ready. If some objects you are refering to, arent ready yet in the DOM, thus JQuery cant find the object, then JQuery simply stops executing.

AJAX can't POST to PHP file

FIXED! See bottom for solution.
I am having an incredibly hard time with this. I've been at it for weeks now. I am trying to use AJAX to add a new record into mysql. The PHP file works 100% but I can't seem to be able to make AJAX to work with my form which has a POST method of sending data. This is my first time here on StackOverflow btw so take it easy on me. Here is the code:
HTML code:
<form name='addform' method='POST' >
<td></td>
<td><input type='text' id='cname'></td>
<td>
<select id='fuel'>
<option value='Petrol'>Petrol</option>
<option value='Diesel'>Diesel</option>
<option value='Hybrid'>Hybrid</option>
<option value='LPG'>LPG</option>
</select>
</td>
<td>
<select id='trans'>
<option value='Automatic'>Automatic</option>
<option value='Manual'>Manual</option>
<option value='Semi-Auto'>Semi-Auto</option>
</select>
</td>
<td><input type='text' id='engine'></td>
<td><input type='text' id='doors'></td>
<td><input type='text' id='total'></td>
</tr>
<tr>
<td><input type='submit' value='Add Car' onclick='addRecord()'></td>
...
I have an external .js file to handle Javascript:
function addRecord(){
if (
document.addform.cname.value == ""
|| document.addform.fuel.value == ""
|| >document.addform.trans.value == ""
|| document.addform.engine.value == ""
|| document.addform.doors.value == ""
|| document.addform.total.value == ""
)
{
alert ("Empty >field(s) - Cannot create record");
return;
}
var mydata = null;
// Mozilla/Safari
if (window.XMLHttpRequest)
{
xmlHttpReq2 = new XMLHttpRequest ();
}
// IE
else if (window.ActiveXObject)
{
xmlHttpReq2 = new ActiveXObject ("Microsoft.XMLHTTP");
}
var cname = document.getElementById('cname').value;
var fuel = document.getElementById('fuel').value;
var trans = document.getElementById('trans').value;
var engine = document.getElementById('engine').value;
var doors = document.getElementById('doors').value;
var total = document.getElementById('total').value;
mydata = '?cname='+cname+'&fuel='+fuel+'&trans'+trans+'&engine'+engine+'&doors'+doors+'&total'+total;
alert ("To Server (Add New Record):\n\nadd.php" + mydata);
xmlHttpReq2.open('POST', "add.php" +mydata, true);
xmlHttpReq2.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttpReq2.send(null);
xmlHttpReq2.onreadystatechange = addRecordCallback;
}
The PHP code:
<?php
$link = mysql_connect ("194.81.104.27", "www", "www");
mysql_select_db ("xyz") or die(mysql_error());
$tot=$_POST[total];
$door=$_POST[doors];
$query = "INSERT INTO tbl
(ID, CARNAME, FUELTYPE, TRANSMISSION, ENGINESIZE, DOORS, TOTAL, AVAILABLE)
VALUES ('$_POST[cname]','$_POST[cname]', '$_POST[fuel]', '$_POST[trans]','$_POST[engine]', $door, $tot, $tot)";
$result = mysql_query($query);
mysql_close ($link);
?>
What happens is I put the info into the form, click the button and the alert tells me that it does indeed get the data from the form. But after that nothing happens. I think that the data is not being sent in the right format to the PHP file for some reason.
Thanks!
Solution was:
I managed to get it working! Part of the fault was that like #adeneo said I did not have the onclick='addRecord(); return false;' in there! Another thing I did was to remove the id of the form, not sure if that did anything at all. I have also attached "mydata" to the .send like so: xmlHttpReq2.send(mydata); and finally I had to remove a "?" which was in front of cname in the mydata variable gathering thing. So it was mydata = '?cname='+cname+... and I had to remove the ?. Thanks everyone for all the help!
Your complicating your live since you already use jquery use it for AJAX too.
$.AJAX({
url: "path to php",
type: "post",
data: $("#formID").serialize(),
});
Send this as data and you will be fine.
Sorry for has spelling, sensed from phone.
Greetings
Ezeky
There are quite a few things wrong.
You are not using the name attribute on the input/select elements. They need to have a name in order for them to be sent with the POST request. The id attribute has nothing to do with forms (except when using labels; the for attribute points to them)
<form action="/path/to/php/file.php" method="post" id="addform">
<div>
<label for="carname">CName</label>
<input type="text" name="carname" id="carname">
</div>
<div>
<label for="fuel">Fuel</label>
<select id="fuel" name="fuel">
<option value="Petrol">Petrol</option>
<option value="Diesel">Diesel</option>
<option value="Hybrid">Hybrid</option>
<option value="LPG">LPG</option>
</select>
</div>
<div>
<label for="transmission">Transmission</label>
<select id="transmission" name="transmission">
<option value="Automatic">Automatic</option>
<option value="Manual">Manual</option>
<option value="Semi-Auto">Semi-Auto</option>
</select>
</div>
<div>
<label for="engine">Engine</label>
<input type="text" id="engine" name="engine">
</div>
<div>
<label for="doors">Doors</label>
<input type="text" id="doors" name="doors">
</div>
<div>
<label for="total">Total</label>
<input type="text" id="total" name="total">
</div>
<div>
<label for="submit">Engine</label>
<input type="submit" id="submit" value="Add Car" onclick="addRecord()">
</div>
</form>
As for the javascript, it is much easier to use jQuery (or a similar library). It abstracts away all the nitty-gritty details and browser differences, and makes your life much easier.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
// When the page is done loading...
$(function () {
// When the form is submitted
$("form#addform").on("submit", function () {
// Get the form data and serialize it
var data = $(this).serialize();
// Create a POST request
var post = $.post("/path/to/php/file.php", data);
// When the request is done show a message
post.done(function () {
alert("Form submitted!");
});
// If the request fails show another message
post.fail(function () {
alert("Error! Form not submitted.");
});
// Returning false prevents the form's normal
// behaviour, i.e. its submission
return false;
});
});
</script>
Looking at your PHP code it looks like you have just learnt PHP: You are using a deprecated extension (mysql); you just use POST variables without bothering with security; and your SQL code looks a little iffy (e.g. what is AVAILABLE and why is it set to $total?); and finally, string array indices should be quoted.
// Database handle
$db = new MySQLi('194.81.104.27', 'www', 'www', 'xyz');
// SQL query with placeholders
$sql = "INSERT INTO tbl (CARNAME,FUELTYPE,TRANSMISSION,ENGINESIZE,DOORS,TOTAL) VALUES (?,?,?,?,?,?)";
// Create a statement object
$stmt = $db->prepare($sql);
// Fill in the placeholders
$stmt->bind_param('ssssii', $carname, $fuel, $transmission, $engine, $doors, $total);
// Set the values
$carname = filter_input(INPUT_POST, 'cname', FILTER_SANITIZE_STRING);
$fuel = filter_input(INPUT_POST, 'fuel', FILTER_SANITIZE_STRING);
$transmission = filter_input(INPUT_POST, 'transmission', FILTER_SANITIZE_STRING);
$engine = filter_input(INPUT_POST, 'engine', FILTER_SANITIZE_STRING);
$doors = filter_input(INPUT_POST, 'doors', FILTER_SANITIZE_NUMBER_INT);
$total = filter_input(INPUT_POST, 'total', FILTER_SANITIZE_NUMBER_INT);
// If the statement was not executed then there was an error
if ($stmt->execute() === false) {
header('HTTP/1.0 404 Not Found', true, 404);
}
// Done
Note: I never tested any of the examples. I just wrote them down in my text editor, as needed, so you will probably need to adapt them.
I think part of the issue is that you're pasting data "mydata = '?cname='+cname+'&fuel..." onto the back of the URL like you would if using GET as your transmittal method, but you define POST as the transmittal method, so doing this is unnecessary.
The POST method encapsulates the data for you.Try removing the +mydata from this line
xmlHttpReq2.open('POST', "add.php" +mydata, true);
Also, two more lines down, you're calling a function that's not listed here
xmlHttpReq2.onreadystatechange = addRecordCallback;
Seeing what that function does would be helpful.

Categories