How do i import the extracted Json data to database - php

I am trying to fetch movie information from omdbapi.So far i have this code which is extracting data from imdb using omdb api.But i want import that data to my database.how do i accomplish that.
my code look like this
<form>
<input type="text" id="tst"/>
<input type="button" value="search" id="btn"/>
</form>
<table class="table table-hover" id="imdb">
<thead>
<tr>
<th>Poster</th>
<th>Title</th>
<th>Year</th>
<th>Rated</th>
<th>Runtime</th>
<th>Genre</th>
<th>Director</th>
<th>Actors</th>
<th>Plot</th>
</tr>
</thead>
<tbody></tbody>
</table>
This is jquery code i am using to fetch the movie information
$(document).ready(function () {
$('#btn').click(function(){
var imdbid=$('#tst').val();
var url = "http://www.omdbapi.com/?i="+imdbid+"&plot=short&r=json"
$.ajax({
url:url,
dataType:'json',
success:function (json) {
var tr;
tr = $('<tr/>');
tr.append("<td><img src=" + json.Poster + " width='200' height='297'></td>");
tr.append("<td>" + json.Title + "</td>");
tr.append("<td>" + json.Year + "</td>");
tr.append("<td>" + json.Rated + "</td>");
tr.append("<td>" + json.Runtime + "</td>");
tr.append("<td>" + json.Genre + "</td>");
tr.append("<td>" + json.Director + "</td>");
tr.append("<td>" + json.Actors + "</td>");
tr.append("<td>" + json.Plot + "</td>");
$('#imdb').append(tr);
}
})
})
});

