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();
})
Related
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>';
});
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'
I am [successfully] storing a snippet of jQuery inside a php variable, with values inside the snippet being populated by php script like so:
...//collect necessary variables
$script = "
<script type='text/javascript'>
(function($) {
analytics.identity('" . $cid . "', {
created: '" . $created . "',
email: '" . $email . "',
...: '" . $whatever . "'
});
})(jQuery);
</script>
";
return $script;
I can also [successfully] get the name attribute of all forms on the page like so:
<script type='text/javascript'>
(function($) {
$('form').each(function() {
var formname = $( this ).attr('name');
if(formname !== undefined) {
console.log(index + ':' + encodeURIComponent(formname));
};
});
})(Jquery);
</script>
The problem I'm having (maybe obviously) is the lack of experience with javascript to know how to incorporate the two so my $script would look like so:
$script = "
<script type='text/javascript'>
(function($) {
analytics.identity('" . $cid . "', {
created: '" . $created . "',
email: '" . $email . "',
...: '" . $whatever . "'
});
analytics.trackForm($('form[name="formname1"]'),'Form Submitted', {
lead: formname
});
analytics.trackForm($('form[name="formname2"]'),'Form Submitted', {
lead: formname
});
...//(n) number of form names
})(jQuery);
</script>
";
Latest script added directly to the footer:
<script type="text/javascript">
(function($) {
$('form').each(function() {
var formname = $(this).attr('name');
if( formname !== undefined) {
console.log( formname );
var forms = $('form[name="' + formname + '"]');
var trackforms = analytics.trackForm(forms, 'Submitted Optin Form', { leadmagnet: "'" + formname + '"' });
return trackforms;
}
});
})(jQuery);
</script>
Console.log outputs the one form currently on the page, and if I add another, it outputs that correctly also, but the rest of the code is simply written as is and I'm not getting it.
Thanks again.
document.write(...) is adding the string to the document not to the script.
You need to return the functions you want.
$script = "
<script type='text/javascript'>
(function($) {
analytics.identify('" . $ifs_id . "', {
created: '" . $created . "',
email: '" . $email . "',
firstName: '" . $first_name . "',
leadsource: '" . $lead_source ."'
});
$('form').each(function( index ) {
var formname = $( this ).attr('name');
if( formname !== undefined) {
//console.log( index + ':' + formname );
var forms = $('form[name=\"+formname+\"]);
var trackform = analytics.trackForm(forms, 'Submitted Opt In Form', {
leadmagnet : $( this ).attr('name')
});
return trackform;
}
});
})(jQuery);
</script>
";
return $script;
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.
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 );