Show results for checkbox selected items - javascript

I am calling Api : $url = 'https://plapi.ecomexpress.in/track_me/api/mawbd/?awb=awbnumber&order=' . $orderrecords[$k]["order_id"] . '&username=admin&password=admin123'; and fetching Status results of all Order IDS & displaying in php page when we refresh php page.
But I dont want to Call APi everytime when we refresh page. But When i select Order IDs through checkbox, than when i click on button "Show Status" , than only i want to Call Api & update the Selected Order IDs status in web page.
Url Output
PHP
<?php
$tabindex=1;
function checkecomstatus($orderid)
{
$data['username']='admin';
$data['password']='ouhk78epe34csmed46d';
$data['awb']=$orderid;
$url = 'https://plapi.ecomexpress.in/track_me/api/mawbd/?awb=awbnumber&order='.$orderid.'&username=admin&password=ouhk78epe34csmed46d';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);
curl_close($ch);
$res = explode("\n",$output);
if ( ! isset($res[13]))
{
$res[13] = null;
}
$status = str_replace('</field>.','',$res[13]);
$statusfinal = str_replace('<field type="CharField" name="status">','',$status);
if($statusfinal!='')
{
$sqlecom = "UPDATE do_order set in_transit='".$statusfinal.".',tconformed_by='Ecom' where order_id=".$orderid;
$db_handleecom = new DBController();
$resultecom = $db_handleecom->executeUpdate($sqlecom);
}
return $statusfinal;
}
?>
<p><button type= "button" >Show Status</button></p>
<table class="tbl-qa" border="1">
<thead>
<tr>
<th class="table-header">ID</th>
<th class="table-header">ORDERID</th>
<th class="table-header">Status</th>
</tr>
</thead>
<tbody id="table-body">
<?php
if(!empty($orderrecords))
{
foreach($orderrecords as $k=>$v)
{?>
<tr class="table-row" id="table-row-<?php echo $orderrecords[$k]["id"]; ?>" tabindex="<?php echo $tabindex;?>">
<td><input type="checkbox" onclick="assignorderids('<?php echo $orderrecords[$k]["order_id"]; ?>')" name="assigneeid" id="assigneeid-<?php echo $orderrecords[$k]["order_id"]; ?>" value="<?php echo $orderrecords[$k]["order_id"]; ?>"></td>
<td><?php echo $orderrecords[$k]["order_id"]; ?></td>
<td><?php echo checkecomstatus($orderrecords[$k]["order_id"]);?></td>
</tr>
<?php
$tabindex++;
}
}?>
</tbody>
</table>
<input type="hidden" name="ordercheckallIDs" id="ordercheckallIDs" value="<?php echo $ordercheckall;?>"/>
Javascript
function assignallorderids()
{
var checkstatus=$("#checkall").is(":checked");
if(checkstatus==true)
{
var id=document.getElementById("ordercheckallIDs").value;
document.getElementById("orderids").value=id;
$("input:checkbox[name='checkassigneeid']").prop('checked',true);
}
else
{
$("input:checkbox[name='checkassigneeid']").prop('checked',false);
document.getElementById("orderids").value='';
}
}
function assignorderids(oid)
{
var checkstatus=$("#assigneeid-"+oid).is(":checked");
var morderId =document.getElementById("orderids").value;
if(checkstatus==false)
{
var arrayorder = JSON.parse("[" + morderId + "]");
document.getElementById("orderids").value='';
for (var i = 0; i < arrayorder.length; i++) {
var orderstatusValue=arrayorder[i];
if(orderstatusValue!=oid){
if (document.getElementById("orderids").value=='')
{
document.getElementById("orderids").value=orderstatusValue;
}
else
{
var newvalue=document.getElementById("orderids").value;
document.getElementById("orderids").value=newvalue+","+orderstatusValue;
}
}
}
}
else
{
if(morderId=='')
{
document.getElementById("orderids").value=oid;
}
else
{
document.getElementById("orderids").value=morderId+","+oid;
}
}
}

This seems like you don't know about jQuery basics. If you can grab data from API but is firing on refresh then put it in trigger fire approach. something like if you have fetchData() function which fetches data from API as per the checkbox then don't fire it directly instead do something like
$('#fetch-button-id').click(function() { fetchData(); });
and if you have just put fetch data from api code directly into document then add those code into function then call it.

Related

Call php function from Javascript inside php file

