Issue with Ajax and JSON Response - php

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);

Related

Dependable drop down list using ajax in codeigniter is not working

Im trying to make a dependable dropdownlist using ajax in codeigniter. I used a code..but its not working.. the values are not appended to the dropdownlist. Retrieving data from database to first dropdown list is working perfectly. First Dropdown list works fine...but i want to make dependable dropdown list subcategory based on category using ajax
CONTROLLER::
public function pdview()
{
$this->load->helper('url');
$this->load->helper('form');
$this->load->model('AjaxpModel');
$data['cnames'] = $this->AjaxpModel->getcat();
$this->load->view('pd',$data);
}
public function getsubcaty()
{
$postData = $this->input->post();
$this->load->model('AjaxpModel');
$data = $this->AjaxpModel->getsubcategory($postData);
echo json_encode($data);
}
View::
Category Name : <select name="category" id="category">
<option value="">Select</option>
<?php
foreach($cnames as $catn){
echo "<option value='".$catn['catname']."'>".$catn['catname']."</option>";
}
?>
</select><br><br>
Subategory Name :
<select name="subcategory" id="subcategory">
<option value="">Select</option>
</select><br><br>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type='text/javascript'>
var baseURL= "<?php echo base_url();?>";
$(document).ready(function(){
// Category Change
$('#category').change(function(){
var cat = $(this).val();
// AJAX request
$.ajax({
url:'<?=base_url()?>index.php/Ajaxuser/getsubcaty',
method: 'post',
data: {cat:cat},
dataType: 'json',
success: function(response){
$('#subcategory').find('option').not(':first').remove();
// Add options
$.each(response,function(index,data){
$('#subcategory').append('<option value="'+data['subcatname']+'">'+data['subcatname']+'</option>');
});
}
});
});
});
Model:::
public function getcat()
{
$this->load->database();
$result=$this->db->select('cid,catname')->from('catc')->get()->result_array();
$cname=array();
foreach($result as $r)
{
$catname[$r['catname']] = $r['catname'];
}
$catname[''] = 'Select ';
return $catname;
}
function getsubcategory($postData){
$response = array();
// Select record
$this->db->select('scid,subcatname');
$this->db->from('scatc');
$this->db->where('catname', $postData['cat']);
$q = $this->db->get();
$response = $q->result_array();
return $response;
}
first of all check if your base_url() is defined properly.
As you followed my steps on comment section, I think I see the issue on your JS,
You can try this one:
$(document).ready(function(){
// Category Change
$('#category').change(function(){
var cat = $(this).val();
// AJAX request
$.ajax({
url:'<?=base_url()?>index.php/Ajaxuser/getsubcaty',
method: 'post',
data: {cat:cat},
dataType: 'json',
success: function(response){
var $el = $("#subcategory");
$el.empty();
$("#subcategory").val('');
$el.append($("<option></option>")
.attr("value", '')
.attr("hidden",'')
.text('Select Subcategory'));
$.each(response, function(index, data){
$el.append('<option
value="'+data.subcatname+'">'+data.subcatname+'</option>')
});
}
});
});
});
Let's see what you got there after trying this.
On your getsubcategory model you forgot to load the database. It should be like this:
$this->load->database();
On same model function, $postData[cat] must be only $postData because you are not passing an array data from your controller otherwise you will be having Illegal string offset error.
EDIT:
Since we've figured out that the problem is base_url()
Configure if the helper 'url' is loaded, you can set it on application/config/autoload.php.
and you must define it to know what exactly the value of base_url().
You can set it on application/config/config.php.
To test if the base_url() is working, try to echo base_url().

store JSON values in input fields

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!

Trying to get information from database with jQuery

I am VERY new to jQuery, and I have been trying to get information from my SQL database whenever the user chooses a new option in a datalist form. This is the code:
<form>
<input list="chemicals" name="chemicalsearch">
<datalist id="chemicals">
<?php while ($info3=mysql_fetch_array($info2)) {
echo "<option value='$info3[name]'>$info3[formel]</option>";
}
?>
</datalist>
</form>
<script type="text/javascript">
$('#chemicals').on('change', function() {
var record_id = $(this).val();
var data = {
'id': record_id
};
$.ajax({
type: "GET",
url: '/Chemistry%20Calculator/getchemical.php',
data: data,
success: function(response) {
document.getElementById('formel').innerHTML = data.formel;
},
error: function(jqXHR, textStatus, errorThrown) {
}
});
});
</script>
And then the PHP file:
<?php
include_once 'connect.php';
$info="SELECT * from chemicals where name='$id'";
$info2=mysql_query($info) or die("Wrong link. This page does not exist.");
$info3=mysql_fetch_array($info2);
$name = $info3['name'];
$formel = $info3['formel'];
$massa = $info3['molmassa'];
$array = array($name, $formel, $massa);
$data = json_encode($array);
echo $data;
?>
Please be patient with me here, as I have never used jQuery before. And yes, I am aware of the fact that I'm using the old MySQL syntax, I will change that as soon as I get this working.
Any help would be greatly appreciated :)
You are not writing what exactly is the problem, either from the side of php or javaScript. But anyway, correct your syntax to php regarding the variables. Like below:
<?php while ($info3=mysql_fetch_array($info2)) {
echo '<option value="'.$info3[name].'">'.$info3[formel].'</option>';
}?>
and later on your query...$info='SELECT * from chemicals where name="'.$id.'"'
The success method is a function to be called if the request succeeds. The function gets passed three arguments:
The data returned from the server, formatted according to the dataType parameter or the dataFilter callback function, if specified;
A string describing the status;
The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object.
In your case:
success: function(data, textStatus, jqXHR) {
//The "data" returned from server is assigned to HTML element here
document.getElementById('formel').innerHTML = data;
}
A side note: usage of mysql_* functions is deprecated, use PHP PDO instead.
EDIT: Do not forget to include jQuery library in your file, before trying to execute the code $(“#chemicals")..... The error of $ being undefined means exactly that.

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},
...

