ajax not loading content - php

I have a button for increasing the quantity
<input name="quantity-"'.$item_id.'" " id="quantity-'.$item_id.' " type="text" value="' . $quantity . '" />
$increase = '1';
<input name="increase-' . $item_id . '" id="increase-' . $item_id . '" type="button" value="+" onClick="cart_change_quantity('.$item_id .','.$quantity.','.$increase.')" />
the function:
function cart_change_quantity( item_id, quantity, mod ) {
$.ajax({
url: 'functions/product-change-quantity.php',
type: 'GET',
data: {
item_id: item_id,
quantity: quantity,
mod: mod
},
success: function(response) {
if ( response.search('success') != -1 ) {
var felbontva = response.split('__'),
new_quantity = felbontva[1];
$('#quantity-' + item_id).val( new_quantity );
}
else {
alert( 'An error occured while trying to update your order.' );
}
}
});
}
and the product-change-quantity.php:
$item_id = $_GET["item_id"];
$quantity = $_GET["quantity"];
$mod= $_GET["mod"];
if ( $mod == '1' ) { $new_quantity = (int)$quantity + 1; }
echo 'success__' . $new_quantity;
it's just not doing anything. I would like to increase the quantity of a product with that button and later i would like to do more things in the background without refreshing the page so that's why i choosed ajax
Thank you!

Based on the source codes you posted above, you're accessing an input element which is not in your html file. If you can notice that in HTML, you have added space after the item id for the input element's ID. While on your javascript, you didn't add space after item id when you are trying to access the same element although I think it is better if you don't put spaces in your ID.
[HTML]
<input name="quantity-"'.$item_id.'" " id="quantity-'.$item_id.' " type="text" value="' . $quantity . '" />
[Javascript]
$('#quantity-' + item_id).val( new_quantity );

Related

Display radio buttons and checkbox for certain items CodeIgniter

I am new to Codeigniter framework. I have a scenario where I have to display radio box and checkbox based on the database value 0 or 1. If the value is 0 then the radio buttons should appear for the particular items and if the value is 1 then display items with the checkboxes so the user can select multiple items. How can I accomplish this task? Right now, I am able to display all items only with checkboxes.
I have added new field in database with the name of multi_select. Here I am saving items with the value of 0 and 1.
Here is my code.
$(document).on('click', '.add_cart_modal', function (e) {
$('.item_attr_div_model').empty();
var it_val = $(this).attr('value');
$data = 'item_id=' + it_val;
var rest_id = $("#restid-" + it_val).val();
$url = '<?= base_url() ?>main/get_item_attributes';
$.ajax({
url: $url,
type: "POST",
dataType: 'json',
data: $data,
success: function (data) {
if (data.item_options != null && data.group_attrib == '1') {
var item_group_data = '';
$.each(data.item_options, function (key, item) {
var item_attrib = '';
if (item.attributes != null) {
$.each(item.attributes, function (key, it_attrbues) {
item_attrib += '<div class="col-lg-4" style="margin-top: 10px;">' +
'<div class="checkbox">' +
'<input id="' + it_attrbues.name + '" type="checkbox" value="' + it_attrbues.id + '" class="options_ids" name="options[]" style="margin-right:5px">' +
if (item.attributes != null) {
item_group_data += + item.group_name +
'' + item_attrib +;
}
});
var item_attr_display =
'<input name="item_id" id="attr_item_id" type="hidden" value="' + data.item_id + '" >' +
'<input name="item_name" id="attr_item_name" type="hidden" value="' + data.item_name + '" >' +
'<input name="item_price" id="attr_item_price" type="hidden" value="' + data.item_price + '" >' +
'<input name="rest_id" id="attr_rest_id" type="hidden" value="' + rest_id + '" >' +
data.item_name + data.item_description + Price +
data.item_price + item_group_data;
$('.item_attr_div_model').append(item_attr_display);
$('#add_cart_modal').modal('show');
} else {
var attribute_ids = '';
post_array =
{
"item_id": $("#id-" + it_val).val(),
"item_name": $('#name-' + it_val).val(),
"item_qty": $("#qty-" + it_val).val(),
"item_price": $("#price-" + it_val).val(),
"rest_id": $("#restid-" + it_val).val(),
"attribute_ids": attribute_ids
}
$.post(base_url + "main/add_item_to_cart", post_array,
function (data) {
var res = jQuery.parseJSON(data);
update_cart_items(res.cart_view, res.total_cost, res.items_count);
$('.whole_div').hide();
});
}
}
});
});
How can I read 0 and 1 value from database for particular items and display radio or checkbox based on their value?
Change your $.each function as follow
$.each(item.attributes, function (key, it_attrbues) {
var ty = 'radio';
if(it_attrbues.multi_select == '1') //if the value is 1 then it will pass checkbox
{
ty = 'checkbox';
}
item_attrib += '<div class="col-lg-4" style="margin-top: 10px;">' +
'<div class="checkbox">' +
'<input id="' + it_attrbues.name +
'" type="'+ty+'" value="' + it_attrbues.id + '" class="options_ids" name="options[]" style="margin-right:5px">' +
'<label style="padding-left: 25px;" class="label-radio oswald-font bold font22"for="' + it_attrbues.name + '">' + it_attrbues.name + ' (' + it_attrbues.price + ')</label>' +
'</div>' +
'</div>';
});

Live Update Table entries to database SQL PDO AJAX

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'

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();
})

how to post dynamically generated html table when form submitted?

I have a form that will contain a html table which allows users can add or delete rows from it. That will works fine .
/*add row*/
function add_Items(itemtypeid, itemid, reqqty) {
var mode = 1;
var pstSettings = {
url: 'ajax_Items/' + itemid + '/' + mode
callback: function (data) {
var dyntd = "";
var hidval = "";
var $response = $(data);
var resitmname = $response.filter('#Item_Name').text();
var resitmdesc = $response.filter('#Item_Descrip').text();
dyntd = "<td><label>" + itemid + "</label></td>";
dyntd += "<td><label>" + resitmname + "</label></td>";
dyntd += "<td><label>" + resitmdesc + "</label></td>";
dyntd += "<td><label>" + reqqty + "</label></td>";
hidval += '<input type="hidden" name="itemid" value=' + itemid + ' />';
hidval += '<input type="hidden" name="reqitem" value=' + reqqty + ' />';
dyntd += '<td>' + hidval + '<input type="button" name="min" class="minus" value="-" />';
$('.item-result-table tr:last').after('<tr>' + dyntd + '</tr>');
}
};
post_Call(pstSettings);
}
}
/* delete row */
$(document).ready(function () {
$('.item-result-table').delegate('.minus', 'click', function (e) {
$(this).parent().parent().remove();
});
});
But now my problem is how to submit the html table in a form, because of all are html tags not input type tags . I have added a hidden tag . But it also creates problem that it only takes the first element , others are ignored. Is any other method existing to submit this html table data?
The reason you are only getting one input is because you defined it wrong, you need to define it as array:
<input type="hidden" name="itemid[]" value=' + itemid + ' />
<input type="hidden" name="reqitem[]" value=' + reqqty + ' />'
and then in PHP:
$_POST['itemid'][0];
I think that you could use the $.ajax jquery function. You can serialize all your inputs in the form like this:
$("#btn_submit").on('click', function() {
$.ajax({
url: $(this).closest("#div_content").find("#form").attr( 'action' ),
type: 'post',
data: $(this).closest("#div_content").find("#form").serialize(),
}).done( function(msg) {
//console.log("ok");
}).fail( function(jqXHR, textStatus) {
//console.log("fail");
});
});
With the "serialize" you can send all the variables and on the controller you can read the variables with $_POST and the name of the input.

