store JSON values in input fields - php

hi i'm looking for some help
I'm learning how to use Ajax and PHP and what I want to do is to run a query in PHP and store the results in a JSON.
Then I want to echo the JSON and set it's values into text fields.
Is this possible?
Since I'm pretty new to Ajax and jQuery I'm not sure how to do this.
I attempted to do it, but I'm only getting the first value of the array.
This is my code:
<input type="text" id="text1">
<button type="button" class="btn btn-success" id="send">Success Button</button>
<input type="text" id="text2">
<input type="text" id="text3">
<input type="text" id="text4">
<script type="text/javascript">
$(document).ready(function(){
$("#send").click(function(event){
event.preventDefault();
var Rfc=$("#text1").val();
$.ajax({
type: 'POST',
url: 'search.php',
data: 'Rfc='+Rfc,
dataType : 'json',
success: function(msg){
var datashow = JSON.parse(msg);
$("#text2").val(msg[0].id_person); ///this is the only value that i get
$("#text3").val([1].person_name); ///i want to get the person's name here
$("#text4").val([2].person_address);///i want to get the person's address here
},
error : function () {
alert("error");
}
});
});
});
</script>
And this is my PHP file:
<?php
$rfc=$_POST['Rfc'];
$connection = mysqli_connect("localhost","root","","transferorders");
$query = mysqli_query($connection,"SELECT * FROM person where rfc_number ='$rfc'");
$Data = array();
while($row = mysqli_fetch_assoc($query)){
$Data[]=$row;
echo json_encode($Data);
}
?>
this is what i get in console
Uncaught TypeError: Cannot read property 'person_name' of undefined
at Object.success (test ajax1.php:40)

bro in the PHP file try to identify every variable in the array to catch them in the script, take a look at this:
<?php
$rfc=$_POST['Rfc'];
$connection = mysqli_connect("localhost","root","","transferorders");
$query = mysqli_query($connection,"SELECT * FROM person where rfc_number ='$rfc'");
$row = mysqli_fetch_array($query)
$Data = '{"id":"'.$row['id_person'].'", "name":"'.$row['person_name'].'", "address":"'.$row['person_address'].'"}';
echo json_encode($Data);
?>
and the script:
success: function(msg){
var datashow = JSON.parse(msg);
$("#text2").val(datashow["id"]); ///this is the only value that i get
$("#text3").val(datashow["name"]); ///i want to get the person's name here
$("#text4").val(datashow["address"]);///i want to get the person's address here
},
I hope it helps!

Related

Using jQuery $.ajax to post json encoded data to a php script: success event is doing nothing

I am making an ajax call using jquery to post data as json to a php file, however nothing is happening on success. My code is below :
AJAX section
$.ajax({
url:"myData.php",
dataType: 'json',
method:"POST",
data:'country',
success:function(j){
var $country = $("#country");
$.each(j, function () {
$country.append($('<option></option>').attr("value", this.country_id).text(this.country_name));
});
}
});
PHP section
if(isset($_REQUEST['country'])){
$conn=new MySQLi("localhost","root","","newdb");
$myQuery="select * from country";
$result=$conn->query($myQuery);
while($country=$result->fetch_assoc()){
echo json_encode($country);
}
}
HTML section
<label >country:</label>
<select class="form-control" id="country" >
<option>---select---</option>
</select>
You need to collect all countries in array then echo json.
$countries = [];
if(isset($_REQUEST['country'])){
$conn=new MySQLi("localhost","root","","newdb");
$myQuery="select * from country";
$result=$conn->query($myQuery);
while($country=$result->fetch_assoc()){
$countries[] = $country;
}
echo json_encode($countries);
}
Also in js send country as parameter.
...
method:"POST",
data: {country : true},
...

loadJSON only loads some objects

