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.
Related
I'm trying to get multiple checked checkbox value data added to mysql with php without reloading the form page and show confirmation message in div on form page. At the moment, showing on div works but data is not being sent.
I already have done another similar one which I had almost the same code that had the input as text area so I changed that part and it works but the this one is not working. Could anyone give me help here?
form is in vote.php:
<html>
<form action="vote_received.php" method="post" target="" id="vote-submit">
<input type="hidden" name="recieved-date" id="todayDate" />
<input type="hidden" name="user-occup" id="user-occup" value="<?php $_SESSION['occupation']; ?>" />
<input type="checkbox" name="voting[]" value="How might we improve driver facilities such as lunch rooms or break rooms?" id="voting_1">
<label for="voting_1">How might we improve driver facilities such as lunch rooms or break rooms?</label>
<input type="checkbox" name="voting[]" value="How might be increase driver security at night time?" id="voting_2">
<label for="voting_2">How might be increase driver security at night time?</label>
<input type="checkbox" name="voting[]" value="How might we change the on-call communication with management?" id="voting_3">
<label for="voting_3">How might we change the on-call communication with management?</label>
<input type="checkbox" name="voting[]" value="How might we enhance the passenger conflict management system?" id="voting_4">
<label for="voting_4">How might we enhance the passenger conflict management system?</label>
<br><br>
<input type="submit" name="submit" value="Submit" class="btn align-right"></form>
<script>
$("#vote-submit").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $(this),
$messages = $("input[name='voting[]']"),
$occup = $form.find('input[name="user-occup"]'),
$submit = $form.find('button[type="submit"]'),
message_value = $messages.val(),
url = $form.attr('action');
var posting = $.post(url, { submission : message_value});
posting.done(function(data) {
/* Put the results in a div */
$("#vote_success").html('<h2>THANK YOU!</h2><p>Thank you for your voting. Meeting invitations will be send out on December 7th, 2017.');
/* Hide form */
$form.hide();
});
});
</script>
</html>
the vote_received.php is:
<?php
session_start();
if(isset($_POST['vote-submit'])) {
$voteArray=$_POST['voting'];
$conn = mysqli_connect($servername, $username, $password, $database);
if(is_null($voteArray)) {
echo("<p>You didn't select any topic.</p>\n");
} else {
$N = count($voteArray);
for($i=0; $i < $N; $i++) {
$var1 = $voteArray[$i];
$jobTitle = $_SESSION['occupation'];
$sql = "INSERT INTO vote_response (occupation, voting,
created) VALUES('$jobTitle', '$var1', now())";
$success = mysqli_query($conn, $sql);
if (!$success) {
die("Couldn't enter data: ".$conn->error);
}
echo $var1;
$conn->close();
}
}
}
?>
Thank you very much!
try to change this part of your code
var $form = $(this),
$messages = $("input[name='voting[]']"),
$occup = $form.find('input[name="user-occup"]'),
$submit = $form.find('button[type="submit"]'),
message_value = [],
url = $form.attr('action');
$.each($messages, function(idx, val){
message_value.push($(val).val());
});
var posting = $.post(url, { submission : message_value});
on further reading of your code, try to change this part of you code also:
if(isset($_POST['submission'])) {
$voteArray=$_POST['submission'];
i need to update a message box every second or so and i dont really have a clue what to do and i also do most coding differently to what i find online, heres my code
<?php
//first connect to the database
require_once('includes/connect.php');
$sql = "SELECT * FROM `MetalM` WHERE `class` LIKE :msg";
$paragraph = $pdo->prepare($sql);
$paragraph->bindValue(':msg','Message',PDO::PARAM_STR);
$paragraph->execute();
?>
This is the code for my connection
<?php
try
{
$pdo = new PDO('mysql:host=localhost;dbname=DATABASE', 'USER',
'PASSWORD');
}
catch (PDOException $e)
{
echo 'Unable to connect to the database server.';
exit;
}
?>
this is the code for where my messages are being loaded
<div id="mesgBox">
<?php
foreach ($paragraph as $key) {
echo '<div id="messages"><p>'.$key['Name'].': <br>'.$key['Message'].'</p></div>';
}
?>
</div>
<div id="sndmsg">
<h1>Message:</h1>
<form action="insert.php" method="GET">
<input id="meassage" name="meassage" type="text" placeholder="Text Here">
<input id="submit" type="submit" value="Send">
</form>
<br>
</form>
</div>
You will need to do this with Ajax.
You ll need to set Set up a timer that will retrieve every x seconds the new data
for example:
Requirements: jQuery
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
setInterval(function(){
$.post ('/get-update.php', function(data,success)
{
if (success=='success')
if (data.status=='ok')
$('#messages').html(data.Messages);
},'json');
},5000);
</script>
Now, you will have to change your php a little bit in order to make this work.
-- EDIT --
ok, let me refine..
You will need to include jquery lib in your head
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Then you will need to have a php file which does exactly what you need to do.... (bring the new messages)
as in:
<?php
// file name: get-update.php
// Just this code here.
require_once('includes/connect.php');
$sql = "SELECT * FROM `MetalM` WHERE `class` LIKE :msg";
$paragraph = $pdo->prepare($sql);
$paragraph->bindValue(':msg','Message',PDO::PARAM_STR);
$paragraph->execute();
$TextBuffer ="";
$StringFormat = "<div id='messages'><p>%s : <br>%s</p></div>";
while ($row = $paragraph->fetch(PDO::FETCH_ASSOC))
$TextBuffer .= sprintf($StringFormat, $row['Name'],$row['Messagge']);
echo json_encode(array("status"=>"ok","Messages"=>$TextBuffer));
?>
I am using this autocomplete tut: http://www.jensbits.com/2010/03/29/jquery-ui-autocomplete-widget-with-php-and-mysql/ .
The jQuery aren't displaying. You can actually click the grey line (shown in picture) and it will load everything. I just can't see the names for some reason.
I thought it could be a css problem, but I couldn't find anything relevant.
<div class="guestinfo">
<form action='' method="POST">
<div class="ui-widget">
<div class="existingguest"><label>Exisiting Guest</label>
<input type="text" class="auto" name="guests" id="guests"/></div>
</div>
<div class="existingguestinfo">
<div><label>First Name</label><input readonly="readonly" type="text" id="firstname" name="firstname"/></div>
<div><label>Last Name</label><input readonly="readonly" type="text" id="lastname" name="lastname"/></div>
<script>
$(function() {
$('.auto').val("");
$(".auto").autocomplete({
source: "classes/autocomplete_guests.php",
minLength: 1,
select: function(event, ui) {
$('#firstname').val(ui.item.fname);
$('#lastname').val(ui.item.lname);
$('#address').val(ui.item.address);
$('#phone').val(ui.item.phone);
}
});
});
</script>
<!--<div><label>Add New Guest</label></div>-->
<div><label>Address</label><input readonly="readonly" type="text" id="address" name="address"/></div>
<div><label>Phone</label><input readonly="readonly" type="text" id="phone" name="phone"/></div>
</br></div>
</form>
</div> <!-- end guestinfo div -->
autocomplete_guests.php
<?php
//open connection
require_once('../config/db.php');
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$return_arr = array();
/* If connection to database, run sql statement. */
if ($con)
{
$fetch = mysqli_query($con, "SELECT * FROM guests WHERE lname like '%".mysqli_real_escape_string($con, $_GET['term'])."%'");
/* Retrieve and store in array the results of the query.*/
while ($row = mysqli_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['id'] = $row['id'];
$row_array['lname'] = $row['lname'];
$row_array['fname'] = $row['fname'];
$row_array['gender'] = $row['gender'];
$row_array['address'] = $row['address'];
$row_array['city'] = $row['city'];
$row_array['state'] = $row['state'];
$row_array['phone'] = $row['phone'];
$row_array['email'] = $row['email'];
$row_array['dob'] = $row['dob'];
$row_array['zip'] = $row['zip'];
array_push($return_arr,$row_array);
}
}
/* Free connection resources. */
mysqli_close($con);
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
?>
You should
1) write script tags like <script type="text/javascript">
2) Put your javascript at the bottom of the page and not half way through the form... (?!!)
3) Add a document ready to that function so that it executes when the page finished loading.
$( document ).ready(function() {
4) Make sure you have included all the required jquery files: Jquery Core, Jquery UI, etc.
5) Provide some CSS if you think that is the problem??
EDIT:
Ignore 3. Ive just looked at the plugin documentation.
Just try these lines inside before ur Jquery script
====sorry if am wrong =====
I am working with jQuery autocomplete plugin and this is my index:
<script>
$(document).ready(function(){
$("#tag").autocomplete({source: "./search.php?q="+ $("#tag").val()});
});
</script>
<form action="search.php" method="post" class="form-inline search">
<input type="text" id="tag" name="tag">
<input type="submit" class="btn" value="Search" />
</form>
in search.php which is in the same folder as index.php is following:
include 'config.php';
$q=$_GET['q'];
$my_data=mysql_real_escape_string($q);
$sql="SELECT * FROM tags WHERE tag LIKE '%$my_data%'";
$result = mysql_query($sql) or die(mysql_error());
if($result)
{
while($row=mysql_fetch_array($result))
{
echo $row['tag']."\n";
}
}
When I start typing, autocomplete doesn't offer me any suggestions. Also no errors in JS console. In the code is just displayed No search results..
The paths are set up correctly, the database connection as well.
Thus, where could be a problem?
Thank you
You don't need to use a query string on the src url of autocomplete.
Just write your src file without query string:
$("#tag").autocomplete({source: "./search.php"});
And in your php file you have to capture the term parameter:
$q = $_GET['term'];
Solved this way - in PHP file must be data returned in JSON:
while($row=mysql_fetch_array($data))
{
$result[] = $row['tag'];
}
echo json_encode($result);
I am a newby so appologise for asking a basic question.
I have a php page - a 'create new project' page
There are some simple data such as name, deadline etc...
but depending on the type of the project I have 4 different ends (different pages?) in this FORM and I can't find the solution for it.
Here is my code:
<h1>New Project</h1>
<form name="newpr">
New project name:<input type="text" placeholder="new project name..."><br />
New project end date:<input type="text" placeholder="date..."><br />
New project type:
<select name="menu" onChange="location=document.newpr.menu.options[document.newpr.menu.selectedIndex].value;" >
<?php
$listdata = mysql_query("SELECT * FROM lists WHERE tag='prtype' ORDER BY listing ASC");
while($listresult = mysql_fetch_array($listdata))
{
if ($listresult["listing"]!="...") $link=$listresult["value"].".php";
else $link="";
echo "<option value='".$link."'>".$listresult["listing"]."</option> ";
}
?>
</select>
</form>
As you see the select list comes from Mysql and I would like a div under a form to be able to open page1.php or page2.php etc as user selects...
Thanks in advance
Andras
it might be ajax question...
I'd solve this the following way
<!-- using jQuery -->
<h1>New Project</h1>
<form method="" action="post">
New project name:<input type="text" placeholder="new project name..."><br/>
New project end date:<input type="text" placeholder="date..."><br/>
New project type:
<select name="menu">
<?php
$listdata = mysql_query("SELECT * FROM lists WHERE tag='prtype' ORDER BY listing ASC");
while($listresult = mysql_fetch_array($listdata))
{
$link = '';
if($listresult['listing'] != '...') {
$links = $listresult['value'] . ".php";
echo "<option value='$link'>${listresult['listing']}</option>";
}
}
?>
</select>
<div id="page">
<!-- container for loaded page -->
</div>
<script type="text/javascript">
$("select[name=menu]").change(function() {
var url = $("option:selected", this).val();
// Load a page to the container
$("#page").load(url);
});
</script>
</form>
Using jQuery I added on change handler on select box and if it's changed it loads via ajax a page to the div container.
And let me give you and advice - try to avoid mixing code and html. It leads to difficulties in further development and maintenance.
You want to make a HTTP request to your php page Checkout http://mootools.net/docs/core/Request/Request.HTML
http://mootools.net/docs/more/Request/Request.JSONP
Listen for the callback on your request then inject the returned data as an element into the DOM. Mootools is my weapon of choice but Jquery etc. all have this same functionality. call php page under Javascript function This question is very similar to yours.