I have a form adding data into db. I have single input field and button which add more input fields on click. My question is how to grab in controller all inputs and send it to model. My code so far is:
jQuery:
<script>
$('a').click(function(e){
$('#inp').append('<div><input class = "new_input" type=text name="name[]"/><a class="remove_field "href="#"> X</a><div><br/>');
$('.remove_field').click( function(e){
e.preventDefault();
$(this).parent('div').remove();
})
});
</script>
form:
<?php
// Forma za unos podataka
echo $this->session->flashdata('item');
echo '<h4>Unesite podatke</h4>';
echo '<div id="warning"></div>';
$att = array('name'=>'form','onsubmit'=>" return validation()");
echo form_open('admin/crud/adding/',$att);
echo form_label('Novi podatak:', 'input_data_info') . br() . br();
$data = array(
'name' => 'input_data_info',
'id' => 'input_data_info',
'placeholder' => 'Unestite podatke',
);
echo form_input($data) . br() . br();
echo '<div id="inp"></div>';
echo "<a href='#'>".'Novi unos'."</a>" .br() .br();
echo form_submit('save', 'Snimi') . br() . br();
echo form_submit('add', 'Dodaj').br();
echo form_close();
?>
controller:
$input_data_info = (string)$this->input->post('input_data_info', TRUE);
//model za dodavanje podataka
$this->load->model('Data');
$query = $this->Data->add($input_data_info);
The first input field name is 'input_data_info' and then JQuery adds input fields with 'name[ ]'
As you want to pull the data from all the input fields, they , first need to have a common name.
So, rename the input field that you have created initially in the form to name= 'name[]' that makes your code:
$data = array(
'name' => 'name[]',
'id' => 'input_data_info',
'placeholder' => 'Unestite podatke',
);
Then in you controller use something like this:
$all_input_data = $this->input->post('name');
//the $all_input_data is an array containing all your input values.
Related
I have an ajax form that filters posts based on the category.
Setup:
HTML form
PHP function to echo ouput
jQuery ajax request to load php
function
Question: How can I parse a value to the php function ($test, see below) from within the jQuery ajax function?
Form - Outputs html select field and button to filter posts
<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">
<?php
if( $terms = get_terms( 'category', 'orderby=name' ) ) : // to make it simple I use default categories
echo '<select name="categoryfilter"><option>Select category...</option>';
foreach ( $terms as $term ) :
echo '<option value="' . $term->term_id . '">' . $term->name . '</option>'; // ID of the category as the value of an option
endforeach;
echo '</select>';
endif;
?>
<button>Apply filter</button>
<input type="hidden" name="action" value="myfilter">
</form>
<div id="response"></div>
PHP function - Outputs result on button click in HTML form
function misha_filter_function($test){
// Do something with $test, but how to parse it with jQuery into this php function?
$args = array(
'orderby' => 'date', // we will sort posts by date
'order' => $_POST['date'] // ASC или DESC
);
// for taxonomies / categories
if( isset( $_POST['categoryfilter'] ) )
$args['tax_query'] = array(
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => $_POST['categoryfilter']
)
);
$query = new WP_Query( $args );
if( $query->have_posts() ) :
while( $query->have_posts() ): $query->the_post();
echo '<h2>' . $query->post->post_title . '</h2>';
endwhile;
wp_reset_postdata();
else :
echo 'No posts found';
endif;
die();
}
add_action('wp_ajax_myfilter', 'misha_filter_function');
add_action('wp_ajax_nopriv_myfilter', 'misha_filter_function');
jQuery - Question: how to parse php value $test to the above php function?
jQuery(function($){
$('#filter').submit(function(){
var filter = $('#filter');
$.ajax({
url:filter.attr('action'),
data:filter.serialize(), // form data
type:filter.attr('method'), // POST
beforeSend:function(xhr){
filter.find('button').text('Processing...'); // changing the button label
},
success:function(data){
filter.find('button').text('Apply filter'); // changing the button label back
$('#response').html(data); // insert data
}
});
return false;
});
});
You serialize data so accesed by:
parse_str($_POST['data'], $inputValues); //$inputValues will be array with your form fields
I have an form input of type datalist, in this list is about 5000 options, because of the large amount of options a select form just is not practical as you are allowed to type and it suggests what you want with a datalist.
<div class='form-row'>
<div class='col-xs-12 form-group required' style="margin-top: -2px; margin-bottom: 0px;">
<h2><label class='control-label' style="font-size: 20px;">Product code</label></h2>
<input required id="ItemSelect" list=jobs style='font-size:21px;height: 40px;'
class='form-control'
name="Code">
<datalist id=jobs>
<?php
foreach ($this->Products as $a) {
$inputValue = " " . htmlentities($a["Code"] . " | " . $a["Name"]) . " ";
echo '<option>' . $inputValue;
}
?>
</datalist>
</div>
This is what i have now, however the user can type and submit things that are not in the list and i can not allow this. How can i stop this from happening?
Alert the user if the field has a incorect value
$('input[type="submit"]').on('click',function(e) {
$datalistval= $('#ItemSelect').val();
if ($('option[value="'+$datalistval+'"]').length == 0) //if no option is found alert the user
{
alert('incorect datalist value');
e.preventDefault();
}
});
jsfiddle: https://jsfiddle.net/ev63ghwk/
If you're willing to use jQuery UI's autocomplete this would work:
<?php // tweak the below to use your data
$arr = array( array('Name' => 'one'), array('Name' => 'two'), array('Name' => 'three') );
$optsArr = array();
foreach ($arr as $a) {
array_push( $optsArr , '"'.htmlentities( $a["Name"] ).'"' ); ;
}
$options = implode(",", $optsArr)
?>
var availableTags = [<?php echo $options ?>];
$(function() {
$( "#ItemSelect" ).autocomplete({
source: availableTags,
change: function (event, ui) {
if(!ui.item){
//http://api.jqueryui.com/autocomplete/#event-change -
// ui.item property is null if the input was not found in the list
$("#ItemSelect").val("");
}
}
});
});
Here's a working Demo
I am having problem solving the following:
I have a form with one search field (with autosuggest).
In this field I would like to be able to type a name or mobile.nr.
Based on what I type I get suggestions, so typing letters or numbers returns: name and mobile based on matches in the database.
If no match is found a "create customer" button shall appear.
If a match is found a "create work-card" button shall appear.
In my code below I am getting all the data from my customer table, but I can not figure out how to make it show in list form with one row per result including the persons name and mobile in the autosuggest ex:
suggestion 1: name and mobile
suggestion 2: name and mobile
suggestion 3: name and mobile
etc…..
My autosuggest script:
<script type="text/javascript">
$(document).ready(function() {
//autocomplete
$(".input_name_or_mobil").autocomplete({
source: "search.php",
minLength: 1
});
});
</script>
The script searches in my search.php file:
<?php
if ( !isset($_REQUEST['term']) )
exit;
$connect = mysql_connect('localhost', 'root', '') or die( mysql_error() );
mysql_select_db('workcard');
$results = mysql_query('SELECT name AS shout FROM customer WHERE name LIKE "'. mysql_real_escape_string($_REQUEST['term']) .'%" UNION SELECT mobil FROM customer WHERE mobil LIKE "'. mysql_real_escape_string($_REQUEST['term']) .'%" ORDER BY 1 LIMIT 10', $connect);
$data = array();
if ( $results && mysql_num_rows($results) )
{
while( $row = mysql_fetch_array($results, MYSQL_ASSOC) )
{
$data[] = array(
'label' => $row['shout'],
'value' => $row['shout']
);
}
}
echo json_encode($data);
flush();
?>
If i understood you question:
You are using UNION, so the records will be after each others.
Try this:
$results = mysql_query("SELECT name, mobile FROM customer WHERE name LIKE '" . mysql_real_escape_string($_REQUEST['term']) . "%' OR mobil LIKE '" . mysql_real_escape_string($_REQUEST['term']) . "%' ORDER BY 1 LIMIT 10", $connect);
$data = array();
if ($results && mysql_num_rows($results)) {
while ($row = mysql_fetch_array($results, MYSQL_ASSOC)) {
$data[] = array(
'label' => $row['name'] . " " . $row['mobile'],
'value' => $row['name'] . " " . $row['mobile']
);
}
}
In this code, you will be get back the name and mobile fields form the table, and all the records wher name OR mobil is similar than the term.
Use mysqli_ function because mysql_ functions are deprecated.
i need to get the value of a variable in a javascript function to put it in a textfiled.
Javascripts function:
function obtenerArrendatario(){
arrendatario_id = $.fn.yiiGridView.getSelection('arrendatario');
alert(arrendatario_id);
}
The alert give me the id of the selected row but i need to put the id in the textfield to save/create the form
Gridview
<div class="row">
<?php echo $form->labelEx($model,'zf_arrendatarios_arrendatario_id'); ?>
<?php
$arrendatarios = new ZfArrendatarios;
$this->widget('bootstrap.widgets.TbGridView',
array(
'id'=>'arrendatario',
'selectableRows'=>1,
'selectionChanged'=>'obtenerArrendatario',
'type'=>'striped bordered condensed',
'dataProvider'=>$arrendatarios->search(),
'filter' => $arrendatarios,
'template'=>"{items}\n{pager}",
'columns'=>array(
array('name'=>'arrendatario_id_personal', 'header'=>'DNI',),
array('name'=>'arrendatario_nombre', 'header'=>'Nombre'),
array('name'=>'arrendatario_email', 'header'=>'Email'),
),
));
?>
<?php
echo $form->textfield($model,'zf_arrendatarios_arrendatario_id',array('class'=>'input input_r input_pryk', 'value'=>$arrendatario));
?>
<?php echo $form->error($model,'zf_arrendatarios_arrendatario_id'); ?>
</div>
So i need that id that the function capture to fill my textfield.
I tried
$arrendatario= "<script> document.write(arrrendatario_id) </script>";
But it print me the string not the value.
For your requirement, you can set the textfield value in below js function
function obtenerArrendatario(){
arrendatario_id = $.fn.yiiGridView.getSelection('arrendatario');
$(".input_pryk").val(arrendatario_id );// input_pryk should be class for this text field alone.
}
Then you will get in controller while submitting the form.
I'm implementing a like button in yii,when i click on the button it calls a controller action which increases the number of likes by 1, i show the changed value in the Button label,how do i do it?
here is my view,what do i change ?
<?php $id =$data->id;
$foo = $data->likes;
echo CHtml::ajaxbutton($foo.' '.'Likes',
array('post/like/'.$id),
array(
'type'=>'POST',
'success'=>'js:function(data){
')
);
?>
You should try the following
<?php $id =$data->id;
$foo = $data->likes;
echo CHtml::ajaxbutton($foo.' '.'Likes',
array('post/like/'.$id),
array(
'type'=>'POST',
'replace'=>'#buttonId')
),
array(
'id'=>'buttonId'
);
?>
However, I suggest using sending parameters as data for AJAX like this:
<?php $id =$data->id;
$foo = $data->likes;
echo CHtml::ajaxbutton($foo.' '.'Likes',
array('post/like),
array(
'type'=>'POST',
'data'=>array("id"=>$id),
'replace'=>'#buttonId')
),
array(
'id'=>'buttonId'
);
?>
http://www.yiiframework.com/doc/api/1.1/CHtml#ajax-detail
replace: string, specifies the selector whose target should be replaced by the AJAX