ajax to receive data from database request does not work - javascript

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

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!

Show results for checkbox selected items

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.

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>

Popup message cannot display new update records from php mysql

I've made a popup message with auto-refresh function, so every few minutes the popup will appear to display the records. And it worked.
The following is the JavaScript code that auto refreshes:
$(document).ready(function() {
setInterval(function() {
$('#rtnotice').load('plugins/notice/n_notice_invoice.php').fadeIn("slow");
}, 5000)
});
code of n_notice_invoice.php
<script>
$(document).ready(function(){
$("#hide").click(function(){
$("#noticearea").hide();
});
});
</script>
<?php
try{
require_once "../../config/c_config.php";
$db = dbConn::getConnection();
$timestamp = $_REQUEST['term'];
$sqlck = $db->prepare("SELECT COUNT(id_notice_alert) as ttlinv FROM str_notice_alert WHERE date_alert > '$timestamp'");
$sqlck->execute();
$resck = $sqlck->fetch(PDO::FETCH_ASSOC);
if($resck['ttlinv'] == '0')
{}else{
?>
<div id="noticearea">
<div id="modal">
<div class="modal-content">
<div class="header">
<div id="circle" align="center"><h1><?php echo $resck['ttlinv'];?></h1></div><div class="titlenotice"><h1>NOTICE ALERT<?php echo $timestamp; ?></h1></div>
<div class="break"></div>
</div>
<div class="copy">
<p>
<table width="100%" class="gridtable">
<tr><th>No</th><th>Name</th><th>Status</th><th>Location</th><th>Date</th></tr>
<?php
$sqll = $db->prepare("SELECT * FROM str_notice_alert");
$sqll->execute();
while($resl = $sqll->fetch(PDO::FETCH_ASSOC)){
?>
<tr><td align="center"><?php echo $resl['id_notice_alert']; ?></td><td><?php echo $resl['alert_name']; ?></td><td align="center"><?php echo $resl['alert_status']; ?></td><td align="center"><?php echo $resl['alert_location']; ?></td><td><?php echo $resl['date_alert']; ?></td></tr>
<?php } ?>
</table>
</p>
</div>
<div class="cf footer">
<button id="hide" class="btn">Close</button>
</div>
</div>
<div class="overlay"></div>
</div></div>
<?php
$sqltrunc = $db->prepare("TRUNCATE TABLE str_notice_alert");
$sqltrunc->execute();
}$db = null;}
catch (PDOException $e) {
echo "Connection Error " . $e->getMessage();
}
?>
After a popup message is displayed, it will display the file n_notice_invoice.php existing records and also delete the records via queries available. In any appearances. But the question is, why the records are not updated / changed. uUnless I refresh the file directly n_notice_invoice.php, and then auto-refresh displays the most recent data.
$timestamp = $_REQUEST['term'];
should be updated each time you call the page. You should load the page with Ajax passing $timestamp as a parameter instead of just loading it.
To get what you need can I suggest you to use long polling? PHP long polling or even better with node.js. For php for example the "server" page:
$timeStart = time();
// Create connection
$con = mysqli_connect('localhost','root','','polldb');
// Check connection
if (mysqli_connect_errno($con))
die ('Failed to connect to MySQL: ' . mysqli_connect_error() );
// select where item is new
if(isset($_POST['timestamp'])){
$timestamp = $_POST['timestamp'];
}else{
// get current database time
$row = mysqli_fetch_assoc(mysqli_query($con,'SELECT now() as now'));
$timestamp = $row['now'];
}
$sql = "SELECT * FROM `notification` WHERE timestamp > '$timestamp'";
$newData = false;
$notifications = array();
// loop while there is no new data and is running for less than 20 seconds
while(!$newData && (time()-$timeStart)<20){
// check for new data
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($result)){
$notifications[] = $row;
$newData = true;
}
// let the server rest for a while
usleep ( 500000 );
}
// get current database time
$row = mysqli_fetch_assoc(mysqli_query($con,'SELECT now() as now'));
$timestamp = $row['now'];
mysqli_close($con);
// output
$data = array('notifications'=>$notifications,'timestamp'=>$timestamp);
echo json_encode($data);
exit;
and the client:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(function(){
pullNotification();
});
function pullNotification(timestamp){
var data = {};
if(typeof timestamp!='undefined')
data.timestamp = timestamp;
$.post('longpoll.php',data,function(msg){
var newData = '';
for(i in msg.notifications){
newData+=msg.notifications[i].message+'\n';
}
if(newData!='')
alert(newData);
pullNotification(msg.timestamp);
},'json');
}
</script>
This will check for database updates and will pop them up. Every 20 seconds it will renew the request. Obviously you have to adapt it to your needs.
I believie your issue comes from cached request (in Browser on in ajax itself)
please try to disable ajax caching :
$(document).ready(function() {
setInterval(function() {
$.ajax({
url: "plugins/notice/n_notice_invoice.php",
cache: false
})
.done(function( data ) {
$('#rtnotice').html(data).fadeIn("slow");
});
}, 5000)
});

