How to fetch data from mySQL and view in Modal - javascript

I am trying to show some records from my table columns named tid and ketprob by showing Modal when clicking on a link. The modal and query looks fine (checked by echoing last_query), but the modal is showing no data... Please help me :(
JS Code:
$('#showdata').on('click', '.item-info', function(){
var tid = $(this).attr('data');
$.ajax({
type: 'ajax',
method: 'get',
url: '<?php echo base_url() ?>repeatproblem/infoReprob',
data: {tid:tid},
async: false,
dataType: 'json',
success: function(data){
var html = '';
var i;
for(i=0; i<data.length; i++){
html +='<p>'+data[i].tid+'</p>'+
'<p>'+data[i].ketprob+'</p>';
}
$('#infoModal').modal('show');
$('#view_errorcode').html(html);
},
error: function(){
alert('Gagal Info Kode Error!');
}
});
});
My Controller:
public function infoReprob(){
$result = $this->m->infoReprob();
echo json_encode($result);
}
My Model:
public function infoReprob(){
$tid = $this->input->get('tid');
$this->db->select('tid, ketprob')->where('tid', $tid);
$query = $this->db->get('histprob');
if($query->num_rows() > 0){
return $query->row();
}else{
return false;
}
}

You are using return $query->row(); syntax in your model if this condition is true: $query->num_rows() > 0, so that means your model will return the object representation of the first row of the query and the $result variable in your controller below will be an object with two properties: tid and ketprob
public function infoReprob(){
$result = $this->m->infoReprob();
echo json_encode($result);
}
Now have a look at your ajax call success callback function
success: function(data){
var html = '';
var i;
for(i=0; i<data.length; i++){
html +='<p>'+data[i].tid+'</p>'+
'<p>'+data[i].ketprob+'</p>';
}
$('#infoModal').modal('show');
$('#view_errorcode').html(html);
}
Since your controller above uses echo json_encode($result); syntax, your ajax call will return the json representation of $result variable and the data variable in your success callback function above will be like below
{ "tid": "1", "ketprob": "abc" }
The problem is, data.length in your ajax success callback function will be undefined because data isn't an array, so the for loop won't be executed and html will be an empty string, see this jsfiddle. That's why your modal is showing no data.
To fix the problem, I'd suggest changing your model code as below
public function infoReprob(){
$tid = $this->input->get('tid');
$this->db->select('tid, ketprob')->where('tid', $tid);
$query = $this->db->get('histprob');
return $query->result();
}
By using return $query->result(); syntax, your model will always return an array of object. As the result, your ajax call will return a json like this
[ { "tid": "1", "ketprob": "abc" } ]
which is a json array, so data.length in your ajax success callback function won't be undefined and your modal will show the data. See this jsfiddle, you'll see that the html variable is not empty.

I guess you should use echo $query->row(); instead of return $query->row();.

Solved by changing return $query->row(); to return $query->result();
Going to learn about this. Or can anybody tell about the different.. Thanks
public function infoReprob(){
$tid = $this->input->get('tid');
$this->db->select('tid, ketprob')->where('tid', $tid);
$query = $this->db->get('histprob');
if($query->num_rows() > 0){
return $query->result();
}else{
return false;
}
}

Related

Ajax call to php, get mysql data as array and use in JS function

I'm looking to make an ajax call to a PHP script to get data from MySQL, create a json array and pass it back to the success function of the ajax call, where i will then use it as parameters for a JavaScript function.
This is my ajax call,
$('button[name="message"]').click(function() {
var $row = $(this).closest("tr"); // Find the row
var $tenant_id = $row.find(".col-md-1 id").text(); // Find the tenants ID
var $landlord_id = "<?php echo $id; ?>"
$.ajax({
url : "./message.php",
type : "POST",
async : false,
data: {
landlord_id: $landlord_id,
tenant_id : $tenant_id
},
success: function(data){
console.log(data);
var messages = data;
insertChat(messages.sender_id, messages.body, messages.timestamp);
}
})
});
And this is my PHP file,
<?php
session_start();
require_once('../dbconnect.php');
// update tenants table to show deposit returned
if(isset($_POST['tenant_id'])){
$tenant_id = $_POST['tenant_id'];
$landlord_id = $_POST['landlord_id'];
$sql = "SELECT * from messages WHERE messages.sender_id OR messages.receiver_id = '$tenant_id' AND messages.sender_id OR messages.receiver_id = '$landlord_id'";
$result = mysqli_query($conn, $sql) or die("Error in Selecting " . mysqli_error($conn));
//create an array
$messages = array();
while($row =mysqli_fetch_assoc($result))
{
$messages[] = $row;
}
echo json_encode($messages);
}
?>
If anybody has a link to a tutorial or the individual parts that would be fantastic. I don't even know if the process i have outlined above is correct.
If anybody could tell me the correct way to go about this that would be of great help!
Thanks
Just a few things to adjust your javascript side (I won't explain the php sql injection issue you have... but please research prepare, bind_param and execute):
Since you are returning an ARRAY of $messages from php (json_encoded), you need to loop on those in your success handler.
Add dataType: 'JSON' to your options, so it explicitly expects json returned from php.
And you were missing a couple semicolons ;)
Adjustments added to your code:
$('button[name="message"]').click(function() {
var $row = $(this).closest("tr");
var tenant_id = $row.find(".col-md-1 id").text();
var landlord_id = "<?php echo $id; ?>";
$.ajax({
url : "./message.php",
type : "POST",
data: {
landlord_id: landlord_id,
tenant_id : tenant_id
},
dataType: 'JSON',
success: function(data){
console.log(data);
if (typeof data !== undefined) {
for(var i = 0; i < data.length; i++) {
insertChat(data[i].sender_id, data[i].body, data[i].timestamp);
}
}
}
});
});

How to show AJAX response data inside div

I am using Laravel framework. I get stuck on this. I get data successfully. But, when I want to display the data, it displays me data in array form. Can anyone help me how to display the Listing. I have one layout inside div
<div class="col-md-9 col-sm-9 col-xs-12" id="ajaxListings">
#include('layouts.publicLayout.get-listings')// here i have implemented layout
</div>
and
function filteredlistings(){
$.ajax({
url:'search-listings',
data:{
'service_name':title,
'location':location
},
type:"get",
success:function(allData)
{
$("#ajaxListings").html(allData);
},
error: function()
{
alert('error');
}
});
}
And here is my function :
public function search_listings(Request $request){
if($request->ajax()){
$data = $_GET;
$users = DB::table('users')
->join('business_services', 'users.id', '=', 'business_services.user_id')
->join('listings','users.id', '=', 'listings.user_id')
->select('users.id', 'business_services.name', 'business_services.list_id','listings.location')
->where(['business_services.name'=>$data['service_name'],'users.service_name'=>"Seller"])
->where('listings.location','like','%'.$data['location'].'%')
->get();
$users = json_decode(json_encode($users),true);
foreach($users as $alluser){
$ids[] = $alluser['id'];
}
$allData="";
if(!empty($ids)){
$allData = User::with('listings')->whereIn('id',$ids)->get();
$allData = json_decode(json_encode($allData),true);
}
$title = "Nails";
echo "<pre>"; print_r($allData); die;
}
}
Iguess that you want to return the layout + the data, so you could use :
return view('layouts.publicLayout.get-listings',compact('allData'));
Instead of :
echo "<pre>"; print_r($allData); die;
You could access your data inside the layout using $allData.
Hope this helps.
The issue is this:
echo "<pre>"; print_r($allData); die;
Instead of print_r, return the data as JSON so that it can be parsed by jQuery:
return response()->json($allData);
Then in your jQuery success function you can iterate over the data
success:function(allData)
{
// simple example showing the firstnames
var example = '';
$.each(allData, function(){
example += ', ' + this.firstname;
});
$("#ajaxListings").text(example);
},

Populating an array through jquery AJAX in php

I have a function in a compare.php that takes a parameter $data and uses that data to find certain things from web and extracts data and returns an array.
function populateTableA($data);
So to fill array I do this
$arrayTableA = populateTableA($name);
now this array is then used to iterate tables..
<table id="tableA">
<input type="text" name="search"/><input type="submit"/>
<?php foreach($arrayTableA as $row) { ?>
<tr>
<td><?php echo $row['name']?></td>
<td><?php echo $row['place']?></td>
</tr>
</table>
Now what I want to do is to enter some data on input and then through jquery ajax
function populateTableA($data);
should be called and $array should be refilled with new contents and then populated on tableA without refreshing the page.
I wrote this jquery but no results.
$(document).on('submit',function(e) {
e.preventDefault(); // Add it here
$.ajax({ url: 'compare.php',
var name = ('search').val();
data: {action: 'populateTableA(name)'},
type: 'post',
success: function(output) {
$array = output;
}
});
});
I have been doing web scraping and the above was to understand how to implement that strategy... original function in my php file is below
function homeshoppingExtractor($homeshoppingSearch)
{
$homeshoppinghtml = file_get_contents('https://homeshopping.pk/search.php?category%5B%5D=&search_query='.$homeshoppingSearch);
$homeshoppingDoc = new DOMDocument();
libxml_use_internal_errors(TRUE);
if(!empty($homeshoppinghtml)){
$homeshoppingDoc->loadHTML($homeshoppinghtml);
libxml_clear_errors();
$homeshoppingXPath = new DOMXPath($homeshoppingDoc);
//HomeShopping
$hsrow = $homeshoppingXPath->query('//a[#class=""]');
$hsrow2 = $homeshoppingXPath->query('//a[#class="price"]');
$hsrow3 = $homeshoppingXPath->query('(//a[#class="price"])//#href');
$hsrow4 = $homeshoppingXPath->query('(//img[#class="img-responsive imgcent"])//#src');
//HomeShopping
if($hsrow->length > 0){
$rowarray = array();
foreach($hsrow as $row){
$rowarray[]= $row->nodeValue;
// echo $row->nodeValue . "<br/>";
}
}
if($hsrow2->length > 0){
$row2array = array();
foreach($hsrow2 as $row2){
$row2array[]=$row2->nodeValue;
// echo $row2->nodeValue . "<br/>";
}
}
if($hsrow3->length > 0){
$row3array = array();
foreach($hsrow3 as $row3){
$row3array[]=$row3->nodeValue;
//echo $row3->nodeValue . "<br/>";
}
}
if($hsrow4->length > 0){
$row4array = array();
foreach($hsrow4 as $row4){
$row4array[]=$row4->nodeValue;
//echo $row3->nodeValue . "<br/>";
}
}
$hschecker = count($rowarray);
if($hschecker != 0) {
$homeshopping = array();
for($i=0; $i < count($rowarray); $i++){
$homeshopping[$i] = [
'name'=>$rowarray[$i],
'price'=>$row2array[$i],
'link'=>$row3array[$i],
'image'=>$row4array[$i]
];
}
}
else{
echo "no result found at homeshopping";
}
}
return $homeshopping;
}
As mentioned in the comments PHP is a server side language so you will be unable to run your PHP function from javascript.
However if you want to update tableA (without refreshing the whole page) you could create a new PHP page that will only create tableA and nothing else. Then you could use this ajax call (or something similar) -
$(document).on('submit','#formReviews',function(e) {
e.preventDefault();
$.ajax({
url: 'getTableA.php', //or whatever you choose to call your new page
data: {
name: $('search').val()
},
type: 'post',
success: function(output) {
$('#tableA').replaceWith(output); //replace "tableA" with the id of the table
},
error: function() {
//report that an error occurred
}
});
});
Hi You are doing it in wrong way.You must change your response to html table and overwrite older one.
success: function(output) {
$("#tableA").html(output);
}
});
In your ajax page create a table with your result array
You are in a very wrong direction my friend.
First of all there are some syntax error in your JS code.
So use JavaScript Debugging
to find where you went wrong.
After that Basic PHP with AJAX
to get a reference how ajax and PHP work together
Then at your code
Create a PHP file where you have to print the table part which you want to refresh.
Write an AJAX which will hit that PHP file and get the table structure from the server. So all the processing of data will be done by server AJAX is only used for request for the data and get the response from the server.
Put the result in your html code using JS.
Hope this will help

