How to load data using jQuery and JSON? - php

I want to load data from a MySQL database to a PHP page using jQuery and JSON. When the user choose the name from the select box, it loads the person's data into the text field.
This is my HTML code (select)
<select name='name' id='name'>
<option value='1'>John</option>
<option value='2'>Marco</option>
<option value='3'>Charles</option>
</select>
The text field that I want to populate with the person data:
<input type='text' name='firstname' value='' id='firstname'/>
<input type='text' name='phonenum' value='' id='phonenum'/>
getpersonData.php
<?php
include('dbconfig.php');
$id = $_POST['id'];
$query = "select * from person where ID='$id'";
$result = mysql_query($query);
$data = mysql_fetch_array($result);
echo json_encode($data);
?>
The Ajax call:
$.ajax({
type: "POST",
async : false,
url: 'http://test.com/getpersonData.php',
dataType: 'json',
data : {
id : $("#id").val(),
},
success : function(data) {
//What to insert here?
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest + " : " + textStatus + " : " + errorThrown);
}
});
What code should I use for the success function?

First, you should set your Content-type header right before you echo your json_encode in getpersonData.php:
header("Content-type: application/json");
echo json_encode($data);
In your success function you would do something like:
$("#firstname").val(data.firstname); //firstname is the key of the user's firstname from your mysql query

I'm guessing your DB column names here, but maybe something like this
$('#firstname').val(data.firstname);
$('#phonenum').val(data.phonenum);

getpersonData.php
<?php
include('dbconfig.php');
$id = $_POST['id'];
$query = "select * from person where ID='$id'";
$result = mysql_query($query);
$data = mysql_fetch_array($result);
header("Content-type: application/json");
echo json_encode($data); ?>
main file
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Load JSON data through jQuery and PHP </title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
load_data($('#name').val());
$('#name').change(function(){
load_data($('#name').val());
});
});
function load_data(personid)
{
$.getJSON("getpersonData.php", {id: personid}, function(data){
$('#firstname').val(data['firstname']);
$('#phonenum').val(data['phonenum']);
});
}
</script>
</head>
<body>
<select name="name" id="name">
<option value='1'>John</option>
<option value='2'>Marco</option>
<option value='3'>Charles</option>
</select>
<input type='text' name='firstname' value='' id='firstname'/>
<input type='text' name='phonenum' value='' id='phonenum'/>
</body>
</html>

Related

send selected dropdown value to another PHP page

I do not use submit button
I want the selected value from the user sent to the test1.php page, but when the user selects an option nothing happen in the page, and the value is not sent to the test1.php page
Is there any mistake in my code, or did I miss something ?
test2.php
<?php include_once 'database.php';
?>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(function() {
$('.category').change(function() {
var category = $('.category option:selected').val();
alert('category changed to ' + category);
$.ajax({
method: "POST",
url: "test1.php",
data: {
category1: $(this).val()
},
success: function(data) {
console.log(data);
}
});
});
});
</script>
</head>
<p> Filter By Category</p>
<select id="category" class="category">
<?php
$query = mysqli_query($conn,"select * from category ");
while($category = mysqli_fetch_array($query)) {
echo "<option value='" . $category['cat_name'] . "'>" . $category['cat_name'] . "</option> ";
}
?>
</select>
test1.php
<?php
include_once 'database.php';
if (isset($_POST['category1'])) {
$category = $_POST['category1'];
echo $category;
}
?>
is that all your file ? did you forget to include jquery ?
I just did the same script as yours but in html, and console said $ not found, after add jquery that's working
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(function() {
$('.category').change(function() {
$.ajax({
method: "POST",
url: "https://webhook.site/2d574d22-5570-46f2-b5bd-343d715adff4",
data: {
category1: $(this).val()
},
success: function(data){
console.log(data);
}
});
});
});
</script>
</head>
<body>
<p> Filter By Category</p>
<select id="category" class="category">
<option value='1'>One</option>
<option value='2'>two</option>
</select>
</body>
</html>
here is the webhook to check your request, it is like test1.php but just for debugging purpose https://webhook.site/#!/2d574d22-5570-46f2-b5bd-343d715adff4/e3406220-f58e-45be-a4ef-13d8d3e0b0d3/1
here are some advices:
inspect your page using developer tools, maybe there are some errors
check with console.log .val()
hope this help

Why form is fetching all data when i dont give any input?