Posting dynamic arrays as distinct variables using JavaScript

Am trying to dynamically add the fields for subjects and the grades obtained, but am getting an error "Undefined index: subject in..." when posting those variables using java script.
Could there be something am missing with my posting mechanism. Notice that in the form data am not puting id="subject" to avoid picking the id for only one subject, and am using name="subject[]" to show an array, but I
dont seem to know how to represent this in the java script as we will see below.
form data as follows;
<tr>
<td colspan="6"><div align="center"><strong>
<p style="color:#930">Academic Qualification</p>
</strong></div></td>
</tr>
<?php
require_once("connection/connectPDO.php");
$sql="CALL sp_getSubjects()";
//Initiate and Call Stored Procedure Using PDO
$pdo = new PDOConfig();
$resultsSubject = $pdo->query($sql);
foreach($resultsSubject as $rowSubject)
{
?>
<tr>
<td width="35%" colspan="3"><div align="right"><?php echo $rowSubject['SubjectName']; ?>:<input name="subject[]" type="hidden" value="<?php echo $rowSubject['SubjectID']; ?>" /></div></td>
<td width="65%" colspan="3"><select name="grades[]" id="grades" class="validate[required]">
<option value="">--Select Grade--</option>
<?php
$sql="CALL sp_grabGrades()";
//Initiate and Call Stored Procedure Using PDO
$pdo = new PDOConfig();
$resultset = $pdo->query($sql);
foreach($resultset as $row)
{
?>
<option value="<?php echo $row['GradeObtainedID']; ?>"> <?php echo $row['Grade']; ?> </option>
<?php } ?>
</select></td>
<?php } ?>
</tr>
the form looks like this
Academic Qualification
English <--select-->
Biology <--select-->
Science <--select-->
the java script code is as follows;
$(document).ready(function(){
$("#submit").click(function(){
//if invalid do nothing
if(!$("#formD").validationEngine('validate')){
return false;
}
var vgrades = $("#grades").val();
var vsubject = $("#subject").val();
$.post("sendInitialApplication.php",
{
grades : vgrades,
subject : vsubject
/*Handles response from server*/
function(response){
alert(response);
});
alert("You are here");
});
});
the PHP code "sendInitialApplication.php" is as follows
<?php
$method = $_SERVER['REQUEST_METHOD'];
function connect(){
try{
$dbConn = new PDO('mysql:host=localhost; dbname=student', 'root', 'root');
$dbConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbConn;
}
catch(PDOException $e){
echo $e->getMessage();
}
}
/*Checks if method is HTTP POST*/
if(strtolower($method) == 'post'){
$grades = addslashes($_POST['grades']);
$subjects = addslashes($_POST['subject']);
try {
$dbHandler = connect();
$dbHandler->beginTransaction();
//Saving Various subjects with distinct grade obtained
foreach($subjects as $key => $subject)
{
$setIndexSubject = 'CALL sp_sendIndexSubject(:vSubjectID,:vGradeObtainedID)';
$stmt_subject = $dbHandler->prepare($setIndexSubject);
$stmt_subject->bindValue(':vSubjectID', $subject);
$stmt_subject->bindValue(':vGradeObtainedID', $grades[$key]);
$stmt_subject->execute();
$stmt_subject->closeCursor();
}
$dbHandler->commit();
echo "The Operation was Successful!!!!!!";
} catch (PDOException $e) {
$dbHandler->rollback();
die($e->getMessage());
}
}else{
echo "Oops! Make sure Method is POST";
}
?>
I'm expecting that $_POST['subject'] and $_POST['grades'] should be array. Than you cannot use $subjects = addslashes($_POST['subjects']), but $subjects = $_POST['subjects']. Calling addslashes on array throws PHP warning and returns NULL.
Edit:
I suggest modify logic of your code.
Input type hidden, with subject id, will not work, as you expects. Modify your list:
// ... obtaining subjects from db ...
foreach($resultsSubject as $rowSubject) {
?>
<tr>
<td>
<select name="grade[<?= $rowSubject['SubjectID']; ?>]">
<option value="">--Select Grade--</option>
<?php
// ... obtaining grades from db ...
foreach($resultset as $row) {
?>
<option value="<?php echo $row['GradeObtainedID']; ?>"> <?php echo $row['Grade']; ?> </option>
<?php
}
?>
</select>
</td>
</tr>
<?php
}
Than serialized form should return array:
grade = array (
subjectID1 => selectedGradeId,
subjectID2 => selectedGradeId,
...
)
And data processing in sendInitialApplication.php:
// prepare db transaction
$grades = $_POST['grade'];
foreach ($grades as $subject => $grade) {
$setIndexSubject = 'CALL sp_sendIndexSubject(:vSubjectID,:vGradeObtainedID)';
$stmt_subject = $dbHandler->prepare($setIndexSubject);
$stmt_subject->bindValue(':vSubjectID', $subject);
$stmt_subject->bindValue(':vGradeObtainedID', $grade);
$stmt_subject->execute();
$stmt_subject->closeCursor();
}
// close db transaction

Categories