In Concrete5 how do I update my block edit view to show the current values saved in the database?

I have code that dynamically creates a product features list and puts all the values together into one string seperated by newline characters and gets saved to the database. When this string is passed to the view I output as an unordered list. When I go to edit the block it does not show what is already in the list, so I have to retype all the features everytime I need to edit my block, even if it's not the feature list (I have some titles and other textareas). If I put the php variable into my edit page it will show me what has been saved but I would need it to be instantly added to the list and not showing separate. I basically need it to "auto appendTo" my <ul>. Here is my code...
controller function to save the list in controller.php
public function save($args) {
$args['features'] = implode("\n", $args['features']);//combine all feature items into one string, separated by "newline" characters
parent::save($args);
}
my edit.php - this will show it in a list. If I just put echo $features it outputs the string.
echo '<div class="ccm-block-field-group">';
echo '<h2>' . t('Features') . '</h2>';
echo '<input type="text" id="inputList" />';
echo '<button type="button" id="addList">Add</button>';
echo $features = explode("\n", $features);
foreach ($features as $feature) {
echo '<li class="currentFeatures">' . $feature . '</li>';
};
echo '<ul class="featureList">';
echo '</ul>';
echo '</div>';
my auto.js - handles creation of the list
var listItemCounter = 0;
$("#addList").click(function() {
listItemCounter++;
var text = $("#inputList").val(); //assign a unique id number to this button, so it knows which hidden field to remove when clicked
var buttonDataId = text + '<button data-id="' + listItemCounter + '">x</button>';
if(text.length){
$('<li />', {html: buttonDataId}).appendTo('ul.featureList');
$('<input type="hidden" name="features[]" value="' + text + '" data-id="' + listItemCounter + '" />').insertAfter('ul.featureList');
};
});
$('ul').on('click','button', function(el){
$('input[data-id="' + $(this).attr('data-id') + '"]').remove();//remove the hidden field so it does not get POSTed when user saves
$(this).parent().remove()
});
and finally part of my db.xml
<field name="features" type="X2"></field>
You'll want to do something similar to what I explained for the "view" in your other question ( https://stackoverflow.com/a/14968046/477513 ).
You want to change the list from a string to an array (via explode("\n", $features)), then run your javascript on each of those features. Since this is basically the same javascript that you'd do when someone adds a new item via the textbox, you will want to move all that code into a function and call the function in both situations (otherwise you will be copying and pasting the same code, which violates the "Don't Repeat Yourself" rule and inevitably leads to bugs in the future). So your auto.js code could look something like this:
var listItemCounter = 0;
function addItem(text) {
if (text.length) {
listItemCounter++;
var itemHtml = '<li data-id="' + listItemCounter + '">'
+ text
+ '<button data-id="' + listItemCounter + '">x</button>'
+ '</li>';
var inputHtml = '<input type="hidden" name="features[]" value="' + text + '" data-id="' + listItemCounter + '" />';
$('ul.featureList').append(itemHtml);
$('ul.featureList').after(inputHtml);
}
}
function removeItem(id) {
$('input[data-id="' + id + '"]').remove();
$('li[data-id="' + id + '"]').remove();
}
$("#addList").click(function() {
additem($("#inputList").val());
});
$('ul').on('click','button', function(el) {
var id = $(this).attr('data-id');
removeItem(id);
});
Then in your edit.php file, add this code to output the saved data and call the addItem function on each one:
<?php
//populate existing data when edit dialog is first opened
$featuresPHPArray = explode("\n", $features);
$featuresJSArray = Loader::helper('json')->encode($featuresPHPArray);
?>
<script>
var savedItems = <?php echo $featuresJSArray; ?>;
$.each(savedItems, function() {
addItem(this);
});
</script>

Categories