The JSON seems to load into the array ok and it loads into the plain text objects.
The checkbox shows checked ON even though the data clearly shows its a 0
The data does not load at all
The plain text works great
Here is the JSON
[{"0":"0","drscomplete":"0","1":"2016-03-12","drsremind":"2016-03-12","2":"db","drsby":"db"}]
This works:
<input name="drsby" type="text" id="drsby" readonly />
This load checked ON even though the data says 0:
<input name="drscomplete" type="checkbox" id="drscomplete" value="1" />
and this doesnt load at all:
<input name="drsremind" type="date" id="drsremind" />
Here is the php that does the load:
jQuery.ajax({
url: "dealfinalizeload.php",
data:'id='+id,
type: "POST",
success:function(data){
var data2 = $.parseJSON(data);
$('div#white_content_dealfinalize').loadJSON(data2);
alert(data);
},
error:function (){
alert("Error loading tasks");
}
});
this is the php that load the JSON
$SQL ="SELECT drscomplete, drsremind ,drsby from dealfinalize d where d.ID=" . $id;
$resultArray = array();
$result = mysqli_query($con,$SQL);
if($result->num_rows >0 )
$resultArray = mysqli_fetch_all($result,MYSQLI_BOTH);
echo json_encode($resultArray);
Any ideas what I did wrong?

Displaying different data in different table columns by switching options in a select

