How to get value from radio button dynamically - ajax

i am creating a form for searching a client, using either id or email both are set to be unique. Application made on Codeignitor.
I have created a form with two radio buttons, one for search with ID and another for search with mail+dob.
Depending on the radio button selected, corresponding input fields shown.
In controller, it choose the model function based on the radio button value.
This is I coded, i need to pass the value of radio button to Controller.php file
Form(only included the radio button)
$(document).ready(function() {
$("#usingdob").hide();
$("#usingmail").hide();
$("input:radio").click(function() {
if ($(this).val() == "id") {
$("#usingId").show();
$("#usingdob").hide();
$("#usingmail").hide();
} else {
$("#usingId").hide();
$("#usingdob").show();
$("#usingmail").show();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-4">
<label class="radio-inline">
<input type="radio" name="optradio" value="id" checked>Using ID </label></div>
<div class="col-md-4">
<label class="radio-inline">
<input type="radio" name="optradio" value="mail">Using DOB</label>
</div>
I expected to get the radio button value correctlyenter image description here

JS:
$('input[name="optradio"]').click(function(){
var optradio = $(this).val();
//or
var optradio = $("input[name='optradio']:checked").val();
if(optradio == 'id'){
//do your hide/show stuff
}else{
//do your hide/show stuff
}
});
//on search button press call this function
function passToController(){
var optradio = $("input[name='optradio']:checked").val();
$.ajax({
beforeSend: function () {
},
complete: function () {
},
type: "POST",
url: "<?php echo site_url('controller/cmethod'); ?>",
data: ({optradio : optradio}),
success: function (data) {
}
});
}

Try this
<script type="text/javascript">
$( document ).ready(function() {
$("#usingdob, #usingmail").hide();
$('input[name="radio"]').click(function() {
if($(this).val() == "id") {
$("#usingId").show();
$("#usingdob, #usingmail").hide();
} else {
$("#usingId").hide();
$("#usingdob, #usingmail").show();
}
});
});
</script>

One thing I noticed is that you have 'mail' as a value in the DOB option. Another is that there seems to be 3 options and yet you only have 2 radios?
I adjusted the mail value to dob and created dummy divs to test the code. It seems to work.
$(document).ready(function() {
$("#usingdob").hide();
$("#usingmail").hide();
$("input:radio").click(function() {
console.log($(this).val());
if ($(this).val() == "id") {
$("#usingId").show();
$("#usingdob").hide();
$("#usingmail").hide();
} else {
$("#usingId").hide();
$("#usingdob").show();
$("#usingmail").show();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-4">
<label class="radio-inline">
<input type="radio" name="optradio" value="id" checked>Using ID </label></div>
<div class="col-md-4">
<label class="radio-inline">
<input type="radio" name="optradio" value="dob">Using DOB</label>
</div>
<div id="usingId">
Using Id div
</div>
<div id="usingdob">
Using dob div
</div>
<div id="usingmail">
Using mail div
</div>
As far as passing the value to the controller goes, ideally the inputs should be in a form. When you submit the form, the selected value can be passed to the php.
<?php
if (isset($_POST['submit'])) {
if(isset($_POST['optradio']))
{
Radio selection is :".$_POST['optradio']; // Radio selection
}
?>

If you want to get currently checked radio button value Try below line which will return current radio button value
var radioValue = $("input[name='gender']:checked").val();
if(radioValue)
{
alert("Your are a - " + radioValue);
}

Related

MVC 4.x Validate dropdown and redirect to next page

Beginner question:
I have an MVC app where there are three dropdowns on a page. Currently I'm using AJAX to evaluate a drop down on form submission and modify a CSS class to display feedback if the answer to the question is wrong.
HTML:
<form method="post" id="formQuestion">
<div class="container-fluid">
<div class="row">
<div class="col-md-4">
<p>This is a question:</p>
</div>
<div class="col-md-4">
<select id="Question1">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
<div class="col-md-4 answerResult1">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<button class="btn btn-success" type="submit" id="btnsubmit">Submit Answer</button>
</div>
</div>
</form>
AJAX:
#section scripts {
<script>
$(document).ready(function () {
$("#formQuestion").submit(function (e) {
e.preventDefault();
console.log($('#Question1').val())
$.ajax({
url: "/Home/DSQ1",
type: "POST",
data: { "selectedAnswer1": $('#Question1').val() },
success: function (data) { $(".answerResult1").html(data); }
});
})
});
</script>
}
Controller:
public string DSQ1(string selectedAnswer1)
{
var message = (selectedAnswer1 == "3") ? "Correct" : "Feed back";
return message;
}
I have three of these drop downs, that all get evaluated by AJAX in the same way. My question is, how would I go about evaluating all three and then returning a particular View if all three are correct.
I would like to avoid using hard-typed http:// addresses.
You could declare a global script variable prior to your document ready function, this will determine if the fields are valid. See var dropdown1Valid = false, ....
Then on your ajax success function, you could modify the values there. Say in the ajax below, your answering with first dropdown, if your controller returned Correct, set dropdown1Valid to true.
Lastly, at the end of your submit function, you could redirect check if all the variables are true, then redirect using window.location.href="URL HERE or use html helper url.action window.location.href="#Url.Action("actionName");
#section scripts {
<script>
var dropdown1Valid = false;
var dropdown2Valid = false;
var dropdown3Valid = false;
$(document).ready(function () {
$("#formQuestion").submit(function (e) {
e.preventDefault();
console.log($('#Question1').val())
$.ajax({
url: "/Home/DSQ1",
type: "POST",
data: { "selectedAnswer1": $('#Question1').val() },
success: function (data) {
$(".answerResult1").html(data);
if(data == "Correct"){
// if correct, set dropdown1 valid to true
dropdown1Valid = true;
}
// option 1, put redirect validation here
if(dropdown1Valid && dropdown2Valid && dropdown3Valid){
// if all three are valid, redirect
window.location.href="#Url.Action("actionName","controllerName", new { })";
}
}
});
// option 2, put redirect validation here
if(dropdown1Valid && dropdown2Valid && dropdown3Valid){
// if all three are valid, redirect
window.location.href="#Url.Action("actionName", "controllerName", new { })";
}
})
});
</script>
}

How do I post the value of a radio button to a database using AJAX?

I want to be able to post the value of a radio button to a database, without having to submit the form, hence why I have attempted this using 'on change'.
$("input:radio[name=q1_MC]").on("change", function () {
var dunno1 = $(this).serialize();
$.ajax({
url: "get_response.php",
type: "POST",
data: dunno1,
success: function (data) {
console.log("working)";
},
error: function (request, status, error) {
console.log(request.responseText);
}
});
});
My console.log does show when I click one of my radio buttons.
Inside get_response.php I have:
<?php
require("db_connection.php");
if((isset($_POST['your_name']) {
$yourName = $conn->real_escape_string($_POST['your_name']);
$q1_MC = $conn->real_escape_string($_POST['q1_MC']);
$q2 = $conn->real_escape_string($_POST['q2']);
$q3 = $conn->real_escape_string($_POST['q3']);
$q4 = $conn->real_escape_string($_POST['q4']);
$q5 = $conn->real_escape_string($_POST['q5']);
$q6 = $conn->real_escape_string($_POST['q6']);
$q7_MC = $conn->real_escape_string($_POST['q7_MC']);
$q8 = $conn->real_escape_string($_POST['q8']);
$sql="INSERT INTO commenttable (name, q1_MC, q2, q3, q4, q5, q6, q7_MC, q8) VALUES ('".$yourName."','".$q1_MC."', '".$q2."', '".$q3."', '".$q4."', '".$q5."', '".$q6."', '".$q7_MC."', '".$q8."')";
if(!$result = $conn->query($sql)){
die('There was an error running the query [' . $conn->error . ']');
} else {
echo "Thank you! Your feedback is appreciated";
}
}
?>
HTML:
<input type="radio" name="q1_MC" value="Excited"> Excited
<input type="radio" name="q1_MC" value="Optimistic"> Optimistic
<input type="radio" name="q1_MC" value="Indifferent"> Indifferent
<input type="radio" name="q1_MC" value="Nervous"> Nervous
<input type="radio" name="q1_MC" value="Sceptical"> Sceptical
if((isset($_POST['your_name']) will only be true when you submit the whole form. In your case you appear to be posting just the key/value of the radio button.
EG:
$("input:radio[name=q1_MC]").on("change", function() {
var dunno1 = $(this).serialize();
console.log(dunno1);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<label><input type="radio" name="q1_MC" value="test1" />test1</label>
<label><input type="radio" name="q1_MC" value="test2" />test2</label>
</form>

How to save the content of a textarea using Ckeditor and CodeIgniter?

I'm using Codeigniter with Ckeditor. My problem is that when I submit the content, the data from the textarea is not stored in the database. But when I tried it again it finally did. So the situation is like I have to double click submit button to save it.
I stored the downloaded Ckeditor on a folder named ./Assests/Ckeditor(Sorry for the wrong spelling.I'll fix this later.)
Here's my form in my view folder:
ask_view.php:
<form id="form" enctype="multipart/data" method="post" onsubmit="createTextSnippet();">
<div class="form-group">
<label for="exampleInputEmail1">Title</label>
<input type="text" name ="title" class="form-control" id="title" placeholder="Title" required >
</div>
<input type="hidden" name="hidden_snippet" id="hidden_snippet" value="" />
<div class="form-group">
<label for="exampleInputEmail1">Editor</label>
<textarea name ="text" class="form-control" id="text" rows="3" placeholder="Textarea" required></textarea>
</div>
<input type="submit" class="btn " name="submit" value ="Submit" style="width: 100%;background: #f4a950;color:#161b21;">
</form>
<script src="<?php echo base_url('assests/js/editor.js')?>"></script>
<script type="text/javascript">
CKEDITOR.replace('text' ,{
filebrowserBrowseUrl : '<?php echo base_url('assests/filemanager/dialog.php?type=2&editor=ckeditor&fldr=')?>',
filebrowserUploadUrl : '<?php echo base_url('assests/filemanager/dialog.php?type=2&editor=ckeditor&fldr=')?>',
filebrowserImageBrowseUrl : '<?php echo base_url('assests/filemanager/dialog.php?type=1&editor=ckeditor&fldr=')?>'
}
);
</script>
<script type="text/javascript">
//code used to save content in textarea as plain text
function createTextSnippet() {
var html=CKEDITOR.instances.text.getSnapshot();
var dom=document.createElement("DIV");
dom.innerHTML=html;
var plain_text=(dom.textContent || dom.innerText);
var snippet=plain_text.substr(0,500);
document.getElementById("hidden_snippet").value=snippet;
//return true, ok to submit the form
return true;
}
</script>
<script type="text/javascript">
$('#form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/knowmore2/index.php/ask_controller/book_add',
data: $('form').serialize(),
success: function (data) {
console.log(JSON.parse(data));
}
});
});
</script>
Ask_model.php:
public function book_add($data)
{
$query=$this->db->insert('article', $data);
return $query;
}
Ask_controller.php:
public function book_add(){
$data = $_POST;
$details = array();
$details['title'] = $data['title'];
$details['content'] = $data['text'];
$details['snippet'] = $data['hidden_snippet'];
$details['createdDate']=date('Y-m-d H:i:s');
$result=$this->ask_model->book_add($details);
echo json_encode($details);
}
The content with html tags should be save in a column named content in the database, but it didn't save in the first click. It only saves on the second one,but the other data are saved in the first like the title, etc. So I get 2 rows of data, one without the content and the other with one.
Database:

Ajax submit and replace submit button with checkmark after success

First, I'm not having luck with ajax submitting at all in cakephp 1.3 environment. Once I successfully submit, I'm hoping user stays on page and submit button hidden or replaced with a checkmark. I've tried a few things... controller without $action and then .click function instead of on submit. I'm also not versed in debugging js to see where it might be wrong so any suggestions are welcome.
Maybe "update_a" is the $action within my dashboard controller
"function applications($action) {" instead?
dashboard controller
function update_a($action) {
...
switch ($action) {
case 'save':
if (!empty($this->data)) {
// update fields in database table matching model
$this->data['Model']['submitted'] = $_POST['submitted'];
$this->data['Model']['locked'] = $_POST['locked'];
if ($this->Model->save($this->data)) {
// save form fields to other models
$this->OtherModel->saveField('form_status_id',$_POST['form_status_id']);
$this->OtherModel->saveField('form_status',$_POST['form_status']);
}
}
}
break;
default:
//$this->redirect("admin/index");
$this->render("dashboard/applications");
break;
} //case
} // end function
html
<body>
<form id='update_a' action='save'>
<div class='form-group'>
<input type='hidden' class='hidden' name='locked' id='locked' value='1'>
<input type='hidden' class='hidden' name='form_status' id='form_status' value='Locked'>
<input type='hidden' class='hidden' name='form_status_id' id='form_status_id' value='3'>
<input type='hidden' class='hidden' name='submitted' id='submitted' value='<?php echo date("Y-m-d G:i:s") ?>'>
</div>
<div class='text-center'>
<input name='submit' type='button' class='btn btn-default' value='Submit Form A'>
</div>
</form>
</body>
<script>
$(document).ready(function () {
$('#update_a').on('submit', function (e) {
//$('#update_a').click(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/dashboard/update_a',
data: $('#update_a').serialize(),
success: function () {
alert('Form A has been submitted and locked for editing');
$('#update_a').hide();
},
error : function() {
alert("Error");
}
});
return false;
});
});
</script>

Using Validation Plugin, how can i submit form when either one of the checkbox is checked or specific text field is not empty

//Using Validation Plugin, how can i submit form when either one of the checkbox is checked or specific text field is not empty? I have checkboxes which generates dynamically and category_name text field. I want to submit form when either one of the checkbox is checked or category_name text field is not empty...
<?php
while($cat_row = "fetch_result"){
$tr.='<b><input type="checkbox" class="required" name="category[]" value="'.$cat_row['category_name'].'" id="category[]" checked/>'.$cat_row['category_name'].'</b>';
}
?>
//HTML File
<body>
<form id="abc" name="abc" action="PATH_TO_PHPFILE" method="post" enctype="multipart/form-data" >
<div id="cd">
<?=$tr?>
<div id="err"></div>
</div>
<input type="text" name="category_name" id="category_name" class="text_box" value="" />
</form>
<script>
$(function() {
$("form").validate({
rules:{
category:{
required:true,
minlength:2
}
},
errorPlacement: function(error, element) {
error.appendTo('#err');
},
submitHandler: function(form){
var options = {
success:function (data){
$.unblockUI();
//do something
},
beforeSubmit:function (){
//do something
}
};
$(form).ajaxSubmit(options);
}
});
});
</script>
</body>

Resources