Unable to catch data - php

I am passing data using J-Query and AJAX to res.php page:-
attempt.php (my main page from where the res.php is called)
$.ajax(
{
url: "res.php",
type: "POST",
data: data,
success: function (data)
{
var build_id='build_';
build_id += i;
alert(build_id);
$('#npc').append(data);
$('#build_id').attr('disabled','true');
var total = $("#build_id");
alert(total);
}
});
In the res.php page I am using the passed data to generate the query and retrieve data from the database and calculated the total value and display the total in a text box.
res.php
$i = mysql_real_escape_string($_POST['i']);
$query = "select * from ";
$query = $query . $building;
$query = $query . " where lvl=" . $level;
$query = $query . ";";
$result = mysql_query($query) or die('Error in Child Table!');
echo $i;
while( $data = mysql_fetch_assoc($result))
{
$total_res = $data['lumber'] + $data['clay'] + $data['iron'] + $data['crop'];
echo '<tr><td>'. $building. '</td><td>'. $level. '</td><td><input type="text" style="width:70px" id="build_' . $i . '" value="' . $total_res . '"></td></tr>';
}
I am using id="build_' . $i . '" to auto increment the id of the text box. Till here everything goes fine.
Back to the attampt.php page,
when I try to access the data from the text box i am unable to access it.
The code that I'm using to access the data is:-
var build_id='build_';
build_id += i;
$('#build_id').attr('disabled','true');
var total = $("#build_id");
alert(total);
the alert function at the end of the code gives the following output:-
[object Object]
I am trying to append a list of text boxes with some values to a table and then calculate the sum of all the values in the text boxes.
Please help.

$('#build_id') should be $('#'+build_id) and to calculate the total of all the values, you should put var total=0; outside your callback function, and the function should contain
total += $('#'+build_id).val();
Another problem is that each row of the table has the same id="build_$i", but IDs have to be unique.
And do you really intend to display $i at the beginning of the table, without it being in a table row?

Related

populate HTML table with JQuery AJAX using JSON formatted data

