How to get value from multiple input with codeigniter [duplicate] - javascript

This question already has answers here:
Getting data from post array in CodeIgniter
(5 answers)
Closed 6 years ago.
I have a problem to send multiple data to controller.
$target is result from post('warna'). How do I get all data?
<form action="http://localhost/starsc/trueaccon2194/opsional" id="form" method="post" accept-charset="utf-8">
<div class="row">
<div class="col-md-12 input group kolom">
<div id="warna1" style="padding-left:0;padding-right:0;" class="col-md-12 col-sm-12 col-xs-12">
<input type="text" id="warna1" name="warna[]" class="joss form-control">
<br>
</div>
<div id="warna2" style="padding-left:0;padding-right:0;" class="col-md-12 col-sm-12 col-xs-12">
<input type="text" id="warna2" name="warna[]" class="joss form-control">
<br>
</div>
<div id="warna3" style="padding-left:0;padding-right:0;" class="col-md-12 col-sm-12 col-xs-12">
<input type="text" id="warna3" name="warna[]" class="joss form-control">
<br>
</div>
<button type="button" class="simpan_warna btn btn-primary">Simpan</button>
</form>
$('.simpan_warna').click(function() {
var UrlToPass = $("#form").serialize();
$.ajax({ // Send the credential values to another checker.php using Ajax in POST menthod
type: "POST",
data: UrlToPass,
url: baseURL + "trueaccon2194/opsional/proses_tambah_opsi_warna",
beforeSend: function() {
$('.simpan_warna').prop('disabled', true);
$('.simpan_warna').html('sedang menyimpan...'); //Loading button text
},
success: function(success) { // Get the result and asign to each cases
$('.simpan_warna').prop('disabled', false);
$('.simpan_warna').html('Simpan'); //reset button text to original text
alert('Data Berhasil disimpan!');
$('#modal_form').modal('hide');
location.reload();
},
error: function() {
$('.simpan_warna').prop('disabled', false);
$('.simpan_warna').html('Simpan'); //reset button text to original text
alert('Data gagal disimpan!');
}
});
return false;
});
my controller is :
function proses_tambah_opsi_warna(){
$target = $this->input->post('warna[]');
if($this->input->post()){
$data = $this->input->post();
$data['nama_depan'] = $this->data['nama_depan'];
$this->opsional_adm->add_warna($data);
log_helper("warna", "Menambah Warna ".$target."");
}else{
log_helper("warna", "Gagal Menambah warna baru");
}
}

Try to get the 'warna' post value, not the 'warna[]' :
$target = $this->input->post('warna');
With this, $target will be an array and you'll able to access values with a loop like this :
foreach ($target as $id => $value) {
echo $value;
}

Related

Submit HTML forms that contain dynamic IDs