You can create a json object from your api response(in same function where you are creating html).
JSONData = JSON.stringify({
"Title": Title,
"Year": Year,
"Rated" : Rated,
...........so on
});
postDataToserver(JSONData);
And you can define your function to post data like -
function postDataToserver(JSONData)
$.ajax({
url: "your_server_script_path",
type:"POST",
data:JSONData,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(response) {
error: function (error) {
}
});
If you want to send in simple post format not as JSON object then you don't need to use JSON.stringify and similarly in function remove contentype information. Hope this will help you.

Related

Data columns not binding with the element of HTML table

I'm trying to display data from my PostgreSQL into an HTML table using Ajax and PHP. But it seems that the data I am getting is not binding into the columns element of HTML table, I just get back a Json string .
How can I am binding id, employee_name, employee_salary and employee_age column with 'td' element of HTML table
This is my code:
HTML
<div class="col-sm-6" style="padding-top:50px;">
<table id="employee_grid" class="table" width="100%" cellspacing="0">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Salary</th>
<th>Age</th>
</tr>
</thead>
<tbody id="emp_body">
</tbody>
</table>
</div>
Ajax (binding column with element of HTML table):
$(document).ready(function(){
/* Handling get employee */
function get_employee() {
$.ajax({
type : 'GET',
url : 'response.php?action=list',
success : function(response){
response = JSON.parse(response);
var tr;
$('#emp_body').html('');
$.each(response, function( index, emp ) {
tr = $('');
tr.append("" + emp.id + "");
tr.append("" + emp.employee_name + "");
tr.append("" + emp.employee_salary + "");
tr.append("" + emp.employee_age + "");
var action =
"<div class='btn-group' data-toggle='buttons'>";
action += "<a href='#' target='_blank' class='btn btn-warning btn-xs' data-toggle='modal' data-target='#edit_model'>Edit</a>";
action += "<a href='#' target='_blank' class='btn btn-danger btn-xs'>Delete</a></div>";
tr.append(action);
$('#emp_body').append(tr);
});
}
});
}
//initialize method on load
function init() {
get_employee();
}
init();
});
PHP (query data from PostgreSQL)
<?php
include("connection.php");
$params = $_REQUEST;
$action = isset($params['action']);
$params['action'] !='' ? $params['action'] : 'list';
$empCls = new Employee();
switch($action) {
case 'list':
$empCls->getEmployees();
break;
default:
return;
}
class Employee {
protected $conn;
protected $data = array();
function __construct() {
$db = new dbObj();
$connString = $db->getConnstring();
$this->conn = $connString;
}
function getEmployees() {
$sql = "SELECT * FROM employee";
$queryRecords = pg_query($this->conn, $sql) or die("error to fetch employees data");
$data = pg_fetch_all($queryRecords);
echo json_encode($data);
}
}
?>
You need add <tr> & <td> tag as well while appending the responses to your table.
Changes you can add in your current code :
var tr = $('<tr></tr>'); //tr tag
//appending td >>
tr.append("<td>" + emp.id + "</td>");
tr.append("<td>" + emp.employee_name + "</td>");
tr.append("<td>" + emp.employee_salary + "</td>");
tr.append("<td>" + emp.employee_age + "</td>");
Demo Code :
var response = [{
"id": 1,
"employee_name": "xyz",
"employee_salary": 3444,
"employee_age": 23
},
{
"id": 2,
"employee_name": "xyz2",
"employee_salary": 34442,
"employee_age": 9
},
{
"id": 3,
"employee_name": "xyz3",
"employee_salary": 34443,
"employee_age": 2
}
] //this is dummy data
$(document).ready(function() {
/* Handling get employee */
function get_employee() {
/* $.ajax({
type: 'GET',
url: 'response.php?action=list',
success: function(response) {
response = JSON.parse(response);*/
$('#emp_body').html('');
$.each(response, function(index, emp) {
var tr = $('<tr></tr>'); //tr tag
//appending td >>
tr.append("<td>" + emp.id + "</td>");
tr.append("<td>" + emp.employee_name + "</td>");
tr.append("<td>" + emp.employee_salary + "</td>");
tr.append("<td>" + emp.employee_age + "</td>");
var action =
"<td><div class='btn-group' data-toggle='buttons'>";
action += "<a href='#' target='_blank' class='btn btn-warning btn-xs' data-toggle='modal' data-target='#edit_model'>Edit</a>";
action += "<a href='#' target='_blank' class='btn btn-danger btn-xs'>Delete</a></div></td>";
tr.append(action);
$('#emp_body').append(tr);
});
/*}
});*/
}
//initialize method on load
function init() {
get_employee();
}
init();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-6" style="padding-top:50px;">
<table id="employee_grid" class="table" width="100%" cellspacing="0">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Salary</th>
<th>Age</th>
<th>Action</th>
</tr>
</thead>
<tbody id="emp_body">
</tbody>
</table>
</div>

how to clear data of a table before each ajax call

Table data is not cleared after each ajax call. New data is appended below the previous data
$('#show_data').remove();
I have tried this but its not working
View
<table id="example2" class="table table-bordered table-hover">
<thead>
<tr>
<th>Title</th>
<th>Description</th>
<th>Date</th>
<th>Time</th>
<th>Action</th>
</tr>
</thead>
<tbody id="show_data">
</tbody>
</table>
Script
<script>
$(document).ready(function () {
//Date picker
$('#datepicker').datepicker({
autoclose: true,
format: 'yyyy-mm-dd',
});
$("#datepicker").attr("autocomplete", "off");
$(document).on('submit','#myform',function(){
event.preventDefault();
var date = $('#datepicker').val();
console.log(date);
$('#show_data').remove();
$.ajax({
type:"POST",
url:"<?php echo base_url().'admin/Dashboard/get_blog'; ?>",
data:{date:date},
dataType: "json",
success:function(data) {
console.log(data[0].blog_id);
let i;
for(i=0;i<data.length;i++){
$('#show_data').append('<tr><td>' + data[i].article_name + '</td>' +
'<td>' + data[i].description + '</td>' +
'<td>' + data[i].date + '</td>' +
'<td>' + data[i].time + '</td>' +
'</tr>');
}
},
error: function() {
alert("oops...");
},
});
});
});
</script>
Present Output
Input-> 2019-05-25 -> Submit
Output-> Data 1
Data 2
Input-> 2019-05-24 -> Submit
Output-> Data 1
Data 2
Data 3
Expected Output
Input-> 2019-05-25 -> Submit
Output-> Data 1
Data 2
Input-> 2019-05-24 -> Submit
Output-> Data 3
Its because you append your response to previous data. Try this way
$.ajax({
type:"POST",
url:"<?php echo base_url().'admin/Dashboard/get_blog'; ?>",
data:{date:date},
dataType: "json",
success:function(data) {
console.log(data[0].blog_id);
let i;
let html= '';
for(i=0;i<data.length;i++){
html += '<tr><td>' + data[i].article_name + '</td>' +
'<td>' + data[i].description + '</td>' +
'<td>' + data[i].date + '</td>' +
'<td>' + data[i].time + '</td>' +
'</tr>');
}
$('#show_data').html(html);
},
error: function() {
alert("oops...");
},
});
You can try change code
$('#show_data').remove();
to
$('#show_data').empty();
empty() function will clear content of the element. Docs is here https://api.jquery.com/empty/

Display data in table on ajax success [duplicate]

This question already has answers here:
jQuery parse JSON multidimensional array
(2 answers)
Closed 3 years ago.
I am submitting the form from ajax, and after ajax success i want to display all data in table tr td.
Below is my response which i got on ajax success and i want to load inside table on ajax success, but its displaying blank table.
{"raildata":null,"killdata":[{"id":146,"acct_id":1885,"AcctNo":"UP2357"},{"id":145,"acct_id":1885,"AcctNo":"UP2357"}]}
Below is my jquery ajax code which i tried, but its not displaying data after form submit on success.
$(document).ready(function(){
$('#killfrm').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '<?= Router::url(['controller' => 'Killsheets', 'action' => 'addKillsheet']) ?>',
data: $('form').serialize(),
beforeSend: function(){
$('#ibox1').children('.ibox-content').toggleClass('sk-loading');
},
success: function(response) {
var trHTML = '';
$(response).each(function (i,value) {
trHTML += response.killdata.map(function(killdata) {
return '<tr class="gradeA"><td>' + killdata.id + '</td><td>' + killdata.AcctNo + '</td></tr>';
});
trRailHTML += response.raildata.map(function(raildata) {
return '<tr class="gradeA"><td>' + raildata.rail_no + '</td><td>' + raildata.scale_no + '</td><td><button title="View" class="btn btn-default btn btn-xs tblbtn">View</button></td></tr>';
});
});
$('#txtcount').val(sum);
$('#listRail').html(trRailHTML);
$('#listKill').html(trHTML);
},
error: function(response) {
console.log(response);
}
});
});
});
Below is my HTML table
<table class="table table-bordered">
<thead>
<tr>
<th>Sheet#</th>
<th>Acc #</th>
<th>Action</th>
</tr>
</thead>
<tbody id="listKill"> </tbody>
</table>
you can pass $.each:
script:
$(document).ready(function(){
$('#killfrm').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '<?= Router::url(['controller' => 'Killsheets', 'action' => 'addKillsheet']) ?>',
data: $('form').serialize(),
beforeSend: function(){
$('#ibox1').children('.ibox-content').toggleClass('sk-loading');
},
success: function(response) {
let trHTML = '';
let killData = response.killdata;
let raildata = response.raildata;
$.each(killData, function(kill) {
let killid = kill.id;
let killacct_id = kill.acct_id;
let killAcctNo = kill.AcctNo;
trHTML += '<tr>';
trHTML += '<td>'+killid+'</td>';
trHTML += '<td>'+killacct_id+'</td>';
trHTML += '<td>'+killAcctNo+'</td>';
trHTML += '</tr>';
});
$('#listRail').html(raildata);
$('#listKill').html(trHTML);
},
error: function(response) {
console.log(response);
}
});
});
});
you get result html trHTML in id of #listKill:
html:
<table class="table table-bordered">
<thead>
<tr>
<th>Sheet#</th>
<th>Acc #</th>
<th>Action</th>
</tr>
</thead>
<tbody id="listKill">result goes here </tbody>
</table>
you can get any response data from response.objectkey = get value
for get json data in ajax response you need to pass ajax options :
dataType:"json"
go with below example:
$.ajax({
type: 'post',
url: 'Your Url',
data: $('form').serialize(),
dataType:'json',
success: function(response) {
response == here you get object you can get any value by object key
}
});
your json response:
{"raildata":null,"killdata":[{"id":146,"acct_id":1885,"AcctNo":"UP2357"},{"id":145,"acct_id":1885,"AcctNo":"UP2357"}]}
you can get result by using response variable like below
console.log(response.killdata);
console.log(response.raildata);
try above if you get any help
Table body is appended like this:
Assin id to your table
<table class="table table-bordered" id='my_table'>
Add this row to add the new rows
$("#my_table tbody").append(trHTML);

