ajax php jquery mobile select menu - php

On the same page I have an area to add a patient and a separate patient select menu. If a patient is added, I would like the select menu to show this new patient without refreshing the page.
The select menu is originally populated with:
<?php
$result = mysql_query("SELECT * FROM `patients` WHERE `company_id` = " . $user_data['company_id'] . " ORDER BY `patient_firstname`");
while($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['patient_id'] . '">' . $row['patient_firstname'] . ' ' . $row['patient_lastname'] . '</option>';
}
?>
When the select menu is used the input fields first_name, last_name, & dob are populated using:
$('#patientselect').live('change', function() {
$.ajax({
url : 'patientget.php',
type : 'POST',
dataType: 'json',
data : $('#patientform').serialize(),
success : function( data ) {
for(var id in data) {
$(id).val( data[id] );
}
}
});
});
which retrieves the information from the patientget.php:
$patientId = $_POST['patientselect']; // Selected Patient Id
$result = mysql_query("SELECT `patient_id`, `patient_firstname`, `patient_lastname`, `patient_dob` FROM `patients` WHERE `patient_id` = $patientId");
$row = mysql_fetch_assoc($result);
$patientId = $row['patient_id'];
$patientFirstName = $row['patient_firstname'];
$patientLastName = $row['patient_lastname'];
$patientDob = $row['patient_dob'];
$arr = array(
'input#patient_id' => $patientId,
'input#patient_firstname' => $patientFirstName,
'input#patient_lastname' => $patientLastName,
'input#patient_dob' => $patientDob);
echo json_encode( $arr );
?>
This is my first post, so please let me if I need to provide more/clearer information.
Thank in advance!! Adam

Related

Image change from dropdown using AJAX

Here I have one drop down menu on which selection other dropdown changes result the id of other dropdown is "style_code". Now I also want to change image on dropdown selection, it is like when I select color from dropdown it changes sizes which is other dropdown, but I also want to change image on color selection.
<script>
function getState(val) {
$.ajax({
type: "POST",
url: "check.php",
data:'id='+val,
success: function(data){
$("#style_code").html(data);
}
});
}
</script>
Here is check.php
<?php
$con=mysqli_connect("localhost","root","","db") or die(mysql_error());
if(!empty($_POST["id"])) {
$query ="SELECT * FROM stylecolor WHERE color_code = '" . $_POST["id"] . "'";
$results = mysqli_query($con,$query);
while ( ($row=mysqli_fetch_array($results))){?>
<option value="<?php echo $row["color_name"]; ?>">
<?php echo $row['size'] ; ?>
</option>
<?php
}
}
?>
Your difficulty comes from the fact that you are returning HTML code from the PHP script. My advice is to return JSON data then generate style_code children with jQuery.
It would be something like that :
check.php
<?php
$con = mysqli_connect("localhost", "root", "", "db") or die(mysql_error());
if(!empty($_POST["id"])) {
$query = "SELECT * FROM stylecolor WHERE color_code = '" . $_POST["id"] . "'";
$results = mysqli_query($con, $query);
$data = new stdClass(); // This object will carry the results
while (($row = mysqli_fetch_object($results))) {
$data->option[] = $row;
}
// Another query to get the image name
$query = "SELECT name FROM image_name WHERE color_code = '" . $_POST["id"] . "'";
$results = mysqli_query($con, $query);
if ($row = mysqli_fetch_object($results)) {
$data->image_name = $row->name;
}
header('Content-Type: application/json');
echo json_encode($data);
}
HTML & Javascript:
...
<div class="thumb-image" id="style_image" >
<img src="images/<?php echo $productimg1?>" data-imagezoom="true" class="img-responsive" alt="" />
</div>
...
<script language="javascript">
function getState(val) {
$.ajax({
type: "POST",
url: "check.php",
data: {id: val},
dataType:'json',
success: function(data) {
$("#style_code").children().remove(); // empty the dropdown
// Add new options in the dropdown from the result data
data.option.forEach(function (item) {
$("#style_code").append('<option value="' + item.color_name + '">' + item.size + '</option>');
});
// Change the 'src' attribute of the <img>
$("#style_image").find('img').attr('src', 'images/' + data.image_name + '?d=' + Date.now().toString());
}
});
}
</script>

display the information of the person once selected autocomplete jquery