I have a php file that shows all the user details in table form. On click of edit, I am want to set something from DB to local storage using javascript.
So to show a table of users I am doing the following:
<table cellspacing="0">
<tr>
<th>ID</th>
<th>Name</th>
<th>View</th>
<th>Edit</th>
</tr>
<?php
$count=1;
$sel_query="Select * from user_details ORDER BY id desc;";
$result = mysqli_query($con,$sel_query);
while($row = mysqli_fetch_assoc($result)) {
?>
<tr>
<td align="center"><?php echo $count; ?>
<td align="center"><?php echo $row["docname"]; ?>
<td align="center">View</td>
<td align="center">Edit</td>
</tr>
<?php $count++; } ?>
</table>
The above shows the records in the table perfectly.
Now when edit is clicked, I call a javascript function. (This is called before I click on edit? I am not sure why?)
<script type="text/javascript">
function handleLinkClick (e) {
e.preventDefault ();
var id = e.target.href.split ("?").pop ();
var key = <?php echo add(id);?>
console.log(key);
localStorage.setItem ("myKey", key);
//window.location.href = e.target.href;
}
</script>
Now from javascript function, I am trying to call a PHP function a variable is sent from javascript to PHP function to fetch corresponding records details and return that data to javascript, below is the PHP function:
function add($id){
$sel_query="select * from user_details where id=$id";
$result = mysqli_query($con,$sel_query);
while($row = mysqli_fetch_assoc($result))
{
$key = $row["rawText"];
echo $key;
}
return $key;
}
?>
I don't see any results. I am not sure why I am not getting any results? Can some give me the right syntax or correct me?
Thanks!

Insert multiple records in single checkbox in codeigniter?

