Live Update Table entries to database SQL PDO AJAX - php

i try to make an editable-table on a homepage which automatically save the new entries after you leave the "field" or press enter but something doesnt work.
Everthing is fine until i want to save the new entrie to database.
I fired the PDO-SQL-Statment and it works.
For me it seems to be the table_edit_ajax.php wasnt work but i dont know why!
Hope some of you guys can help me?
Im using a normal mysql database
Homepagecode:
<Table>
$getIDBusinessRessources = $dbPDO->geteditableSingleBusinessRessoure();
foreach($getIDBusinessRessources as $getidBusiness){
$id = $getidBusiness['checkid'] ;
echo '<tr id="'
. $getidBusiness['checkid']
. '" '
. 'class="edit_tr"'
. '>';
// Spalte Ressourcenname
echo '<td class="edit_td">'
.'<span id="RessourceName_'
.$getidBusiness['checkid']
. '" '
. 'class="text">'
.$getidBusiness['Rn']
.'</span>'
.'<input type="text" value="'
.$getidBusiness['Rn']
. '" class="editbox" id="Ressourcname_Input_'
. $getidBusiness['checkid']
.'">'
.'</td>';
// Spalte Amount
echo '<td class="edit_td">'
.'<span id="Amount_'
.$getidBusiness['checkid']
. '" '
. 'class="text">'
.$getidBusiness['AM']
.'</span>'
.'<input type="text" value="'
.$getidBusiness['AM']
. '" class="editbox" id="Amount_Input_'
. $getidBusiness['checkid']
.'" '
.'</td>';
</tr>
</table>
JS:
$( document ).ready(function() {
$(".edit_tr").click(function()
{
var ID=$(this).attr('id');
$("#RessourceName_"+ID).hide();
$("#Amount_"+ID).hide();
$("#Ressourcname_Input_"+ID).show();
$("#Amount_Input_"+ID).show();
}).change(function()
{
var ID=$(this).attr('id');
var first=$("#Ressourcname_Input_"+ID).val();
var last=$("#Amount_Input_"+ID).val();
var dataString = 'id='+ ID +'&RessourceName='+first+'&Amount='+last;
$("#RessourceName_"+ID).html('<img src="img/bearbeiten.png" />'); // Loading image
if(first.length>0&& last.length>0)
{
$.ajax({
type: "POST",
url: "table_edit_ajax.php",
data: dataString,
cache: false,
success: function(html)
{
$("#RessourceName_"+ID).html(first);
$("#Amount_"+ID).html(last);
}
});
}
else
{
alert('Enter something.');
}
});
// Edit input box click action
$(".editbox").mouseup(function()
{
return false
});
// Outside click action
$(document).mouseup(function()
{
$(".editbox").hide();
$(".text").show();
});
Ajax Code:
<?php
include "DBconnection.php";
if($_POST['id']){
$id = $_POST['checkid'];
$RessourceName = $_POST['Rn'];
$Amount = $_POST['AM'];
$dbPDO->UpdateLiveTableEntries($id,$RessourceName, $Amount );
}
?>
and at least the DB-Update code
function UpdateLiveTableEntries($id ,$Ressourcename, $Amount ){
// echo '<script type="text/javascript"> alert("inside");</script>';
$stmt = self::$_db->prepare("UPDATE BalancesheetInput SET RessourceName =:ressname , Amount =:menge WHERE ID =:id");
$stmt->bindParam(":id", $id);
$stmt->bindParam(":ressname", $Ressourcename);
$stmt->bindParam(":menge", $Amount);
$stmt->execute();
}

If you're sending this:
var dataString = 'id='+ ID +'&RessourceName='+first+'&Amount='+last;
^^ ^^^^^^^^^^^^^ ^^^^^^
why are you looking for these?
$id = $_POST['checkid'];
^^^^^---you aren't sending a 'checkid'
$RessourceName = $_POST['Rn'];
^-- you aren't sending an 'Rn'
$Amount = $_POST['AM'];
^^-- you aren't sending an 'AM'

Related

Send php variables to jquery function

Ok, I need to send data from PHP to jquery and use jquery function to update that data into HTML.
But the problem is jquery want update HTML elements with PHP data...
This is php code.Php is called from ajax.
$product_image = "";
$product_name = "";
$product_description = "";
$product_size = "";
if(mysqli_num_rows($r) > 0) {
while($row = mysqli_fetch_assoc($r)) {
$product_image = "wp-content/themes/meditalis-to-wp/assets/products/" . $row["image"];
$product_name = $row["name"];
$product_description = $row["description"];
$product_size = "wp-content/themes/meditalis-to-wp/assets/products/" . $row["img_size"];
echo '<script type="text/JavaScript">';
echo 'var product_image = ' . json_encode($product_image) . ';';
echo 'var product_name = ' . json_encode($product_name) . ';';
echo 'var product_description = ' . json_encode($product_description) . ';';
echo 'var product_size = ' . json_encode($product_size) . ';';
echo 'showProduct();';
echo '</script>';
}
}
//echo $product_num_id;
mysqli_close($dbc);
exit();
}
This is jquery function for updating html elemtns:
function showProduct()
{
alert("dbg");
$("#product_name_put").html(product_name);
$("#product_desc_put").html(product_description);
$("#product_image_put").attr("src", product_image);
$("#product_size_put").attr("src", product_size);
}
And this is html elements:
<div class="product_view_info">
<ul class="product">
<li><img id="product_image_put" src="" alt=" Product Photo"></li>
<li class="informations">
<div class="product_name"><h4 id="product_name_put"></h4></div>
<div class="desc_info"><p id="product_desc_put"></p></div>
<img id="product_size_put" src="" alt="Size Photo">
</li>
</ul>
</div>
This is a problem: https://ibb.co/HGyJkwB
UPDATE: AJAX CODE: When user click on product ajax sending id of clicked product to php.
$(document).on("click touchend", ".product_stake_stapovi, .product_invalidska_kolica, .product_antidekubitni_program, .product_ortoze, .product_mideri, .product_pojas, .product_toaletni_program, .product_bolnicki_kreveti_i_oprema", function (event) {
var product_num_id = $(this).children(".num_id").attr("id"); //Getting id from image element (that is location of real stored id in database)
var product_id = $(this).attr("class");
var product_real_id = product_id.replace("col-3 col ", "");
$.ajax({
method: "POST",
url: "index.php?proizvodi",
data: ({product_num_id:product_num_id}),
success: function() {
$(".big_categoryes").fadeOut("fast");
$(".all_products").fadeOut("fast");
$(".product_view_info").fadeIn("smooth");
}
});
});
U can get data from PHP as json like so:
if(mysqli_num_rows($r) > 0) {
while($row = mysqli_fetch_assoc($r)) {
$product = (object)[];
$product->image = "wp-content/themes/meditalis-to-wp/assets/products/" . $row["image"];
$product->name = $row["name"];
$product->description = $row["description"];
$product->size = "wp-content/themes/meditalis-to-wp/assets/products/" . $row["img_size"];
echo json_encode($product);
}
}
mysqli_close($dbc);
exit();
and get data from json with jquery:
$(document).on("click touchend", ".product_stake_stapovi, .product_invalidska_kolica, .product_antidekubitni_program, .product_ortoze, .product_mideri, .product_pojas, .product_toaletni_program, .product_bolnicki_kreveti_i_oprema", function (event) {
var product_num_id = $(this).children(".num_id").attr("id"); //Getting id from image element (that is location of real stored id in database)
var product_id = $(this).attr("class");
var product_real_id = product_id.replace("col-3 col ", "");
$.ajax({
method: "POST",
url: "index.php?proizvodi",
data: ({product_num_id:product_num_id}),
success: function(response) {
var product = JSON.parse(response);
console.log(product.image);// example
showProduct(product);
$(".big_categoryes").fadeOut("fast");
$(".all_products").fadeOut("fast");
$(".product_view_info").fadeIn("smooth");
}
});
});
function showProduct(product){
$("#product_name_put").html(product.name);
$("#product_desc_put").html(product.description);
$("#product_image_put").attr("src", product.image);
$("#product_size_put").attr("src", product.size);
}
I hope this could help you.

Passing a variable jquery .submit

So essentially I'm submitting a form via jquery. There are multiple forms with multiple ID's using the format question_vote_[some_value].
I'm picking up the submission using the following selector:
$("form[id^='question_vote_']").submit(function(event){
vote_on_question_recent(/* I need to add the value preceeding the id in here */);
event.preventDefault();
})
Here's my form code:
<?php
if ($question_choices)
{
echo '<form action="" method="post" enctype="multipart/form-data" value="' . $question_details['question_id'] . '" id="question_vote_' . $question_details['question_id'] . '">';
while($question_choice = $database->fetch_array($question_choices))
{
// do something with the $row
echo '<input type = "radio" name = "radio_button_recent_' . $question_details['question_id'] . '" id = "radio_button_' . $question_details['question_id'] . '_' . $question_choice['choice_id'] . '" value = "' . $question_choice['choice_id'] . '" /> <label for = "' . $question_choice['choice_text'] . '">' . $question_choice['choice_text'] . '</label><br>';
}
echo '<input type="submit" name="voteOnQuestion" value="Vote!" class="login_home_sub"></form>';
}
?>
I then have the following code for my 'vote_on_question_recent' function:
function vote_on_question_recent(question_id)
{
var form_name = 'vote_form';
var choice_id = $('[name=radio_button_recent_' + question_id + ' ]:checked').val();
if(choice_id)
{
$.ajax({
type:"POST",
url: "API/index.php",
data: {vote_form: form_name, question_id: question_id, choice_id: choice_id},
success: function(result){
if(result == 'success'){
alert(result);
return false;
}
else
{
alert('error');
return false;
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr + ' / ' + ajaxOptions + ' / Error:' + thrownError + ' Submitted choice:' + choice_id + ' question id:' + question_id);
return false;
}
});
}
}
So essentially I'm looking for some way to pass the 'question_id' to my javascript submit function, or get the actual id of the submitted form so I can parse it and get the ID that way.
You can add a data-* attribute to save the question id and use it in the submit handler to obtain the question id.
echo '<form action="" method="post" enctype="multipart/form-data" value="' . $question_details['question_id'] . '" id="question_vote_' . $question_details['question_id'] . '" data-question="' . $question_details['question_id'] . '">';
then
$("form[id^='question_vote_']").submit(function(event){
vote_on_question_recent($(this).data('question'));
event.preventDefault();
})

PHP Infinite scroll pulling random results?

I have a page that returns 16 records from my table.
As the user scrolls to the bottom, I then pull another 12 records from my table and append them to my previous results, my problem is that my results are being duplicated, and not in the correct order.
JS
// Ajax Getentries.php
var url = location.pathname;
if(url.indexOf('missing-people.php') > -1) {
didScroll = false;
$(window).scroll(function () {
didScroll = true;
});
setInterval(function () {
if(didScroll) {
didScroll = false;
if(($(document).height() - $(window).height()) - $(window).scrollTop() < 100) {
var number = $(".directory").children().length;
$.ajax({
type: "POST",
url: "getentries.php",
data: "count=" + number,
success: function (results) {
$('.directory').append(results).fadein();
}
});
}
}
}, 250);
}
PHP
$result = mysql_query("SELECT * FROM directory LIMIT {$_POST['count']},12");
$c = 1;
while($row = mysql_fetch_array($result))
{
echo '<div class="entry';
if (($c % 4) == 1) echo ' alpha ';
echo ' span3"><span class="name">' . $row['First_Name'] . ' ' . $row['Surname'] . "</span>";
echo '<img src="/access/upload/' . $row["picture_1"] . '" alt="' . $row['First_Name'] . ' ' . $row['Surname'] . ', missing since ' . $row['Date_Last_Seen'] . ' " />';
echo '<span class="missing-from">Last seen in ' . ucwords($row["Location_County_Last_Seen"]) . '</span>View Profile</div>';
$c++;
}
mysql_close($con);
it seems like it's a race condition. Indeed, if you quickly scroll the page this is what happens:
the setInterval gets triggered
there are already 12 images in the dom, hence var number = $(".directory").children().length is 12.
now new data is fetched from the server with ajax.
Now, if I'm still at the bottom of the page and the ajax calls hasn't completed yet, the setInterval is going to be triggered again, number still resolve to 12 and I'm going to do the same ajax request. Hence duplication.
Solving the issue could be as simple as setting number at the beginning of the script and incrementing it every time you make an ajax call.
// Ajax Getentries.php
var url = location.pathname;
var number = $(".directory").children().length;
if(url.indexOf('missing-people.php') > -1) {
didScroll = false;
$(window).scroll(function () {
didScroll = true;
});
setInterval(function () {
if(didScroll) {
didScroll = false;
if(($(document).height() - $(window).height()) - $(window).scrollTop() < 100) {
number += 12;
$.ajax({
type: "POST",
url: "getentries.php",
data: "count=" + number,
success: function (results) {
$('.directory').append(results).fadein();
}
});
}
}
}, 250);
}

Opencart ajax post query to database not working

I am testing opencart in XAMPP. I added this extension which checks zip code and enables to give zip code based shipping. Demo is here. It may not be compatible with the latest version.
The code was not working initially and after some modifications the admin side works. I can insert/modify zip code, etc., which means there is no issues in database.
In the catalog side however I am helpless. There is this ajax button which is not working.
<div class="pincode">
<span><strong>Enter pincode to check serviceability:</strong></span><br><br>
<input type="text" name="zip_code" value="" id="zip_code" size="8">
<a id="button_zipcode" class="button" title="Check"><span>Check</span></a><br><br>
<div id="temp_zipcode" style="width:94%;"></div>
which gets enabled with this script
$('#button_zipcode').bind('click', function() {
$.ajax({
url: 'index.php?route=product/product/zipcode',
type: 'post',
data: 'zip_code='+$('#zip_code').val(),
dataType: 'json',
success: function(json) {
$('.success, .warning, .attention, information, .error').remove();
if (json['warning']) {
$('#temp_zipcode').html('<div class="warning" style="display: none;">' + json['warning'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');
$('.warning').fadeIn('slow');
}
if (json['success']) {
$('#temp_zipcode').html('<div class="success" style="display: none;">' + json['success'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');
$('.success').fadeIn('slow');
}
}
});
});
url: 'index.php?route=product/product/zipcode', what this means? if it is controller/product/product.php what should I add to make it work? The code should check zip code with DB and give output.
And there is another page as catalog/model/localisation/zip_code.php which has
<?php
class ModelLocalisationZipCode extends Model {
public function getZipCode($zip_code_id) {
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "zip_code WHERE zip_code_id = '" . (int)$zip_code_id . "' AND status = '1'");
return $query->row;
}
public function getCodeByZip($zip_code) {
$query1 = $this->db->query("SELECT * FROM " . DB_PREFIX . "zip_code WHERE zip_code LIKE '" . $zip_code . "' AND status = '1'");
return $query1;
}
}
?>
Is there anyway to make it work?
Thanks in advance...
In your catalog/controller/product/product.php
add the fallowing code :
public function zipcode() {
$this->language->load('product/zipcode');
$this->load->model('localisation/zip_code');
$json = array();
if (isset($this->request->post['zip_code'])) {
$zip_code = $this->request->post['zip_code'];
} else {
$zip_code = 0;
}
$zone_data = $this->model_localisation_zip_code->getCodeByZip($zip_code);
if($zone_data->num_rows == 0)
{
$json['warning'] = sprintf($this->language->get('text_warning'));
}
else
{
$city_name = $zone_data->row['city_name'];
$state_name = $zone_data->row['state_name'];
$zone_name = $zone_data->row['zone_name'];
$json['success'] = sprintf($this->language->get('text_success'), $city_name, $state_name, $zone_name);
}
$this->response->setOutput(json_encode($json));
}

AJAX request causes change function unbind

I want to implement simple functionality to allow users to save their message text as template to be used in the future.
php:
echo '<div id="container">';
$sql = ("SELECT template_id, template_text, template_name, member_id FROM message_templates
WHERE member_id = {$member_id}");
$result = mysql_query($sql) or die(mysql_error());
$num_rows = mysql_num_rows($result);
$confName = get_conference_name($confID);
$confName = formatText_safe($confName);
echo "<label>" . $lang['my_template'] . "</label><select id='tempchoose' name='templates'>";
if ($num_rows == 0) {
echo '<option value=""> ' . $lang['no_saved'] . '</option>';
} else {
for ($i = 0; $i < $num_rows; $i++) {
//$template_id = mysql_result($result, $i, 0);
$temp_text = mysql_result($result, $i, 1);
$temp_name = mysql_result($result, $i, 2);
echo '<option value="' . $temp_text . '">' . $temp_name . '</option>';
}
}
echo "</select></div>";
echo '<input id="send" name="Message" value="send" disabled="disabled" type="submit" />
<input id="temp" name="temp" type="button" value="save as template" />"
<textarea style="width: 99%;" id="textarea" name="TextBox" rows="8" disabled="disabled" type="text" value=""/></textarea>';
javascript:
$("#temp").bind("click", function(){
name=prompt("template name?");
temp_text = $("#textarea").val();
if (name!=null && name!="" && name!="null") {
$.ajax ({
data: {temp_text:temp_text, name:name},
type: 'POST',
url: 'save_template.php',
success: function(response) {
if(response == "1") {
alert("template saved successfully");
} else {
alert(response);
}
}
});
} else {
alert("invalid template name");
}
$.ajax ({
url: 'update_templates.php',
success: function(response) {
$("#container").html(response);
}
});
});
$("select").change(function () {
$("select option:selected").each(function () {
$("#textarea").removeAttr("disabled");
$("#send").removeAttr("disabled");
});
$("#textarea").val($(this).val());
})
.trigger('change');
update_temp.php
$sql = ("SELECT template_id, template_text, template_name, member_id FROM message_templates
WHERE member_id = {$member_id}");
$result = mysql_query($sql) or die(mysql_error());
$num_rows = mysql_num_rows($result);
$confName = get_conference_name($confID);
$confName = formatText_safe($confName);
echo "<label>".$lang['my_template']."</label><select id='tempchoose' name='templates'>";
if ($num_rows == 0) {
echo '<option value=""> '.$lang['no_saved'].'</option>';
} else {
for ($i = 0; $i < $num_rows; $i++) {
//$template_id = mysql_result($result, $i, 0);
$temp_text = mysql_result($result, $i, 1);
$temp_name = mysql_result($result, $i, 2);
echo '<option value="' . $temp_text . '">' . $temp_name . '</option>';
}
}
echo "</select>";
the last ajax request in #temp click function is used to updated the droplist with the newly created template, the problem is that when i click save template; ajax request is performed successfully and droplist is updated, however something wired happen which is that the change function of select is not working anymore! anyone knows where's the problem?
Because ajax will inject new elements to your DOM and those elements don't know about the binding you already defined.
Solution : use jQuery on
Change
$("select").change(function () {
to
$(document).on("change","select", function(){
jQuery on is available from 1.7+ version onwards, if you are using a previous version of jQuery, consider using delegate.
If you are rewriting the select with Ajax you should use .delegate() rather than simply .change, like:
$("someSelector").delegate("select", "change", function() {
// do stuff...
});
where someSelector is an element that contains your select.
Yes, because you have replaced the drop down inside of container, which will unhook all of the events on the drop down. The solution would be to modify the code as below:
$.ajax ({
url: 'update_templates.php',
success: function(response) {
$("#container").html(response);
$("#container select").change(
// your drop down change functionality here //
);
}
});
What this is doing is saying, "After the drop down has been refreshed, also refresh the event."
I hope this helps.

Categories