This is index.php . when i give a input, it fetch the specific name and year. that's OK . but when i submit the form ,without any input it gives all the name of the movie and years but i don't want that ,the user can not show all the data saved in the database. i gave priventdefault() method but it's not working. how can i solve this problem ?
<!DOCTYPE html>
<html>
<head>
<title>ajax</title>
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
<script type="text/javascript">
$(function() // this function excited if the jquery is ready i mean after jquery successfully loaded
{
function loaddata()
{
var moviename= $("#moviename").val(); // read moviename value and assign;
$.ajax({
type: "GET",
url: "query.php",
data: {
name:moviename // there is no variable name so you have to assign the moveiname to name vairable ;
},
success: function (data) {
$("#result").html(data);
}
});
}
$("#submit").click(function(event) // Click Event Listener.
{
event.preventDefault();
loaddata()
});
});
</script>
</head>
<body>
<p>Enter movie name </p>
<form action="" method="POST">
<input type="text" name="moviename" id="moviename" placeholder="Enter Movie Name" required autocomplete="off">
<input type="submit" name="submit" id="submit" value="Search"/>
<!-- if you want ot use jquery you have to use event listener. like $("#submit").click(function(event){}); code from line 31 to 35 -->
</form>
<br>
<div id="result">
</div>
</body>
</html
///this is query.php
<?php
include 'dbcon.php';
$name =isset($_GET['name'])?$_GET['name']:'';
$query = mysqli_query( $conn,"SELECT * FROM movie WHERE name like '%$name%'");
while($row = mysqli_fetch_array($query))
{
echo "<p>".$row['name']."</p>";
echo "<p>".$row['year']."</p>";
}
?>
Execute the query only if $name is not null.
if(!empty($name)) {
$query = mysqli_query( $conn,"SELECT * FROM movie WHERE name like '%$name%'");
while($row = mysqli_fetch_array($query)){
echo "<p>".$row['name']."</p>";
echo "<p>".$row['year']."</p>";
}
}
$name =isset($_GET['name'])?$_GET['name']:'';
if(!empty($name)){
$query = mysqli_query( $conn,"SELECT * FROM movie WHERE name like '%$name%'");
while($row = mysqli_fetch_array($query))
{
echo "<p>".$row['name']."</p>";
echo "<p>".$row['year']."</p>";
}
}
in javascript
var moviename= $("#moviename").val(); // read moviename value and assign;
if(moviename){
$.ajax({
type: "GET",
url: "query.php",
data: {
name:moviename // there is no variable name so you have to assign the moveiname to name vairable ;
},
success: function (data) {
$("#result").html(data);
}
});
}
In query.php, you always assign empty string to $name in the line if empty 'name' value passed into query.php
$name =isset($_GET['name'])?$_GET['name']:'';.
So query will return you all the results in db as $name is an empty string and matches with all the data in db.
You can validate if $name is empty, not to run the query.

Jquery Ajax Value Fetch

I want to fetch value through jquery Ajax in PHP. but when I run below this code value is fetch properly but all value are joined together when fetching and together value print all field, but I want to print the separate value in the separate field. my code is below, please solve this problem
index.php
<!DOCTYPE html>
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<select name="Pro" onChange="my_validate_func()" id="pro_serv">
<option value=""></option>
<option value="" ><font size="-1">Add New Product</font></option>
<option value="Development"><font size="-1">Development</font></option>
<option value="Maintance"><font size="-1">Maintance</font></option>
</select>
<br />
<input type="text" name="desc" id="desc" value="" />
<br />
<input type="text" name="unitprice" id="unitprice" value="" />
<br /><input type="text" name="discount" />
<script type="text/javascript" src="bootstrap/jquery1.8.3jquery.min.js">
</script>
<script>
$( document ).ready(function() {});
function my_validate_func() {
var pro_serv = $('#pro_serv').val();
if ($('#pro_serv').val() != "" ) {
$.ajax({
type: "POST",
url: 'check.php',
data: { pro_serv: pro_serv},
success: function(response) {
$('#desc').val(response);
$('#unitprice').val(response);
$('#tax').val(response);
}
});
}
}
</script>
</body>
</html>
check.php
<?php
include('database/db.php');
$type=$_POST['pro_serv'];
$sql="Select * from product_service_details where type='$type'";
$result=mysql_query($sql);
if($dtset=mysql_fetch_array($result))
{
$desc=$dtset['desc'];
$unitprice=$dtset['unitprice'];
$tax=$dtset['tax'];
echo $desc;
echo $unitprice;
echo $tax;
}
?>
You need to use json_encode in php and in jquery you need to parse the response like below:
PHP:
<?php
include('database/db.php');
$type=$_POST['pro_serv'];
$sql="Select * from product_service_details where type='$type'";
$result=mysql_query($sql);
if($dtset=mysql_fetch_array($result))
{
echo json_encode($dtset);
}
JQuery:
$.ajax({
type: "POST",
url: 'check.php',
data: { pro_serv: pro_serv},
success: function(response) {
var res = $.parseJSON(response);
$('#desc').val(res.desc);
$('#unitprice').val(res.unitprice );
$('#tax').val(res.tax );
}
});
You can use a separates for separate values then use JS split function.
echo $desc ."-" . $unitprice ."-" .$tax;
In Js
var arr = response.split('-');
$('#desc').val(arr[0]);
$('#unitprice').val(arr[1]);
$('#tax').val(arr[2]);
in check.php
*echo $tax;* should be echo json_encode('tax'=>$tax);
and in index.php
$('#tax').val(response); can be $('#tax').val(response.tax);