Jquery - Fetching Comments From Database

oI am having problem fetching comments from MySQL database using jQuery.
I am trying this way, but its not working.
PHP (comments.php)
<?php
if (isset($_POST['value1'])) {
$id = ($_POST['value1']);
}else{
$id = '';
}
if (isset($_POST['value2'])) {
$database = ($_POST['value2']);
}else{
$database = '';
}
if (isset($_POST['value3'])) {
$tablename = ($_POST['value3']);
}else{
$tablename='';
}
require_once('rt-connect.php');
$find_data = "SELECT * FROM $tablename";
$query = mysqli_query($connection, $find_data);
?>
<?php while($row = mysqli_fetch_assoc($query)):?>
<div class="comment-container">
<div class="user-info"><?php echo $row['user_name']; ?></div>
<div class="comment"><p><?php echo $row['comment']; ?></p></div>
</div>
<?php endwhile;?>
Jquery(comments.html)
var id=2;
var database='comments_db';
var tablename='comments';
$.post('comments.php', {value1:id, value2:database, value3:tablename}, function(data)
{
$('#comments').load('comments.php .comment-container');
});
Html(div on comments to load on comments.html)
<div id="comments"></div><!--end of comments-->
Please see and suggest any possible way to do it.
Thanks
Try This one it will help you.
This is jquery Ajax post method requesst if you want to show your data is loaded or not just remove the commet.
$.ajax({
type: "POST",
url: url,
data: { value1:id, value2:database, value3:tablename}
}).done(function( data ) {
//alert(data); return false;
$("#comments").html(html);
});
You have $.load() inside success function of $.post(), try this..
$.post('comments.php', {value1:id, value2:database, value3:tablename}, function(data)
{
$('#comments').html(data);
});
In your javascript, you are posting data to a url, accepting response and if the response is successful, you are sending another request to the PHP script, this time without parameters. Your comments box is displaying the result of your second request.
You do not require :
$('#comments').load('comments.php .comment-container');
in your javascript, since you have already received a response. Instead, use :
$('#comments').html(data);
which will display the response data in the comments div.
You could try this one,
var id = 2;
var database = 'comments_db';
var tablename = 'comments';
$.ajax({
type :"POST",
data :"id="+id+"&database="+database+"&tablename="+tablename,
url : comments.php,
success: function(msg){
$("#comments").html(msg);
}
});

Categories