How send data to php with ajax on button click

i have products on my website and i made ajax call to insert product to shopping cart, but there is problem with clicking button. when i click on first product in list everything works but other product buttons do not react
<?php foreach ($products as $product):?>
<?php if($product['kateg'] == "men"):?>
<h5 style="color: #0669b4; min-height: 70px;"><?php echo $product['dasax']?></h5>
<p style="text-align: left; text-decoration: overline">Old price: <strong><span style="text-decoration: line-through"><?php echo round($product['fasi1'], 2)?> GEL</span></strong><br></p>
<p style="text-align: left">New Price: <strong><?php echo round($product['fasi2'], 2)?> GEL</strong><br></p>
<input type="hidden" value="<?php echo $product['id']?>" id="product_id">
<input type="hidden" value="<?php echo $product['dasax']?>" id="product_name">
<input type="hidden" value="<?php echo $product['fasi2']?>" id="product_price">
</a>
<button class="btn btn-primary" type="submit" id="add_to_cart">Add</button>
<?php endif;?>
<?php endforeach;?>
<script>
$(document).ready(function () {
$('#add_to_cart').click(function () {
var product_id = $("#product_id").val();
var product_name = $("#product_name").val();
var product_price = $("#product_price").val();
$.ajax({
url: "/uketesi/index",
method: "POST",
dataType: "json",
data: {
product_id:product_id,
product_name:product_name,
product_price:product_price,
},
success:function (data) {
alert("produqti warmatebit daemata")
$("#კალათა").html("<table id=\"example2\" class=\"table table-bordered table-hover\">" +
"<thead>" +
"<tr>" +
"<th>დასახელება</th>" +
"<th>ფასი</th>" +
"<th>იდენტიფიკატორი</th>" +
"</tr>" +
"<tr>" +
"<td>" + product_name + "</td>" +
"<td>" + product_price + "</td>" +
"<td>" + product_id + "</td>" +
"</tr>" +
"</thead>" +
"</table>");
}
});
});
});
</script>
I figured out how to solve the problem above, i have another question how can i add multiple products with this code. for now i only can add one product when i click on another product the old one dissepears.
You can get the data from data-*="" attribute on the button. So no need hidden inputs. For the click event you should use class name. Other case ID wont be unique. Please try following code.
<?php foreach ($products as $product):?>
<?php if($product['kateg'] == "men"):?>
<h5 style="color: #0669b4; min-height: 70px;"><?php echo $product['dasax']?></h5>
<p style="text-align: left; text-decoration: overline">Old price: <strong><span style="text-decoration: line-through"><?php echo round($product['fasi1'], 2)?> GEL</span></strong><br></p>
<p style="text-align: left">New Price: <strong><?php echo round($product['fasi2'], 2)?> GEL</strong><br></p>
</a>
<button class="btn btn-primary" type="submit" class="add_to_cart" data-id="<?php echo $product['id']?>" data-name="<?php echo $product['dasax']?>" data-price="<?php echo $product['fasi2']?>">Add</button>
<?php endif;?>
<?php endforeach;?>
<script>
$(document).ready(function () {
$('.add_to_cart').click(function () {
var product_id = $(this).data('id');
var product_name = $(this).data('name');
var product_price = $(this).data('price');
$.ajax({
url: "/uketesi/index",
method: "POST",
dataType: "json",
data: {
product_id:product_id,
product_name:product_name,
product_price:product_price,
},
success:function (data) {
}
});
});
});
</script>
Now that we have the form, and jQuery included in our document, we need to store it’s values in 2 variables, ( val1 and val2 ) so then we can pass it to the PHP file to process it.
$('#button').click(function() {
var val1 = $('#text1').val();
var val2 = $('#text2').val();
$.ajax({
type: 'POST',
url: 'process.php',
data: { text1: val1, text2: val2 },
success: function(response) {
$('#result').html(response);
}
});
});
As you can see in the code above, we create a .click event. This means that when the button with the ID of #button is click, out function will run. Then we get the value of each text field and store it in val1 and val2.