I've two different table, 1st is draft_table, and 2nd is fix_table, each table have same fields ( product & price )
i want to make data from draft_table, can be save to fix_table with checkbox, so just selected data will save to fix_table.
i've code like this :
AJAX
<script>
$(function(){
$("a.paid").click(function(){
if(confirm("Are you sure want save this?"))
{
id_array=new Array()
i=0;
$("input.chk:checked").each(function(){
id_array[i]=$(this).val();
i++;
})
$.ajax({
url:'<?php echo base_url(); ?>fix_data/set',
data:"kode="+id_array,
type:"POST",
success:function(respon)
{
if(respon==1)
{
window.parent.location.reload(true);
}
}
})
}
return false;
})
})
</script>
Views :
<?php
foreach($data_get->result_array() as $dp)
{
?>
<tr><td><input type="checkbox" name="chk[]" class="chk" value="<?php echo $dp['id_draft']; ?>" /></td>
<td><?php echo $dp['product']; ?></td>
<td><?php echo $dp['price']; ?></td>
</td></tr>
<?php
}
?>
Controller :
public function set_stts()
{
if($this->session->userdata('logged_in')!="")
{
$id_get = $this->input->post('kode');
$dt = $this->db->get_where("tbl_draft",$id_get)->row();
$product = $dt->product;
$price = $dt->price;
if ($this->input->post('kode')) {
$query = $this->db->query("INSERT INTO tbl_fix (product,price) VALUES (".$product.",".$price.")");
}
if($query){
echo 1;
}
else{
echo 0;
}
}
else
{
header('location:'.base_url().'dashboard_item');
}
}
After i Click submit in draft form, nothing happen, is there anyone may help me with this case?
Thank you
maybe you can change your controller like this :
public function set()
{
if($this->session->userdata('logged_in')!="")
{
$id_get = $this->input->post('kode');
$quer = $this->db->query("select * from tbl_draft WHERE id IN (".$id_get.")");
if ($this->input->post('kode')) {
foreach($quer->result_array() as $dp)
{
$a = $dp['product'];
$b = $dp['price'];
$query = $this->db->query("INSERT INTO tbl_fix (product,price) VALUES
('".$a."','".$b."')");
}
}
if($query){
echo 1;
}
else{
echo 0;
}
}
else
{
header('location:'.base_url().'dashboard_item');
}
}

how can I send post data in php programatically?

I need to send post data to another page programatically.
I have 2 DateTime in Database I want to compare these DateTimes. and if one of them is bigger than another automatically send post data to another page.
this is simple code:
require('connect.php');
$sql = 'SELECT * FROM POSTS ORDER BY POSTDATETIME ASC';
$result = $conn->query($sql);
if($result->num_rows>0)
{
while($row=$result->fetch_assoc())
{
echo $row["ID"].".".$row["PostDateTime"]."<br/>";
$text = $row["Text"];
$d = new DateTime("now");
$d1 = new DateTime($row["PostDateTime"]);
if($d>$d1)
{
// Send Post Data to another page;
}
else
{
echo "false<br/>";
}
}
}
I googled but there is no way to send automatically post data without any form or ajax .
ajax needs to some event occurs.
And I don't have any Idea how to do that . I will appreciate any tips.
You could use CURL to send a post request.
require('connect.php');
$sql = 'SELECT * FROM POSTS ORDER BY POSTDATETIME ASC';
$result = $conn->query($sql);
if($result->num_rows>0)
{
while($row=$result->fetch_assoc())
{
echo $row["ID"].".".$row["PostDateTime"]."<br/>";
$text = $row["Text"];
$d = new DateTime("now");
$d1 = new DateTime($row["PostDateTime"]);
if($d>$d1)
{
$ch = curl_init('http://www.linktoyourotherpage.com');
curl_setopt($ch, CURLOPT_POSTFIELDS, $row);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
}
else
{
echo "false<br/>";
}
}
}
The only way to achieve what you're doing is with a intermediate page that sends the user to Page C. Here's a small/simple snippet on how you can achieve that:
<?php
if($d>$d1) { ?>
<form id="myForm" action="Page_C.php" method="post">
<?php
foreach ($_POST as $a => $b) {
echo '<input type="hidden" name="'.htmlentities($a).'" value="'.htmlentities($b).'">';
}
?>
</form>
<script type="text/javascript">
document.getElementById('myForm').submit();
</script>
<?php } else {
echo "false<br/>";
}
?>
store the data in a global variable say for example $_SESSION and redirect to another page ... session start and use the global variable.

Codeigniter: Using button click to view more data from database

Ideally, In my database table, I have username, name, location, email.
Now I have a table in my view.php where it returns value from the database.
Table header consists of name, username, and more info where name and username comes directly from the database while more info will have a button for each row. When the button is clicked, it should display location and email in a pop up.
Question: How can I retrieve location and email of a user when the button is clicked specifically?
Example:
user1, joe doe, [button] -> user1 location, user1#email.com
user2, jay doe, [button] -> user2 location, user2#email.com
Codes: p.s. code includes pagination.
controller.php
function pagination() {
$config = array();
$config['base_url'] = base_url() . "controller/pagination";
$total_row = $this->model->record_count();
$config["total_rows"] = $total_row;
$config["per_page"] = 8;
$config['uri_segment'] = 3;
/* $config['use_page_numbers'] = TRUE; */
$config['num_links'] = $total_row;
$config['cur_tag_open'] = ' <a class="current">';
$config['cur_tag_close'] = '</a>';
$config['next_link'] = '<span aria-hidden="true">»</span>';
$config['prev_link'] = '<span aria-hidden="true">«</span>';
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data["results"] = $this->model->fetch_data($config["per_page"], $page);
$str_links = $this->pagination->create_links();
$data["links"] = explode(' ', $str_links);
// View data according to array.
$this->load->view("view-employees", $data);
}
model.php
public function record_count() {
return $this->db->count_all('users');
}
public function fetch_data($limit, $start) {
$this->db->limit($limit, $start);
$query = $this->db->get('users');
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
view.php
<tr>
<th>username</th>
<th>name</th>
<th>more</th>
</tr>
<tr>
<?php foreach ($results as $data) { ?>
<td><?php echo $data->username; ?></td>
<td><?php echo $data->name; ?></td>
<td>
<button type='button' class='btn'>
<?php echo $data->location;
echo $data->email;
?>
</button>
</td>
</tr>
You could write a Codeigniter-controller which will return email and location
Then you write Javascript-functions which will call this controller to retrieve the data asJSON-Data
Both, writing a controller which returns JSON and an example how to call this controller from JS can be found here:
Code Igniter - How to return Json response from controller
Try like this..
MODEL:
public function record_count() {
return $this->db->count_all('users');
}
public function fetch_data($limit, $start) {
$this->db->limit($limit, $start);
$query = $this->db->get('users');
if ($query->num_rows() > 0) {
return $query->result_array();
}
}
return false;
}
View:
<tr>
<th>username</th>
<th>name</th>
<th>more</th>
</tr>
<tr>
<?php foreach ($results as $data) { ?>
<td><?php echo $data['username']; ?></td>
<td><?php echo $data['name']; ?></td>
<td>
<button type='button' class='btn'>
<?php echo $data['location'];
echo $data['email'];
?>
</button>
</td>
<?php } ?>
</tr>

ajax to receive data from database request does not work

I'm a really beginner in the ajax domain, and I really need help.
In fact I have done a query to receive some data from a database.
Here on the header I have:
<script type="text/javascript">
<?php if(isset($_GET['p']) AND $_GET['p']=='create_dossier') {?>
function writeInDiv(text){
var objet = document.getElementById('code_client');
objet.innerHTML = text;
}
function ajax()
{
var xhr=null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("GET", "ajaxclient.php?code_client=<?php echo $_GET['code_client'] ; ?>", false);
xhr.send(null);
writeInDiv(xhr.responseText);
setInterval("ajax()",5000);
}
<?php }?>
</script>
on the page ajaxclient.php I have the following code:
<?php require_once('Connections/localhost.php'); ?><?php mysql_select_db( $database_localhost ); ?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
</head>
<body>
<table width="100%" border="0" id="box-table-a">
<tr>
<th scope="col" width="15%">CODE CLIENT</th>
<th scope="col" width="15%">RAISON SOCIALE</th>
<th scope="col" width="55%">ADRESSE </th>
<th scope="col" width="15%">ACTION</th>
</tr>
<?php
$code_client=$_GET["code_client"];
$sql="SELECT * FROM `client` INNER JOIN `adresse_client` ON `client`.`code_client` = `adresse_client`.`code_client` WHERE `client`.`code_client`='".$code_client."'";
if (mysql_errno() <> 0)
{
echo mysql_error(),'<br>',$sql,'<br>';
die();
}
$result=mysql_query($sql);
while($donnees=mysql_fetch_assoc($result))
{?>
<tr>
<td><?php echo $donnees['code_client'] ; ?></td>
<td><?php echo $donnees['raison_sociale'] ; ?></td>
<td><p align="left"> <?php echo $donnees['rue'].'<br>'.$donnees['complement1'].'<br>'.$donnees['complement2'].'<br>'.$donnees['code_postal'].' - '.$donnees['ville'].'<br>'.$donnees['pays'] ; ?></p></td>
<td><a href="index.php?p=create_dossier2&code_client=<?php echo $data['code_client'] ; ?>"><img src="images/001_18.gif" width="24" height="24" /></td>
</tr>
<?php }
?></table>
</body>
</html>
The page called create_dossier.php contain:
<form action="#" method="get"><fieldset>
<legend>CRÉANCIER</legend>
<br />
<label>Raison sociale:</label><input type="hidden" name="p" value="create_dossier" /> <input type="text" name="code_client" onkeypress="form.submit()" /></fieldset><p align="center"><input type="submit" name="enreg" value="Chercher !" /></form>
What I would like is to display the data without sending the page and the thing is that it always send the form before returning any data. For that I do not need ajax.
I really do not know what wrong and how to correct it.
You should returning the result of query as XML or JSON and filling the tables with XML in calling file.
This is an example php.file (Need to convert to PDO)
require("dbinfo.php");
// Get parameters from URL
$code_client=$_GET["code_client"];
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
// Opens a connection to a mySQL server
$connection=mysql_connect ($host, $username, $password);
if (!$connection) {
die("Not connected : " . mysql_error());
}
// Set the active mySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ("Can\'t use db : " . mysql_error());
}
// Search the rows in the markers table
$sql="SELECT * FROM `client` INNER JOIN `adresse_client` ON `client`.`code_client` = `adresse_client`.`code_client` WHERE `client`.`code_client`='".$code_client."'";
if (mysql_errno() <> 0)
{
echo mysql_error(),'<br>',$sql,'<br>';
die();
}
$result=mysql_query($sql);
while($donnees=mysql_fetch_assoc($result))
}
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
$node = $dom->createElement("client");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("'code_client'", $row['code_client']);
//$newnode->setAttribute("xxx", $row['xx']); list all other
}
}
echo $dom->saveXML();
?>
in fact, you should prevent form submitting like this:
onclick="return doSomeAction();"
function doSomeAction() {
// create XHR object
// send data
// handle response
return false;
}
doSomeAction() = ajax() in your case
don't forget to return false

Categories