AJAX is running correctly but doesn't display fetched data

My PHP query is running fine(based on the response on firebug) but the result its giving me are [object Object] on my direct page. So I'm guessing that my problem lies on my javascript because on firebug under the response tab its retrieving all my data on my database
Here is my javascript
function AjaxRetrieve()
{
var rid = document.getElementById('trg').value,
data = {chat: uid, rid: rid, name: user};
$.ajax({
url: "includes/getChat.php",
type: "GET",
data: data,
dataType: 'json',
success: function(result){
var res = $([]);
$.each(result[0], function(key, value) {
res = res.add($('<div />', {text : value}));
});
$("#clog").html(res);
}
});
}
The php script as requested is this
$sql7 = "SELECT message_content, username , message_time, recipient FROM ".$tbpre."chat_conversation WHERE msgid=:chat";
$stmt7=$con3->prepare($sql7);
$stmt7->bindValue( 'chat', $msgd, PDO::PARAM_STR);
$stmt7->execute();
$message_query = $stmt7;
$json = array();
if($message_query->rowCount() > 0) {
while($message_array = $stmt7->fetchAll(PDO::FETCH_ASSOC)) {
$json[] = $message_array;
}
echo json_encode($json);
}
I'm not that familiar yet on JQUERY/AJAX/Javascript so I'm not actually sure if what I'm doing is correct I just based some of my codes on jquery's documentation and some
suggestions from our fellow members here
The way your constructing the json data is wrong,try this way
$json =array();
$i=0;
if($message_query->rowCount() > 0) {
while($message_array = $stmt7->fetchAll(PDO::FETCH_ASSOC)) {
$json[$i]= $message_array;
$i++;
}
echo json_encode($json);
}
Happy Coding :)
Change your success callback like below, you have an array of objects.
success: function(result){
var container = $("#clog");
$.each(result, function(i, message) {
$.each(message, function(key, value) {
container.append($('<div />').html(key + ':' + value));
});
});
}
Edit:
And you have to change fetchAll to fetch in you while loop.
while($message_array = $stmt7->fetch(PDO::FETCH_ASSOC)) {
$json[] = $message_array;
}
echo json_encode($json);
Or just use fetchAll without while loop:
$json = $stmt7->fetch(PDO::FETCH_ASSOC);
echo json_encode($json);