I am using jQuery autocomplete plugin to provide suggestions of names from the database. What I am trying to do is to display the information of the person once selected. Can someone give me an idea on how and where will I pass and get the id (primary key) of the selected person?
js
$('input[name="name"]').autoComplete({
minChars: 1,
source: function(term, response){
$.getJSON('names.php', { name: term }, function(data){
var arr = $.map(data, function(el) { return el });
response(arr);
});
},
onSelect: function(){
//get id -> show info
}
});
names.php
require 'con.php';
$term = $_GET['name'];
$arr = array();
$query = mysqli_query($connection,
"SELECT
id,
firstname,
middlename,
lastname
FROM mytbl
WHERE firstname LIKE '%$term%' ||
middlename LIKE '%term%' ||
lastname LIKE '%term%'");
while($row = mysqli_fetch_array($query)){
$arr[] = $row['firstname'] . " " . $row['middlename'] . " " . $row['lastname'];
}
echo json_encode($arr);
Thank you!
What you need to do is return multidimensional array from PHP script and handle it in jQuery script.
So your PHP snippet should look like this.
<?php
$arr = array();
while ($row = mysqli_fetch_array($query)) {
$name = $row['firstname'] . " " . $row['middlename'] . " " . $row['lastname'] . " " . $row['extension_name'];
$ar = array();
$ar['label'] = $name;
$ar['value'] = $name;
$ar['id'] = $row['id'];
$arr[] = $ar;
}
echo json_encode($arr);
Now jQuery code look something like this,
$('input[name="official_name"]').autoComplete({
minChars: 1,
source: function(term, response) {
$.getJSON('names.php', {
official_name: term
}, function(data) {
var arr = $.map(data, function(el) {
return el
});
response(arr);
});
},
select: function(event, ui) {
var id=ui.item.id;
console.log("Selected item ID => "+ id);
}
});
Above code returns multidimensional array with Name and ID. jQuery autocomplete expect label and/or value as key from returned array to display it in drop-down.
The label property is displayed in the suggestion listand the value will
be added into the textbox after the user selected something
from the list.
When you select any item you just have to use ui.item.id for accessing the id of the selected the item.

How to get multiple fields from a dropdown box in php to be used in other programs

I have two drop down list in the main page, when the user clicks on the country drop down(on change) another drop down list would be shown with the product list. This I accomplish using an ajax call (getproduts.php) from the country drop down list. The screen shots, the ajax call and the programs are attached .
The dropdown list works well and I can select the item too. The drop down list has the both the product description and the price in it.
I would like to get the price in a variable to be used in the main program when ever the user selects the option.
The sub total value(attached screen) in the main program should change with the price from the dropdown box when ever the user selects the product.
How can I achieve this?.
Ajax call
<script type="text/javascript">
function get_products()`enter code here`
{
var country = $("#country").val();
var type = $("#type").val();
var dataString = 'country='+ country + '&type=' + type;
$.ajax({
type: "POST",`enter code here`
url: "getproducts.php",
data: dataString,
success: function(html)
{
$("#get_products").html(html);
}
});
}
</script>
getproducts.php
<?php
error_reporting(1);
//print_r($_POST);
include('function/db_connect.php');
//session_start();
$price = Null;
//$items = Null;
if($_POST)
{
$var1 = $_POST['country'];
$var2 = $_POST['type'];
if ($var1 != '') {
echo "<label>Item<span style='color:red'>*</span></label><span style='color:red'></span></label><span class='address'>";
echo "<select id='items' name='items' style = 'width: 546px;' onChange='get_price(this.value)'>";
$sql = "SELECT * FROM tbl_product WHERE country_id = '$var1' AND type_id = '$var2'";
$db = new DB_CONNECT();
$result = mysql_query($sql);
$myarray = array();
echo "<option value=''>Select</option>";
while ($row = mysql_fetch_array($result)) {
$idp = $row["product_id"];
$iddes = $row["product_desc"];
$selp = $row["product_sell"];
$costp = $row["product_cost"];
echo "<option value='" . $idp . "'>" . $iddes . "==>".$selp ."</option>";
}
echo "</select><label>Item</label></span><span class='address'>";
}
echo "</div>";
echo "<br>";
echo "<div><label></label><span class='name'><button name = 'data' type ='button' onclick= 'valprice('items')'>Validate value</button></span></div>";
}
?>
Right now in your select html element, you're using onChange='get_price(this.value), this line of code only get the option value in this case only $idp = $row["product_id"];. If you want to select others field, then you need to attach those values into option itself during looping process occured. Here is the example usage.
In your option tag, change into this :
echo "<option value='" . $idp . "' data-price='" . $selp . "'>" . $iddes . "==>".$selp ."</option>";
You see i adding data-price='" . $selp . "' as a user defined attribute. This later on we fetch at onchange event.
After that, change your select HTML element onchange into this :
echo "<select id='items' name='items' style = 'width: 546px;' onChange='get_price(this)'>";
Finally, in your get_price() function tweak into this below code :
<script>
// array variable to store product details[id and price in this case]
var myProduct = [];
function getPrice(e) {
// set to empty for initial
myProduct.length = 0;
// fetch price
var price = $('option:selected', $(e)).data('price');
// fetch val ID
var valID = $(e).val();
// insert into array variable as a javascript object
myProduct.push({
ID : valID,
price : price
});
console.log(myProduct);
}
</script>
To fetch another fields, put another data-attributes like example above.
DEMO - check console to see the output

Update a Select Box on Parent Page from FancyBox2

I'm trying to submit a form in a fancybox where users can add a company to a select box that exists on the modals parent page. Im doing this by submitting the modal information to a script that adds the company to my database. Then I run a query to to get all the updated companies as a group of tags. Then I am trying to pass that group of tags to the parent page as a jquery update. Im not sure if this is the best approach or where I'm going wrong.
I am attempting to use this post as a guide:
Find element on site from a fancybox iframe
But I have two problems with my code.
One: The fancybox is not closing
Two: The select box on the parent page is not updating
I am not sure where I am going wrong with my success call. The code from the Modal page is:
$("#send-message").click(function(){
$(this).closest('form').submit(function(){
return false;
});
var frm = $(this).closest('form');
if($(frm).valid()){
$("#ajax-loading").show();
var data = $(frm).serialize();
$(frm).find('textarea,select,input').attr('disabled', 'disabled');
$.post(
"../forms/company_add.php",
data,
function(data) {
if (data.success) {
// data.redirect contains the string URL to redirect to
$('#companyselect', $(parent.document)).html(data.success);
parent.$.fancybox.close();
}
else {
$("#ajax-loading").hide();
$(frm).find('textarea,select,input').removeAttr('disabled');
$("#send_message_frm").append(data.error);
}
},
"json"
);
}
});
The Code from company_add.php returns all the options tags like such:
if ($_POST) {
// Collect POST data from form
$name = filter($_POST['name']);
$conmail = filter($_POST['conmail']);
$addy = filter($_POST['addy']);
$confax = filter($_POST['confax']);
$city = filter($_POST['city']);
$state = filter($_POST['state']);
$con = filter($_POST['con']);
$conphone = filter($_POST['phone']);
$zip = filter($_POST['zip']);
}
$search1 = mysql_query("SELECT man_name FROM manufacturers WHERE man_name = '$name'");
$outcome1 = mysql_fetch_row($search1);
$num_rows1 = mysql_num_rows($search1);
$imageid1 = $outcome1[0];
$imageid1 = filter($imageid1);
if ($num_rows1 > 0) {
echo json_encode(array(
"error" => '<div class="msg-error">A company by that name already exists.</div>'
));
} else {
$stmnt = mysql_query("INSERT INTO manufacturers (manufacturer_id, man_name, man_address, man_city, man_state,man_zip, man_contact, man_phone, man_fax, man_mail) VALUES ('NULL', '" . $name . "', '" . $addy . "' ,'" . $city . "', '" . $state . "' , '" . $zip . "' , '" . $con . "' , '" . $conphone . "' , '" . $confax . "', '" . $conmail . "' )");
//echo "Duplicate WAS found:" . $answer1;
mysql_query($answer1);
//}
$resp['status'] = 'success';
if (empty($error)) {
$nada = "SELECT man_name FROM manufacturers ORDER BY man_name ASC";
$resulter = mysql_query($nada);
$comp1 = '0';
//Spit out array of companys as select boxes
$select = '<option value="">--Select one--</option>';
while ($result59 = mysql_fetch_array($resulter))
$select .= '<option value="' . $result59['man_name'] . '">' . $result59['man_name'] . '</option>';
echo json_encode(array(
"success" =>$select
));
} else {
echo json_encode(array(
"error" => '<div class="msg-error">Error: Unable to add your company at this time</div>'
));
}
}
I am new to programming and very new to Jquery so I'm hoping someone can see where I'm going wrong. I am using fancybox 2 and php.
Have you checked error console for any JavaScript errors?
You can try this anyway:
parent.$('#companyselect').html(data.success);

Problems with certain characters in jQuery/PHP

I am having problems with some characters after I added some jQuery to my code.
http://www.blueskycouncil.com/login-form.php (login: stack/this)
It worked fine when I was just doing it all in php but now it converts some of the characters weirdly.
This is the jQuery code I am using:
<script type="text/javascript">
// Check to see if document is ready
$(document).ready(function () {
// Set sort mode to Best
$.post("_db_index.php",
{sort_id: "best"},
// Take data from _db_index.php and put it into the HTML
function(output){
$('#left').html(output).show();
});
});
// Check to see whether user have voted on item before
function updateKarma(element, id, sortId){
$.post("idea_karma.php",
{pagetype: "index", karmatype: "ideaspace", id: id, sort_id: sortId},
function(output){
element.parentNode.className="karma-btn_voted";
element.parentNode.innerHTML="<span class=\"voted\">"+output+"</span>";
});
return false;
}
function viewMode(sortId){
$.post("_db_index.php",
{sort_id: sortId},
function(output){
$('#left').html(output).show();
$.post("subnavigation.php",
{sort_id: sortId},
function(output){
$('#base').html(output).show();
});
});
};
$(function(){
$(".base a").hover(function(){
$(this).children("span").fadeOut();
}, function(){
$(this).children("span").fadeIn();
})
});
and in the _db_index.php file it fetch it like this
<?php
// Start session
require_once('auth.php');
require_once('config.php');
require_once('db_open_select.php');
// Functions
include('trunctate_text.php');
$sort_id = $_POST['sort_id'];
$member_id = $_SESSION['SESS_MEMBER_ID'];
// Check for PHP Insert Hack
if(array_key_exists("sort_id",$_POST)){
$sort_allowed = array("best","new","comments");
if(in_array($_POST["sort_id"],$sort_allowed)){
$sort_id = $_POST["sort_id"];
}
}
echo "<div id=\"gradient\">";
//If User selected Best Rated or if url is empty:
if (empty($_POST) OR $sort_id == "best") {
//Perform database query
$result = mysql_query("SELECT * , (SELECT COUNT( 1 ) FROM comments C WHERE C.idea_id = I.id) AS COMMENTS, ( SELECT login FROM members M WHERE I.member_id = M.member_id ) as login FROM ideaspace I ORDER BY KARMA DESC", $connection);
$query = mysql_query("SELECT idea_id FROM vote_idea WHERE member_id = $member_id", $connection);
//Create array with which ideas the current user has voted on already
$user_voted_on_this = array();
while($row = mysql_fetch_assoc($query))
{
$user_voted_on_this[] = $row["idea_id"];
}
//If User selected newest:
} elseif ($sort_id == "new") {
$result = mysql_query("SELECT * , (SELECT COUNT( 1 ) FROM comments C WHERE C.idea_id = I.id) AS COMMENTS, ( SELECT login FROM members M WHERE I.member_id = M.member_id ) as login FROM ideaspace I ORDER BY DATE DESC", $connection);
$query = mysql_query("SELECT idea_id FROM vote_idea WHERE member_id = $member_id", $connection);
//Create array with which ideas the current user has voted on already
$user_voted_on_this = array();
while($row = mysql_fetch_assoc($query))
{
$user_voted_on_this[] = $row["idea_id"];
}
//If User selected most commented:
} else {
if ($sort_id == "comments")
$result = mysql_query("SELECT * , (SELECT COUNT( 1 ) FROM comments C WHERE C.idea_id = I.id) AS COMMENTS, ( SELECT login FROM members M WHERE I.member_id = M.member_id ) as login FROM ideaspace I ORDER BY COMMENTS DESC", $connection);
$query = mysql_query("SELECT idea_id FROM vote_idea WHERE member_id = $member_id", $connection);
$user_voted_on_this = array();
while($row = mysql_fetch_assoc($query))
{
$user_voted_on_this[] = $row["idea_id"];
}
}
if (!$result && !$query) {
die("Database connection failed: " . mysql_error());
}
// 4. Use data from database
while ($row = mysql_fetch_array($result)) {
echo
"<dt id=\"idea\">";
if (in_array($row['id'],$user_voted_on_this)) {
echo
"<div class=\"karma-btn_voted\">
<span class=\"voted\">{$row['karma']}</span>
</div>";
} else {
echo
"<div class=\"karma-btn\">
<img src=\"images/btn_lrg_karma.png\" alt=\"Alternative text\"><span class=\"voted\"><div class=\"newkarma\">{$row['karma']}</div></span>
</div>";
}
echo
"<div class=\"textbox\">
<P class=\"category\">" . $row['category'] . "</p>
<P class=\"headline\"> " . $row['d_header']."</P>
<P>" . $shortdesc = myTruncate($row['d_description'], 220, " ") . "</p>" .
"<P class=\"name\">Submitted by " . $row['login'] . " " . date('D d Y', strtotime($row['date'])) . "<img src=\"images/comments.png\" align=\"center\">". $row['COMMENTS'] ."</p>" .
"</div>
</dt></div>";
}
?>
<?Php
require_once('db_close.php');
?>
As I said it worked fine when it was PHP but now that i fetch the data it replaces some characters with diamond ? character icon.
is an encoding issue, lots of things to check - UTF-8 problem when saving to mysql
The response is encoded in cp1252, but your page in UTF8
The char that disappears has decimal-code 146
’
You should change the encoding before you send the response(or better before you insert the data to the db).
mb_convert_encoding($str, "UTF-8", "CP1252");
Thanks everyone I fixed it
mysql_query("SET NAMES utf8"); in the db_connection file.

Categories