I have 2 HTML forms that contain dynamic ID attributes. What I want is to store data with AJAX call from each HTML form separately. Currently AJAX call works only for one HTML form when I use static ID name "surveyImage".
I don't know how I can with jQuery to call method submit() individually for each form. Is there any way to resolve this issue?
Form with id="surveyImage13"
<form method="POST" action="http://localhost/1/467/survey" accept-charset="UTF-8" id="surveyImage13" role="form" class="form-material m-t-40" novalidate="novalidate">
<div class="row">
<div class="col-lg-12">
<input name="questionnaire_pivot_id" id="questionnaire_pivot_id13" class="questionnaire_pivot_id" type="hidden" value="13">
<input name="questionnaire_id" id="questionnaire_id" class="questionnaire_id" type="hidden" value="1">
<input name="survey_image_id" id="survey_image_id" class="survey_image_id" type="hidden" value="467">
...
<div class="row" style="margin-bottom: 5%;">
<div class="col-xl-2 col-lg-3 col-md-3">
<button id="add" class="btn btn-default btn-md-6" type="submit" style="margin-top: 11%;">Save</button>
</div>
</div>
</form>
Form with ID="surveyImage18"
<form method="POST" action="http://localhost/2/467/survey" accept-charset="UTF-8" id="surveyImage18" role="form" class="form-material m-t-40" novalidate="novalidate">
<div class="row">
<div class="col-lg-12">
<input name="questionnaire_pivot_id" id="questionnaire_pivot_id18" class="questionnaire_pivot_id" type="hidden" value="18">
<input name="questionnaire_id" id="questionnaire_id" class="questionnaire_id" type="hidden" value="2">
<input name="survey_image_id" id="survey_image_id" class="survey_image_id" type="hidden" value="467">
...
</div>
</div>
<div class="row" style="margin-bottom: 5%;">
<div class="col-xl-2 col-lg-3 col-md-3">
<button id="add" class="btn btn-default btn-md-6" type="submit" style="margin-top: 11%;">Save</button>
</div>
</div>
</form>
AJAX call
<script type="text/javascript">
$("#surveyImage13").validate({
rules: {
'responses[]': {
required:true
}
},
// change name of error class that is assigned to input fields
errorClass: 'error_validate',
errorPlacement: function (label, element) {
// default
if (element.is(':radio')) {
label.insertAfter(element.parent('.form-check-inline'));
}
else {
label.insertAfter(element);
}
}
});
</script>
<script type="text/javascript">
$("#surveyImage13").submit(function(e) {
e.preventDefault();
var route=$('#surveyImage13').attr('action');
var pivot_id = $("#questionnaire_pivot_id").val();
// Get values of checked checkboxes
var responses = $('.form-check-inline input').filter(':checked').map(function() {
return this.value;
}).get();
var isFormValid = $("#surveyImage13").valid();
if(isFormValid){
$.ajax({
type: "POST",
url: route,
data: {'responses': responses, 'pivot_id': pivot_id},
success: function(response){
$("#surveyImageForm").css("display", "none");
$("#surveyImageAjax").css("display", "block");
$('#SurveyTableAjaxColumn1').append(response[1]);
$('#SurveyTableAjaxColumn2').append(response[0]);
},
error: function(){
console.log('Error');
}
})
}
});
</script>
Why not give your forms a common class
$('.myClass').validate({ ...
})
$('.myClass').submit(...
Based on your provided configuration, it should not be possible for jQuery to perform the submit action. The jQuery selector is #surveyImage, which does not match any id attributes in the provided HTML.
<form id="surveyImage13">...</form>
<form id="surveyImage18">...</form>
$("#surveyImage").submit...
I think you may be able to resolve the issue by using a different query selector string.
$('#surveyImage13 #surveyImage18').submit...
or...
$('form[id^="surveyImage"]').submit...
1.Instead of submit event use button click event
2.Get form id and store it
3.use this variable where you need id
$(".btn").click(function(e) {
e.preventDefault();
var formId = '#'+ $(this).parents('form').attr('id');
var route=$(formId).attr('action');
var pivot_id = $("#questionnaire_pivot_id").val();
// Get values of checked checkboxes
var responses = $('.form-check-inline input').filter(':checked').map(function() {
return this.value;
}).get();
var isFormValid = $(formId).valid();
if(isFormValid){
$.ajax({
type: "POST",
url: route,
data: {'responses': responses, 'pivot_id': pivot_id},
success: function(response){
$("#surveyImageForm").css("display", "none");
$("#surveyImageAjax").css("display", "block");
$('#SurveyTableAjaxColumn1').append(response[1]);
$('#SurveyTableAjaxColumn2').append(response[0]);
},
error: function(){
console.log('Error');
}
})
}
});
Thanks for all answers but I found solution. Im working in LARAVEL therefore I used foreach loop based on which i was able to assign dynamic ID on HTML forms.
#foreach($questionnaire_by_images as $t)
<form id="surveyImage{{$t->id}}">...</form>
<form id="surveyImage{{$t->id}}">...</form>
#endforeach
script
#foreach($questionnaire_by_images as $t)
<script type="text/javascript">
$( document ).ready(function() {
$("#surveyImage{{$t->id}}").validate({
rules: {
'responses[]': {
required:true
}
},
// change name of error class that is assigned to input fields
errorClass: 'error_validate',
errorPlacement: function (label, element) {
// default
if (element.is(':radio')) {
label.insertAfter(element.parent('.form-check-inline'));
}
else {
label.insertAfter(element);
}
}
});
$("#surveyImage{{$t->id}}").submit(function(e) {
e.preventDefault();
var route=$('#surveyImage{{$t->id}}').attr('action');
var survey_image_pivot = $("#survey_image_pivot{{$t->id}}").val();
// Get values of checked checkboxes
var responses = $('.form-check-inline .radio{{$t->id}}').filter(':checked').map(function() {
return this.value;
}).get();
var isFormValid = $("#surveyImage{{$t->id}}").valid();
if(isFormValid){
$.ajax({
type: "POST",
url: route,
data: {'responses': responses, 'survey_image_pivot': survey_image_pivot},
success: function(response){
$("#surveyImageForm{{$t->id}}").css("display", "none");
$("#surveyImageAjax{{$t->id}}").css("display", "block");
$('#SurveyTableAjaxColumn1{{$t->id}}').append(response[1]);
$('#SurveyTableAjaxColumn2{{$t->id}}').append(response[0]);
},
error: function(){
console.log('Error');
}
})
}
});
});
</script>
</script>
#endforeach

Dynamically Pass Form ID Into Function

I have several forms on a page and i want to utilize the same ajax function. It works great for one form since I am grabbing the id with getElementById and then passing it to my ajax function. What I am trying to do is pass down the id of the form onSubmit dynamically.
form
<form id="postData" name="business" method="post" action="{{ path('location_graph', {'location_id': location.getId }) }}"
class="m-form m-form--fit m-form--label-align-right">
<div class="form-group m-form__group row">
<label class="col-2 col-form-label required" for="description">Business
Description</label>
<div class="col-7">
<input type="text" class="form-control m-input" id="description"
name="extra[description]">
</div>
</div>
...
<div class="form-group m-form__group row">
<button type="submit" class="btn m-btn--square btn-outline-primary">
Submit
</button>
</div>
</form>
script
document.getElementById('postData').addEventListener('submit', postData);
function postData(event) {
event.preventDefault();
$.ajax({
type: $(this).attr("method"),
url: $(this).attr("action"),
data: $(this).serialize(),
success: function (data) {
console.log(data);
$('#success__para').html("You data was saved");
}
});
}
You can attach a submit event handler to each of the forms and pass event and this.id (the id of the form element) as arguments.
Javascript:
function postData(event, id) {
event.preventDefault();
var elem = $('#'+id);
$.ajax({
type: elem.attr("method"),
url: elem.attr("action"),
data: elem.serialize(),
success: function (data) {
console.log(data);
$('#success__para').html("You data was saved");
}
});
}
HTML:
<form id="someid" onsubmit="postData(event, this.id)">

How to execute an action when textbox's content has changed?

I have two actions like:
Function getNews: to get list news.
Function searchNews: to get list news base on a keyword.
I create a form to submit that:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<form id="getNew" action="<?php echo admin_url('Xpathnews/searchKeyword') ?>" method="post">
<div class="col-md-12 col-sm-12 col-xs-12">
<h4><b>Select your news</b></h4>
<select id="selectcate" name="selectcate" class="field-custom">
<option value="http://theverge.com">The Verge</option>
<option value="http://neowin.net">Neowin</option>
</select>
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
<h4><b>Keyword:</b></h4>
<input name="search_keyword" id="search_keyword" autocomplete="off" placeholder="Enter your keyword..." />
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
<input name="xpath_title" id="xpath_title" type="hidden" />
</div>
<br>
<div class="col-md-12 col-sm-12 col-xs-12 text-center">
<input name="get_news" type="submit" id="get_news" value="Get News"/>
</div>
</form>
Or fiddle link: https://jsfiddle.net/f7zy0694/2/
I want when the user types any text in textbox search_keyword. Will execute action searchNews.
Usually, the user only clicks button Get News default execute action getNews.
I tried a solution in my controller/action:
public function getNews(){
$xpath_title = $this->input->post('xpath_title');
}
public function searchNews() {
$keyword = $this->input->post('search_keyword');
if(empty($keyword)) {
$this->getNews();
} else {
// execute my code at here
}
}
... is check if $keyword don't have value it will execute function $this->getNews but problem is:
I have some <input> hidden, seem the call to function getNews it not working.
I also tried with seft:redirect("/getNews").
Thanks.
In that you can use Jquery ajax with keyUp or keyDown like:
$(document).ready(function(){
$('#searchbox_id').keyUp(function(){
// get the user entered string
var searchTxt = $(this).val();
$.ajax({
url: 'process_file.php',
type: 'get',
data: {
searchTxt :searchTxt
},
success: function(response){
// do your stuff here
}
});
});
});

codeigniter : form validation jquery

i have a form name nama kategori and then when someone input the nama kategorithat already exist, i want the button become unclickable like when the button being clicked it's not gonna do anything, the problem is i manage to get the error message when input the existing nama kategori, but when i click the button it's still send the data and inputting the data, for more info look the images below
Success Display Error Message
Then i clicked button "Tambah"
it's still adding the data into the tables, i want to prevent that, i want when the button clicked it's not gonna do anything below are my code
JQUERY
$(document).ready(function(){
var check1=0;
$("#kategori").bind("keyup change", function(){
var nama = $(this).val();
$.ajax({
url:'cekData/kategori/nama_kategori/'+nama,
data:{send:true},
success:function(data){
if(data==1){
$("#report1").text("");
check1=1;
}else{
$("#report1").text("*choose another kategori");
check1=0;
}
}
});
});
});
VIEW
<div class="row">
<div class="col s12 m8 l6 offset-m2 offset-l3" align="center">
<form action="<?php echo site_url('kategori/insertKategori') ?>" method="post">
<div class="input-field">
<input id="kategori" name="kategori" type="text" maxlength="40" class="validate" required>
<label for="kategori">nama kategori</label> <span class="error" id="report1"></span>
</div>
<br/>
<button type="submit" class="waves-effect waves-light btn blue darken-1">Tambah</button>
</form>
<br/>
</div>
</div>
CONTROLLER
public function cekData($table, $field, $data){
$match = $this->MKategori->read($table, array($field=>$data), null, null);
if($match->num_rows() > 0){
$report = 2;
}else{
$report = 1;
}
echo $report;
}
You need to make following changes to your jquery code:
$(document).ready(function(){
var check1=0;
$("#kategori").bind("keyup change", function(){
var nama = $(this).val();
$.ajax({
url:'cekData/kategori/nama_kategori/'+nama,
data:{send:true},
success:function(data){
if(data==1){
$("#report1").text("");
check1=1;
$('button[type="submit"]').prop('disabled','');
}else{
$("#report1").text("*choose another kategori");
check1=0;
$('button[type="submit"]').prop('disabled',true);
}
}
});
});
});

Pass an image through AJAX [duplicate]

This question already has answers here:
How can I upload files asynchronously with jQuery?
(34 answers)
Closed 8 years ago.
Basically I want to pass a image file with ajax on submitting a form and retrieve the image and send it by email as an attachment file:
Here's the form :
<form role="form" action="" name="devis" id="devis" method="post" enctype="multipart/form-data" class="form-horizontal">
<fieldset>
<div class="form-group">
<label class="control-label col-md-4" for="societe">Company</label>
<div class="col-md-8">
<input type="text" class="form-control input-md col-md-8" name="societe" value="" maxlength="" id="societe">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4" for="message"><span class="required">* </span>Message</label>
<div class="col-md-8">
<textarea rows="5" name="message" class="form-control input-md col-md-8" maxlength="" required="" style="resize:none;" id="message"></textarea>
</div>
</div>
<div class="form-group" id="input_file">
<label class="control-label col-md-4" for="image_input_field">Logo</label>
<div class="col-md-8">
<div class="input-group uploaddiv">
<span class="input-group-btn">
<span class="btn btn-default btn-file">
Parcourir <input type="file" id="image_input_field" name="file">
</span>
</span>
<input type="text" class="form-control" readonly="">
</div>
</div>
</div>
<div class="form-group">
<div class="form-actions col-md-9 col-md-offset-3 text-right">
<input type="submit" value="Envoyer" name="" class="btn btn-primary" id="submit">
<input type="reset" value="Annuler" name="" class="btn btn-default" id="reset">
</div>
</div>
</fieldset>
</form>
I can't seem to find what's the error in my code ! Here's the AJAX call :
jQuery(document).on("click", "#submit", function(e) {
e.preventDefault();
var fileInput = document.getElementById('image_input_field');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('file', file);
// console.log(file);
var societe = $("input#societe").val();
var message = $("textarea#message").val();
jQuery.ajax({
url: "ajax.php",
type: "post",
data: {
'file': file,
'module' : 'ajax_data_form',
'societe': societe,
'message': message
},
cache: false,
success: function(reponse) {
if(reponse) {
alert(reponse);
// console.log(reponse);
// jQuery('#devis').trigger("reset");
} else {
alert('Erreur');
}
}
});
});
And here's the ajax.php:
<?php
if( isset($_POST['module']) && $_POST['module'] == "ajax_data_form" )
{
var_dump($_FILES);
}
$.ajax({
type: "POST",
url: pathname,
data: new FormData($('#devis')[0]),
processData: false,
contentType: false,
success: function (data) {
$("#divider").html(data);
}
});
and get the file data normally in $_FILES[];. Because FormData is automatically handles the multipart header in an ajax request.
can you try it
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function() {
var fileInput = document.getElementById('image_input_field');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('file', file);
// console.log(file);
var societe = $("input#societe").val();
var message = $("textarea#message").val();
$.ajax({
url: "ajax.php",
type: "POST",
data: "file="+file,
cache: false,
success: function(reponse) {
if(reponse) {
alert(reponse);
// console.log(reponse);
// $('#devis').trigger("reset");
} else {
alert('Erreur');
}
}
});
}); });
</script>
In ajax.php
just write
echo 'something';
As you may know already, it is not possible to process file uploads via ajax calls, it will be possible once HTML5 FILE I/O Api is ready and implemented by major browsers.
You can use jQuery iframe post form plugin to post data in iframe so user experience will be similar to ajax call (partial update of page).
Here is the link:
https://github.com/dogzworld/iframe-post-form
Description: "This jQuery ajax upload plugin creates a hidden iframe and sets the form's target attribute to post to that iframe. When the form is submitted, it is posted (including the file uploads) to the hidden iframe. Finally, the plugin collects the server's response from the iframe."
As mentioned you can send response from the server and display updates on your webpage accordingly.
There has to be a demo page but it is not working as of now.
You can also use it for file uploads.
Calling Example:
jQuery('#frmId').iframePostForm({
json : true,
post : function () {
//return true or false
return true;
},
complete : function (response) {
//complete event
console.log(response);
}
});
Using a Jquery Plugin Called Jquery Form plugin Link
I would suggest to simply submit the form using jquery and what ever data you want you can keep them in hidden fields.
$("#devis").ajaxSubmit(options);
return false;
The you can easily get the file in the php page like this
$ImageTempname = $_FILES['ImageFile']['tmp_name'];
$ImageFilename = $_FILES['ImageFile']['name'];
$ImageType = $_FILES['ImageFile']['type'];
and so on.....

Categories