My problem is the following:
I have an ajax function that, according to the option (of a select) selected, associate a record in a database and populate another input, i.e. a p tag.
I have two td tags that have to be populated. Different data has to be displayed, so i want that, according to the input on the first select, on the second td there will be input y, in the third input z and so on... how can it be possible? If i try to append data to more than one tag, the same data is displayed in all the td columns.
Here i attach my code
Main.php
$(document).ready(function() {
$('#L_NAME0').change(function() {
var L_NAME0 = $("#L_NAME0").val();
$.ajax({
type: "POST",
url: "elaborazione_dati.php",
data: "L_NAME0=" + L_NAME0,
dataType: "html",
success: function(msg) {
$("#L_AMT0").html(msg);
$("#L_DESSERV").html(msg);
},
error: function() {
alert("Call failed");
}
});
});
});
Form.php
<label for="L_DESSERV">Descrizione del servizio</label>
<p class="L_DESSERV" id="L_DESSERV"></p>
</td
<td class="h4">
<label for="L_AMT0">Costo del servizio</label>
<p class="L_AMT0" id="L_AMT0"></p>
</td>
elaborazione_dati.php
$tipologia_selezionata = $_POST['L_NAME0'];
$sql = "SELECT * FROM acquisti WHERE durata = '$tipologia_selezionata' ";
$q = $db->prepare($sql);
$q->execute();
$q->setFetchMode(PDO::FETCH_ASSOC);
while($caratt = $q->fetch()) {
echo '<input readonly="readonly" type="hidden" name="L_NAME0" value="'.$caratt['durata'].'"/>';
echo '<input readonly="readonly" type="hidden" name="L_AMT0" value="'.$caratt['prezzi'].'"/>';
echo $caratt['prezzi']; ?> € <?php
}
Any suggestions?
Thanks a lot!
You need to split the results and the easiest way is to return JSON from PHP and then process it on your js code to generate the fields and text.
So in PHP something like:
while($caratt = $q->fetch()) {
$result->durata = $caratt[duratta];
$result->prezzi = $caratt[prezzi];
}
echo json_encode($result);
then in your js something like:
$('#L_NAME0').change(function() {
var L_NAME0 = $("#L_NAME0").val();
$.ajax({
type: "POST",
url: "elaborazione_dati.php",
data: "L_NAME0=" + L_NAME0,
dataType: "json",
success: function(data) {
$("#L_AMT0").html("<input type='hidden' name='L_NAME0' value='"+data.duratta+"'/>"+data.duratta);
$("#L_DESSERV").html("<input type='hidden' name='L_DESSERV' value='"+data.prezzi+"'/>"+data.prezzi+"€");
},
error: function() {
alert("Call failed");
}
});
However it seems confusing that you put another input named L_NAME0 - the id of your select control, but hey, it's your code... :)

how to get values from database phpmyadmin and show

i need all values from database if i click button(get values) how can
i ? please assist me any one
is there any way to do this ?
this is my index.php
<script type="text/javascript" src="jquery-1.10.1.js"></script>
<form>
<h1>Insert Data Into mySQL Database</h1>
Name <input name="name" type="text" id="name"> <br><br>
Lastname <input name="lastname" type="text" id="lastname"><br><br>
Email <input name="email" type="text" id="email"><br><br>
<input type="button" name="Submit" value="Submit" onclick="insertData()">
</form>
<button type="button">get values</button>
<div id="jcontent"></div>
<script type="text/javascript">
/* * Checking the Login - * */
function insertData(){
var data_get = {
'name_form': $('#name').val().trim(),
'lastname_form': $('#lastname').val().trim(),
'email_form': $('#email').val().trim()
};
$.ajax({
url : 'insert_ac.php',
type : 'POST',
data : data_get,
timeout : 30000,
success : function(response_data, text, xhrobject) {
console.log(text);
if(text == "success"){
$('#jcontent').html('Data Inserted');
}
else if(text == "ERROR"){
$('#jcontent').html('data not inserted');
}
}
});
}
</script>
/*******************************************************/
this is my insert.php
<?php
mysql_connect('localhost','root','');
mysql_select_db('loginthree');
$table_name = "test_three";
$name_form=$_POST['name_form'];
$lastname_form=$_POST['lastname_form'];
$email_form=$_POST['email_form'];
$sql="INSERT INTO $table_name(name, lastname, email)VALUES('$name_form', '$lastname_form', '$email_form')";
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Success";
} else {
echo "ERROR";
}
?>
<?php
// close connection
mysql_close();
?>
i need all values from database if i click button(get values) how can
i ? please assist me any one
is there any way to do this ?
Well firstly, insert a:
return false;
at the end of your insertData() function, in that way you prevent the refresh of the page so that the ajax call can load its data.
Second you are returning Success and you are trying to read success, it's case sensitive and your code will not reach that if.
Resolve these issues and get back to me
Make a PHP script (lets name it getvalues.php) to return the values from the database into JSON, such as:
$result = mysql_query("SELECT * FROM $you_table"); //mod query to match what you need to fetch
$array = mysql_fetch_row($result);
echo json_encode($array);
Then in your script above include jQuery and use something along the lines of the following to retrieve the data:
$(function ()
{
$.ajax({
url: 'getvalues.php',
data: "",
dataType: 'json',
success: function ( values )
{
var value1 = values[0]; //value1, value2, etc should represent the field names in your database
var value2 = values[1];
//and so on and so forth. each field in you DB should be one index in your values array
$('#output').html("<b>Value 1: </b>"+value1+"<b> Value 2: </b>"+value2);
}
});
});

Issue with Ajax and JSON Response

I'm a pretty novice programmer who is making an application where there are multiple divs with a class of jcontainer. Each jcontainer has an id associated with it, which corresponds with a field called apptid in a database. In the Jquery, I send out an AJAX request every five seconds to a php page to retrieve a field called currentlocation in the database (that corresponds with the apptid), which happens for each jcontainer.
Here is my code:
HTML:
<div class='jcontainer' data-param='jcontainer_IDNUMBER'>
<button class='checkIn' data-param='button_IDNUMBER'>Check In</button>
<form method='post' class='myForm' action=''>
<select name='locationSelect' class='locationSelect' data-param='location_IDNUMBER'>
<option value='1'>Exam Room</option>
<option value='2'>Exam Room 2</option>
<option value='3'>X-Ray Room</option>
<option value='1000'>Check Out</option>
</select>
</form>
<div class='finished' style='color:#ff0000;'>Checked Out</div>
</div>
jQuery:
<script type="text/javascript">
$(document).ready(function() {
setInterval(function(){
$('.jcontainer').each(function() {
var $e = $(this);
var dataid = $e.data("param").split('_')[1] ;
$.ajax({
url: 'heartbeat.php',
method: 'post',
contentType: "application/json",
dataType: "json",
data: dataid,
success: function(data){
var msg = $.parseJSON(response);
alert(msg);
}
});
});
},5000);
//other code that I didn't post, because it's not really relevant, but can post if needed be
and php page:
<?php
$hostname = 'localhost';
$username = '******';
$password = '*************';
$apptid = $_POST['dataid'];
$db = new PDO("mysql:host=$hostname;dbname=sv", $username, $password);
$statement = $db->prepare("SELECT currentlocation FROM schedule WHERE apptid = :apptid");
$statement->execute(array(':apptid' => $apptid));
$row = $statement->fetch();
$currentlocation = array('CurrentLocation' => $row['currentlocation']);
echo json_encode($currentlocation);
?>
The problem is I can't get any response from the alert(msg). Why is this? I checked Chrome Developer and no errors came up.
The end goal is to have the currentlocation number recorded in a jquery variable. ex -> var currentLocation = Number
Thanks for any and all help, and if you need more details to clear things up, I can happily post!
This block of code:
success: function(data){
var msg = $.parseJSON(response);
alert(msg);
}
should read
success: function(data){
var msg = $.parseJSON(data);
alert(msg);
}
cause the response variable is not declared and undefined so you should use the data variable in your parseJSON method as that is the actual data received. Hope this solves it for you.
You don't need $.parseJSON, jQuery will automatically parse the JSON since you're telling it dataType: "json". Your alert should then say Object. Use your browser console, and console.log(data) to see the object's structure.
You should use $.getJSON()
$.getJSON("heartbeat.php?jsoncallback=?",
{dataid},
function(data){
console.log(data);
}
);
Then in your PHP, you have to use the jsoncallback like so:
echo $_GET['jsoncallback'].'('.json_encode($currentlocation).')';
Two things to notice here.
1, I put the return from the json data in the console, rather than alert()
2, You might need to check you dataid variable as it uses traditional array values (id:3,key:value) method rather than "id=3&key=vaule"
you may use my library that does that for you automatically http://phery-php-ajax.net
function heartbeat($data){
$r = new PheryResponse;
$hostname = 'localhost';
$username = '******';
$password = '*************';
$apptid = $data['id'];
$db = new PDO("mysql:host=$hostname;dbname=sv", $username, $password);
$statement = $db->prepare("SELECT currentlocation FROM schedule WHERE apptid = :apptid");
$statement->execute(array(':apptid' => $apptid));
$row = $statement->fetch();
// If you want to manipulate the DOM inside the jcontainer use:
// $r->this()->find('.locationSelect');
// for examplee
return $r->set_var('currentLocation', $row['currentlocation']); //set the global var
}
Phery::instance()->set(array(
'heartbeat' => 'heartbeat'
))->process();
And you'd change your HTML to fit the Phery library
<div class='jcontainer' data-remote='heartbeat' data-args="<?php echo Phery::args(array('id' => $number)); /* place your number in here */ ?>" id='jcontainer_IDNUMBER'>
<button class='checkIn' data-param='button_IDNUMBER'>Check In</button>
<form method='post' class='myForm' action=''>
<select name='locationSelect' class='locationSelect' data-param='location_IDNUMBER'>
<option value='1'>Exam Room</option>
<option value='2'>Exam Room 2</option>
<option value='3'>X-Ray Room</option>
<option value='1000'>Check Out</option>
</select>
</form>
<div class='finished' style='color:#ff0000;'>Checked Out</div>
</div>
And your new jquery each will be:
$('.jcontainer').each(function(){
var $this = $(this);
$this.phery('remote'); // call the remote AJAX with the data
});
if you want to check the data in the dev console, you can use, the PHP variable will be dumped in the console
$r->dump_var($row, $apptid);

Categories