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);
Related
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;
}
}
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);
}
}
}
});
});
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
I have a function that populates the DataTable when the document is ready.
$(document).ready(function()
{
var $dataTable = $('#example1').DataTable({
"ajax": 'api/qnams_all.php',
"dataType": "json",
"bDestroy": true,
"stateSave": true
});
// this portion reloads the datatable without refreshing the page
setInterval(function() {
$dataTable.ajax.reload();
}, 60000);
}
So now I want to add a search feature. It would basically re-populate the DataTable with the search data returned from the server.
Directly below is the jQuery that retrieves the parameters entered by the user:
$('#searchSubmit').on('click', function()
{
var searchbooking = $('#searchbooking').val();
var searchquote = $('#searchquote').val();
$.ajax({
url:'api/qnams_all.php',
type:"POST",
data:{searchbooking: searchbooking, searchquote: searchquote},
contentType:"application/x-www-form-urlencoded; charset=UTF-8",
dataType:"json"
}).done(function(response){
console.log(response.data)
}).fail(function(){
alert('error');
}).always(function(){
alert('done');
});
});
Here is the PHP process found in api/qnams_all.php:
<?php
include("../include/database.php");
include("../include/sessions.php");
$_SESSION['where'] = "";
$searchbooking = strip_tags(mysqli_real_escape_string($dbc, trim(strtoupper($_POST['searchbooking']))));
$searchquote = strip_tags(mysqli_real_escape_string($dbc, trim(strtoupper($_POST['searchquote']))));
// build the WHERE clause
if($searchbooking != ""){
$_SESSION['where'] = "booking = '".$searchbooking."'";
}
if($searchquote != ""){
if( $_SESSION['where'] != "" )
$_SESSION['where'] .= " AND ";$_SESSION['where'] .= "quote = '".$searchquote."'";
}
// check if WHERE is blank
if($_SESSION['where'] == ""){$where = "where TLI_COMPLETE = 'N'";}
else{$where = $_SESSION['where'];}
// run the query
$select = "SELECT
CONCAT('\"',COALESCE(booking,''),'\"')
,CONCAT('\"',COALESCE(quote,''),'\"')
FROM
searchTable " . $where . "";
$query = mysqli_query($dbc, $select) or die(mysqli_error());
$resnum = mysqli_num_rows($query);
echo "{\"data\":[";
$i = 1;
while($row = $query->fetch_assoc())
{
echo "[";
echo implode(', ', $row);
echo "]";
if($i < $resnum){
echo ",";
}
$i++;
}
}
echo "]}";
mysqli_free_result($query);
?>
The PHP process above works perfectly with the $(document).ready() function.
My question is: how can I manipulate my code so that the search functions works with the ready() function?
Right now, the search function is located outside of the ready() function. Can I apply the search function within the ready() function? If so, how would the AJAX call look like?
Currently, it reads:
"ajax": 'api/qnams_all.php'
If I am able to add the search to the ready() function, would this AJAX call change?
To put it in one question, how can I add the search feature to the ready() function so that I can initially display data, and then repopulate the data if the user decides to search for a record?
You have to keep 2 copies of the same code(ajax part)
In document.ready with async:false in ajax call.(Will load the search results when the page opens).
The original place where it is now i.e inside the onClick function.(For the default behaviour).
That's because you need to wrap your ajax call in an eventListener and here you are having to separate events.
I want to load more than 10 rows from my table with jQuery, but it's not working.
My php code: (...chat.php?load=archive)
} else if (isset($_GET["load"]) && $_GET["load"] == "archive") {
echo "<script type='text/javascript' src='includes/js/chatArchive.js'></script>";
$limit = (int)$_POST["limit"];
$result = mysql_query("SELECT * FROM `chat` ORDER BY `date` DESC LIMIT ".$limit.", 2");
if (mysql_num_rows($result)) {
while($db = mysql_fetch_array($result)) {
echo "..."; // My datas...
}
echo "<div style='text-align: center; margin: 10px 0 10px 0;'>\n";
echo "<input type='submit' value='Load more rows' class='loadMore'>\n";
echo "</div>\n";
}
}
My JS file: (chatArchive.js)
var limit = 50;
$(document).ready(function() {
$(".loadMore").click(function() {
limit += 10;
$.ajax({
url: "../../../system/functions/chat.php?load=archive",
type: "POST",
data: { "limit" : limit },
success: function() {
alert("Success...");
console.log(limit); // This displayed my console!!!
}
});
});
});
Can anyone point out the problem?
Function which is defined as a callback for success property has an argument, usually called data, which is the returned value from your script. So, you should change your success function as follows:
success: function(data) { // see data here
alert("Success...");
console.log(limit); // This displayed my console!!!
console.log( data ); // check what data contains
}
Also it's a good practice to add error callback, which will indicate that something bad happens:
$.ajax({
url: "../../../system/functions/chat.php?load=archive",
....
error: function() {
alert("Bad thing happenned!");
}
)};
your ajax method is POST but in your php script you check GET request
if (isset($_GET["load"]) && $_GET["load"] == "archive")
Change Your ajax method to GET