How to pass row name from php to ajax using jquery

I have a table in which the details are fetched from the DB.
if(mysql_num_rows($sql) > 0)
{
$row_count_n=1;
while($rows=mysql_fetch_assoc($sql))
{
extract($rows);
$options1 = select_data_as_options("project_resources", "name", $resource_allocated);
$options2 = select_data_as_options("project_roles", "name", $role);
echo "<tr>";
echo "<td><select name='ra_$row_count_n'><option value=''>-- Select --$options1</option></select></td>";
echo "<td><select name='role_$row_count_n'><option value=''>-- Select --$options2</option></select></td>";
echo "<td><input type='text' name='start_date_tentative_$row_count_n' class='date_one' value=$tentatively_starts_on /></td>";
echo "</tr>";
$row_count_n++;
}
}
I wanted to update the table when required, am doing this using Ajax by collecting data from the form using Jquery and saving it on button click.
$("#save_changes_id").click(function()
{
// To retrieve the current TAB and assign it to a variable ...
var curTab = $('.ui-tabs-active'); // in NEWER jQueryUI, this is now ui-tabs-active
var curTabPanelId = curTab.find("a").attr("href");
if(curTabPanelId == "#tab_dia")
{
var curTab = $('#sub_tabs .ui-tabs-active');
var curTabPanelId = curTab.find("a").attr("href");
}
responseData = doAjaxCall($(curTabPanelId + " form"));
if(responseData == 1)
showMessage('status_msg', 'Project details updated successfully', 'green');
else
showMessage('status_msg', 'Error: Please check all the fields', 'red');
});
function doAjaxCall(objForm)
{
var values = objForm.serialize();
$.ajax({
url: ajaxURL,
type: "post",
data: values,
async: false,
success: function(data)
{
responseData = data;
},
error:function()
{
alert('Connection error. Please contact administrator. Thanks.');
}
});
return responseData;
}
Ajax code is as below:
case "allocate_ba_details":
for($i=1; $i<=$row_count; $i++)
{
$resource = $_REQUEST["ra_$i"];
$role = $_REQUEST["role_$i"];
$start_date_tentative = $_REQUEST["start_date_tentative_$i"];
$already_available_check = mysql_num_rows(mysql_query("select * from project_allocate_ba where project_id = $pdid"));
if($already_available_check > 0)
{
$sql = ("UPDATE project_allocate_ba SET resource_allocated='$resource', role='$role', tentatively_starts_on='$start_date_tentative' WHERE project_id=$pdid");
}
}
echo $sql;
break;
As I am new to this am not sure how to pass the row name in order to update a particular row.
Please suggest a solution. Thanks in advance.
firstly use PDO or some php framework that has nice API to work with mysql. Second don't use success/error callback in jquery is too deprecated. Instanted use done/fail.always.
I understand that you want update row in html table data from the server ?
In success callback simply update the table using jquery text method for jquery object. You don't paste all code so i write example:
in server.php
<?php
[...]
$already_available_check = mysql_num_rows(mysql_query("select * from project_allocate_ba where project_id =" . intval($pdid)));
[...]
echo $already_available_check;
?>
This code return the integer, so in doAjaxCall:
function doAjaxCall(objForm)
{
var values = objForm.serialize();
$.ajax({
url: ajaxURL,
type: "post",
data: values,
async: false,
success: function(data)
{
if(typeof data !== 'undefined' && $.isNumeric(data)) {//check that server send correct anserw
$('whereIsData').text(data);
}
},
error:function()
{
alert('Connection error. Please contact administrator. Thanks.');
}
});
}
Now in success method you populate some DOM element using text method. You cannot simply return data from ajaxCall method because $.ajax is asynchronized method and responseData has value only when ajax request ends, so always return undefined in you example. You must present responseData to the user in success callback method.
For one thing...
$sql = ("UPDATE project_allocate_ba SET resource_allocated='$resource', role='$role', tentatively_starts_on='$start_date_tentative' WHERE project_id=$pdid")
needs single quotes around $pdid
Also don't echo the $sql. Instead do your inspection and form a response.
$response = array();
if(EVERYTHING_IS_GOOD){
$response['status'] = 'good to go';
}else{
$response['status'] = 'it went horribly wrong';
}
echo json_encode($response);

Categories