How do I get the value of the selected customer to echo <input> element?

Database info:
CREATE TABLE
IF NOT EXISTS tz_customer (
id INT (10) NOT NULL,
customervarchar (255) NOT NULL,
NAME VARCHAR (255) NOT NULL,
vs_1 VARCHAR (255) NOT NULL,
stamp VARCHAR (255) NOT NULL
)
And PHP Code
THIS IS index.php FILE
<select name="nimetus" id="nimetus" onchange="chg(this.value)">
<?php $q3 = mysql_query("SELECT * FROM tz_kliendid"); while ($f3 = mysql_fetch_array($q3)) { ?>
<option value="<?php echo $f3['id']; ?>"><?php echo $f3['klient']; ?></option><?php } ?></select>
<input type="text" id="target" value="">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">function chg(str){
$.ajax({
url: "showdata.php",
type: "POST",
data: {
"val": str
},
success: function (response) {
$("#target").val(response);
},
error: function (xhr) {
alert("Some error found!!");
}
});
}</script>
AND showdata.php FILE
<?php if(isset($_GET['val'])){$nimetus=$_POST['nimetus'];
$q1=mysql_query("SELECT vs_1 FROM tz_kliendid WHERE id='".$nimetus."' ORDER BY id DESC LIMIT 1"); $f1=mysql_fetch_array($q1); echo $f1['vs_1']; } ?>
Each customer has a "tz customer" table "vs_1" column marked 0 or 1.
When I choose a customer, how can I reach the selected customer "vs_1" value from the table?
And
How do I get the value of the selected customer to echo <input> element?
Hi I don't completely understand your question as far as i can understand you need vs_1 value of every customer when you change that select.You need to change your option value as id as it is the primary.You need ajax to do this
<select name="nimetus" id="nimetus" onchange="chg(this.value)">
<?php
while ($f3 = mysql_fetch_array($q3)) {
?>
<option value="<?php echo $f3['id']; ?>">
<?php echo $f3['customer']; ?>
</option>
<?php
}
?>
</select>
<input type="text" id="target" value="">
In java script
function chg(str){
$.ajax({
url: "showdata.php",
type: "POST", //send it through post method
data: {
"val": str
},
success: function (response) {
//Do Something
$("#target").val(response);
},
error: function (xhr) {
//Do Something to handle error
alert("Some error found!!");
}
});
}
In showdata.php
if(isset($_POST['val']))//your POST method
{
$nimetus=$_POST['val'];
$q1=mysql_query("SELECT vs_1 FROM tz_kliendid WHERE id='".$nimetus."' ORDER BY id DESC LIMIT 1");
$f1=mysql_fetch_array($q1);
echo $f1['vs_1'];
}
You can use a data-attribute to hold the value of v1 and then access it with jquery to display it, by doing this you won't need to have an extra ajax call each time you change the value
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<?php
$option = '';
$q3 = mysql_query("SELECT * FROM tz_customer");
while ($f3 = mysql_fetch_array($q3)) {
$option .= '
<option value="' . $f3['customer'] . '"' . ($f3['id'] == $f3['customer'] ? " selected" : "") . ' data-v1="'.$f3['v1'].'">
' . $f3['customer'] .
'</option>';
} ?>
<select name="nimetus" id="nimetus">
<?= $option ?>
</select>
<div id="output"></div>
<script>
$(function() {
$('#cbo').on('change', function() {
var opt = $('option:selected', $(this));
$('#output').html(opt.text()+ ' => v1 :'+ opt.data('v1'));
});
});
</script>
</body>
</html>

how to get dynamic value by ajax function call

on my web page i have text area like this
and i suppose to get data in textarea when i alternate the value of select box( or onChange event), so i used ajax function
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
function myCall() {
var request = $.ajax({
url: "ajax.php",
type: "GET",
dataType: "html"
});
request.done(function(msg) {
$("#mybox").html(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
</script>
and this is my select box code,
<select name="txtname" id="txtname" onChange="myCall()" >
<option value="0">Select Age:</option>
<option value="100083">100083</option>
<option value="22-26">22-26</option>
<option value="26-30">26-30</option>
<option value="30-34">30-34</option>
</select>
actualy i want to fetch record on the basis of select box value, this function working fine for static value but i am puzzled how to get data from data base..
and my ajax page coding is here..
<?php
$con=mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("hmc", $con);
$sql="SELECT * FROM news WHERE name = '22-26'";
$result = mysql_query($sql);
?>
<?php
while($row=mysql_fetch_array($result))
{
?>
<tr>
<td>
<?php echo $row['news1'];?></h3></td>
</tr><br /><hr /><br />
<?php
}
?>
</div>
any idea will be appreciated...
Your ajax call is not proper, you need to pass your select box value to the php side, like this
$.ajax({
url: "ajax.php",
type: "GET",
dataType: "html",
data:"value="+$("#txtname").val();
});
then use this value on php side using $_GET['value']

Categories