I am new here and newbie learner. I've checked some similar questions like this but could not get them to work.
What I am trying to achieve is, querying my database, retrieve list of accounts, then jquery function sends a query to ajaxtest2.php file for each of the account to retrieve account information and shows it in a html table.
Main problem is, table is populating with information of the last account in the database instead of all accounts.
I am getting this output at the moment:
`3459 1459 3459 1459`
Your help will be much appreciated.
Thank yoU :)
include_once('database.php');
$sql1 = "select * from account ";
$result1 = mysql_query($sql1);
while ($arr1 = mysql_fetch_array($result1)) {
$var = $arr1["account_no"];
?>
<script type="text/javascript">
$(document).ready(function() {
$(window).load(function() {
var numValue = <?php echo $var; ?>;
$.getJSON("ajaxtest2.php", {number: numValue}, function(data){
var trHTML = '';
$.each(data, function () {
trHTML += '<td>' + data.bal + '</td><td>' + data.eq + '</td>';
});
$('#location').append(trHTML);
});
}); `
});
</script>
<table id="location" border='1'>
</table>
<?php
}
The below is the response from ajaxtest2.php
echo json_encode(array("bal" => "$balance", "eq" => "$equity"));
?>
Make sure that you have table rows when you generate the cells.
trHTML += '<tr><td>' + data.bal + '</td><td>' + data.eq + '</td></tr>';
Else your cells will always append to the right of the previous cell without changing rows
Also, the your code could all be done using PHP only (no js)
Here's how:
<?php
include_once('database.php');
$sql1 = "select * from account ";
$result1 = mysql_query($sql1);
?>
<table id="location" border='1'>
<?php
while ($arr1 = mysql_fetch_array($result1)) {
$var = $arr1["account_no"];
//your ajaxtest2.php functionnalities go here
//let's say $accBalance and $accEquity contain the information you wanted about that specific row
echo '<tr><td>'.$accBalance.'</td><td>'.$accEquity.'</td></tr>';
}
?>
</table>
And there you have your populated table using database values without using JS.
Hoped it helped!

How to display database value into specific index of html table?

I need help for display selecting data value from database into a specific position in a html table.
I have made the code for displaying it but it will display the data in index 0 on the html table.
Anyone know how to make the data will displaying at index 1 on the html table?
I've try to change the index but it failed to displaying it.
Here my code:
$(document).ready(function(){
$.ajax({
type: "Post",
url: "../php/bkk/bkk_isel.php",
success: function(data){
var list = JSON.parse(data);
for(var i = 0; i < list.length; i++){
$('#mat').val((list[i]['material']));
$('#lok').val((list[i]['lokasi']));
$('#kpl').val((list[i]['kapal']));
$('#po_numb').val((list[i]['po']));
var tr = "<tr>";
tr += "<td>"+list[i]['tanggal']+"</td>";
tr += "<td>"+list[i]['no_pol']+"</td>";
tr += "<td>"+list[i]['netto']+"</td>";
tr += "</tr>";
$("#table_s tbody").append(tr);
}
return false;
}
});
});
This is the {data} that i use. i use php function for the data
<?php
$con=mysqli_connect("localhost","root","","silo");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
// Data for Titik1
$query = mysqli_query($con,"SELECT * FROM temp2");
$rows = array();
while($tmp= mysqli_fetch_array($query)) {
$rows[] = $tmp;
}
echo json_encode($rows);
mysqli_close($con);
?>
can you please more explain what shape you mold with html Table. basically table row always append with general indexing. if you need a black row before your data row so kindly append a blank row in your html table.
If you want the index number of the row to show on the html table, then you need to add a new column before all other columns. This new column will show the serial number of the row. For example before this line:
tr += "<td>"+list[i]["tanggal"]+"</td>";
Add this line:
tr += "<td>"+ (i+1) +"</td>";

Removing Selected Option From Database

I have a select element created dynamically with items from my database. I would like to be able to delete the record from the database if the delete button is selected. Currently I have an AJAX function that is sending a GET request to my current page to remove it, and it removes the item from my options, however, my PHP used to access my database is never called and therefore when I refresh, the query is ran and what I just "removed" is displayed again because it is still in my db. I know I must be missing something simplistic, I just can't quite put my
finger on it and would appreciate any help or advice. I'm open to other methods as well. This is definitely not my strong suit.
My AJAX:
window.onload = function () {
document.getElementById("deleteLoc").onclick = function () {
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "adminLocationEdit.php", //Where to make Ajax calls
data:{deleteLoc : $("#lList option:selected").val() },
dataType:"text", // Data type, HTML, json etc.
});
$("#lList option:selected").remove();
}
};
My HTML:
<select id ="lList" multiple="multiple" style="width:400px;height:400px;">
<?php
//Query that selects all locations from the database and creates the list dynamically.
$qry = "SELECT * FROM location";
$qry_result = odbc_exec($admconn,$qry) or die("A database error has been detected. Err: adminLocationListEdit-1");
//Echo the db results into the select box.
while($row = odbc_fetch_array($qry_result)){
//Sets each row to variable.
$locID = $row['locationName'];
echo "<option id =\"$locID\" name = \"$locID\" onclick =\"$('#form1').load('incl/adminLocationEdit.php?loc='+$(this).attr('id'));displayFieldsets('form1', 'locList', 'lList');\">" . $locID . "</option>";
}
?>
My PHP:
//If user wants to add a new location
if(isset($_POST['addLoc'])){
//Re-directs
//header("Location: adminLocation.php");
exit;
}
//If user wants to Delete a location from the database.
if(isset($_POST['deleteLoc'])){
$contentToDelete = $_POST['deleteLoc'];
//Deletes current location from the database.
$qry = "DELETE FROM location WHERE locationName = '" . $contentToDelete . "'";
$qry_result = odbc_exec($admconn,$qry) or die("A database error has been detected. Err: adminLocationListEdit-2");
}
You are mixing both GET and POST
If you are looking for post,
This should be
data:{deleteLoc : $("#lList option:selected").val() },
Or if you are looking fr GET
type: "GET",// this should be GET not POST

Show more result from database with jQuery and AJAX

I'm trying to create news block with AJAX in my template. so i wrote a simple code, in HTML Part:
Show Posts
<div id="result"></div>
jQuery Part:
function ShowPost(){
$.post(dir + 'engine/ajax/posts.php', {action:"showpost"},
function(data) {
$("#result").html(data);
});
};
PHP Part:
if ($_POST['action'] == "showpost") {
$db->query( "SELECT title FROM post LIMIT 0,5 " );
while ( $row = $db->get_row() ) {
echo $row['title']."<br>";
}
}
Question is, how i can get more result after first click? for example, after first click on Show Posts link, i can show the 5 news from database. after second click on Show Posts link i need to show 6 to 10 news, in third click get result from 11 to 15 and continue ...
i hope you understand my question.
Based on your implementation you need to keep track how many items you have shown and pass the page number in. For example:
jQuery Part:
var pageNumber = 0;
function ShowPost() {
pageNumber++;
$.post(dir+ 'engine/ajax/posts.php', {action:"showpost", pageNum: pageNumber},
function(data) {
$("#result").html(data);
});
};
Disclaimer: I m not a PHP developer so please treat teh code below as pseudo-code.
PHP Part:
if ($_POST['action'] == "showpost") {
var pageSize = 5;
var pageNumber = $_POST['pageNumber'];
var from = (pageNumber - 1) * pageSize;
var to = pageNumber * pageSize;
$db->query( "SELECT title FROM post LIMIT " + from + "," + pageSize);
while ( $row = $db->get_row()) { echo $row['title']."<br>"; }
}
Just implement the pagination limit in ur query
var offset = -5;
function ShowPost(){
offset = offset + 5;
$.post(dir + 'engine/ajax/posts.php', {action:"showpost",offset:offset},
function(data) {
$("#result").html(data);
});
};
PHP part
if ($_POST['action'] == "showpost") {
$vOffset = $_POST['offset'];
$db->query( "SELECT title FROM post LIMIT $vOffset,5 " );
while ( $row = $db->get_row() ) {
echo $row['title']."<br>";
}
}
Take a hidden field in html and update it's value after every success call and when next time you call for next record send that value in post.
<input type="hidden" name="limit" value="5">
Show Posts
<div id="result"></div>

Change dynamically loaded image when Autocomplete input changed

I have a table with dynamically created rows ('s) - in each is a set of inputs, one of which is an autocomplete input field where the user can search for an item and is given a list of choices, when they select one, the details of their ITEM are populated in all the remaining fields and an image that corresponds to their choice is called from the Database.
Here's my DB call Query:
$return_arr = array();
$param = $_GET["term"];
$fetch = mysql_query("SELECT * FROM crd_jshopping_products WHERE `name_en-GB` REGEXP '^$param' LIMIT 5");
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['product_name'] = $row['name_en-GB'];
$row_array['category'] = $row ['meta_keyword_en-GB'];
$row_array['jshop_code_prod'] = $row['product_ean'];
$row_array['_ext_price_html'] = number_format($row['product_price'],2);
if (!empty($row['product_thumb_image']) AND isset($row['product_thumb_image'])){
$row_array['image'] = $row['product_thumb_image'];
}else {
$row_array['image'] = 'noimage.gif';
}
array_push( $return_arr, $row_array );
}
mysql_close($conn);
echo json_encode($return_arr);
In my JQuery all I have to do is place this:
$('#prodImage').append('<img class="imgLoads" src="/components/com_jshopping/files/img_products/' + ui.item.image + '" >');
So it will put the Image into the div ID : prodImage.
I have tried IF Statements:
if ($('#prodImage').length)
{
$('#prodImage').append('<img class="imgLoads" src="/components/com_jshopping/files/img_products/' + ui.item.image + '" >');
}
else {
$('#prodImage').remove();
}
And ...
if (!$('#imgLoads').length)
{
$('#prodImage').append('<img class="imgLoads" src="/components/com_jshopping/files/img_products/' + ui.item.image + '" >');
}
else if($('#imgLoads').length){
$('#prodImage').remove();
}
And a whole bunch of variations and replaceWith() statements, but to no avail.
You can check out the live interface here :
http://cardoso.co.za/index.php/login-shop
Username: stackUser
Password: demo
What happens, at best, is the images bunch up one under the other ...
Any help is appreciated. I have also tried the following post, but it didn't work :(
Change image src with jQuery autocomplete
In Response to RST's piece of code, here is how I have tried to implement it so that it only changes the image in the exact TR where the autocomlete ifield is changed:
$(this).closest('#product_name').blur(function(){
$('.imgLoads').attr('src','/components/com_jshopping/files/img_products/' + ui.item.image);
});
This is how I solved the issue:
$(this).closest('tr').find('#product_name').blur(function(){
$(this).closest('tr').find('.imgLoads').attr('src','/components/com_jshopping‌​/files/img_products/' + ui.item.image);
$(this).closest('tr').find ('.imgLoads').attr('style','border-r‌​adius:8px;-webkit-border-radius:8px;-moz-border-radius:8px;border:solid 1px #CF3;');
});
In your HTML set the image tag already
<div id="prodImage">
<img class="imgLoads" src="">
</div>
jQuery
$('.imgLoads').attr('src','/components/com_jshopping/files/img_products/' + ui.item.image);
This code should go in a function, something like:
$('#some-element-id').change(function(){
$('#prodImage img.imgLoads').attr('src','/components/com_jshopping/files/img_products/' + ui.item.image);
)};
So it will adjust when selections are made.
Solved by using this code, after tweaking a lot of things, thanks again RST!
$(this).closest('tr').find('#product_name').blur(function(){
$(this).closest('tr').find('.imgLoads').attr('src','/components/com_jshopping‌​/files/img_products/' + ui.item.image);
$(this).closest('tr').find ('.imgLoads').attr('style','border-r‌​adius:8px;-webkit-border-radius:8px;-moz-border-radius:8px;border:solid 1px #CF3;');
});

Categories