Auto complete function is not working in dynamic data input table rows

I have created a dynamic data input table. And I have added auto complete function to it which working fine.But the problem is if I added new row to my dynamic table auto complete function is not working on that row.How to solve this?
********HTML********
<table class="table table-bordered" id="curd_table">
<tr>
<th width="15%">User ID</th>
<th width="20%">Name</th>
<th width="20%">NIC</th>
<th width="20%">Amount</th>
<th width="25%">Pay date (YYYY-MM-DD)</th>
<th></th>
</tr>
<tr>
<td contenteditable="true" class="uid " name="uid" id="uidr"></td>
<td contenteditable="true" class="name " name="name" id="namer"></td>
<td contenteditable="true" class="nic" name="nic" id="nicr"></td>
<td contenteditable="true" class="amount"></td>
<td contenteditable="true" class="paydate"></td>
<td></td>
</tr>
</table>
**** JS functions****
$(document).ready(function(){
var count=1;
$('#add').click(function(){
count=count+1;
var html_code ="<tr id='row"+count+"'>";
html_code +="<td contenteditable='true' class='uid' name='uid' id='uidr'></td>";
html_code +="<td contenteditable='true' class='name' name='name' id='namer'></td>";
html_code +="<td contenteditable='true' class='nic' name='nic' id='nicr'></td>";
html_code +="<td contenteditable='true' class='amount'></td>";
html_code +="<td contenteditable='true' class='paydate'></td>";
html_code +="<td><button type='button' name='remove' data-row='row"+count+"' class='btn btn-danger btn-xs remove'>-</button></td>";
html_code +="</tr>";
$('#curd_table').append(html_code);
});
$('#uidr').autocomplete({
source: function( request, response ) {
$.ajax({
url : '../control/autoComp.php',
dataType: "json",
method: 'POST',
data: {
id_startsWith: request.term,
type: 'pay_table',
row_num : 1
},
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[0],
value: code[0],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 0,
select: function(event, ui ) {
var names = ui.item.data.split("|");
$('#namer').text(names[1]);
$('#nicr').text(names[2]);
}
});
});
auto complete not working on marked with red arrows.Those are dynamically added rows.
You should change your jquery selector to select class, not id(unique value).
and you missed '})' closing '$(document).ready(function(){'
EDIT:
If you add the component dynamically, you should use on() function to bind the event to the newly added component.
$(document).on('autocomplete','.uid',function(){
source: function( request, response ) {
$.ajax({
url : '../control/autoComp.php',
dataType: "json",
method: 'POST',
data: {
id_startsWith: request.term,
type: 'pay_table',
row_num : 1
},
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[0],
value: code[0],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 0,
select: function(event, ui ) {
var names = ui.item.data.split("|");
$(this).nextAll('.name').text(names[1]);//or just next()
$(this).nextAll('.nic').text(names[2]);//or just next().next()
}
});

Categories