How do I post the value of a radio button to a database using AJAX? - 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>

Related

How to get value from radio button dynamically

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

Ajax Submitting form Twice

I have a form in a modal window that allows a user to resend a confirmation email. When the form is submitted, the confirmation email is sent twice, instead of once. Everything else is working exactly as it should.
Form is pretty standard:
<form enctype="multipart/form-data" id="ReMailf" name="ReMailf" role="form" data-toggle="validator">
<fieldset>
<div class="row">
<p>You may enter a different email than your original if you wish. However, the original email will remain as the main contact on your application.</p>
<label class="desc" for="prim_email"> Email </label>
<input id="prim_email" name="prim_email" type="email" class="form-control" value="<?php echo $tE['prim_email']; ?>" data-error="Please Enter A Valid Email Address" required/>
<div class="help-block with-errors"></div>
</div>
<div class="row">
<input id="submitForm" name="submitForm" class="btn btn-success" type="submit" value="Resend Conformation "/>
<input name="uniqid" type="hidden" value="<?php echo $tE['unqID']; ?>"/>
<input name="ReMAIL" type="hidden" value="ReMAIL"/>
</div>
</fieldset>
</form>
… and here's the handler:
$(document).ready(function () {
$("#ReMailf").on("submit", function(e) {
var postData = $(this).serializeArray();
// var formURL = $(this).attr("action");
$.ajax({
url: '_remail.php',
type: "POST",
data: postData,
success: function(data, textStatus, jqXHR) {
$('#myModal .modal-header .modal-title').html("YOUR EMAIL HAS BEEN RESENT");
$('#myModal .modal-body').html(data);
// $("#ReMailf").remove();
},
error: function(jqXHR, status, error) {
console.log(status + ": " + error);
}
});
e.preventDefault();
});
$("#submitForm").on('click', function() {
$("#ReMailf").submit();
});
});
I've read a number of other post about this, and tried some of the suggestions, but nothing is working. It either doesn't submit at all, or submits twice.
This is the only form on the page...
Suggestions please?
It is because you are using a button or submit to trigger the ajax event. Use this instead:
$(document).ready(function() {
$("#ReMailf").on("submit", function(e) {
e.preventDefault(); //add this line
var postData = $(this).serializeArray();
// var formURL = $(this).attr("action");
$.ajax({
url: '_remail.php',
type: "POST",
data: postData,
success: function(data, textStatus, jqXHR) {
$('#myModal .modal-header .modal-title').html("YOUR EMAIL HAS BEEN RESENT");
$('#myModal .modal-body').html(data);
// $("#ReMailf").remove();
},
error: function(jqXHR, status, error) {
console.log(status + ": " + error);
}
or you can just use a simple form with action and method. It will do the job

How to transmit my jquery result for processing in my codeigniter ocntroller?

Have a good day.
I am doing a select all checkbox to delete selected posts. I am able to get the result in the jquery but I am not sure how to use that result to process in my Codeigniter Controller. Maybe someone can enlighten me. Thanks!
View File:
<input class="delete_selection" type="checkbox" name="delete_selection[]" value="1" />
<input class="delete_selection" type="checkbox" name="delete_selection[]" value="2" />
<input class="delete_selection" type="checkbox" name="delete_selection[]" value="3" />
<button id="delete_selected" name="delete_selected" class="btn btn-danger btn-small" value="" onClick="return confirm('Delete selected posts?')"><i class="icon-trash icon-white"> </i> Delete Selected</button>
JQuery:
//GET SELECTED POSTS/PAGES FOR DELETION
$("#delete_selected").click(function(event) {
/* stop form from submitting normally */
event.preventDefault();
var values = new Array();
$.each($('input[name="delete_selection[]"]:checked'), function() {
var delete_selection = $(this).val()
console.log(delete_selection);
});
});
Controller:
public function post_delete(){
//HOW TO GRAB THE RESULT FROM THE JQUERY?
//I KNOW IT SHOULD BE IN AJAX BUT NOT QUITE SURE HOW TO DO IT.
$id = $this->input->post('delete_selection');
for( $i=0; $i<sizeof($id); $i++) :
$this->posts_model->delete_post_selection($id[$i]);
endfor;
$data['message_success'] = $this->session->set_flashdata('message_success', 'You have successfully deleted your selected posts.');
redirect('admin/posts/posts_list', $data);
}
Model:
//MULTIPLE DELETE
function delete_post_selection($id) {
$this->db->where_in('post_id', $id)->delete('posts');
return true;
}
Your thinking is wrong, the controller isn't gonna 'grab' the values. But javascript is going to post to the controller
Assuming you put your html inside a form you could do something like this:
view:
<form action="/post_delete">
<input class="delete_selection" type="checkbox" name="delete_selection[]" value="1" />
<input class="delete_selection" type="checkbox" name="delete_selection[]" value="2" />
<input class="delete_selection" type="checkbox" name="delete_selection[]" value="3" />
<button id="delete_selected" name="delete_selected" class="btn btn-danger btn-small" value=""><i class="icon-trash icon-white"> </i> Delete Selected</button>
</form>
JS:
$('#delete_selection').click(function(e){
if(!confirm('Delete?')) return;//ask user if they're sure
//stop default form submitting from happening because
//we'll use ajax
e.preventDefault();
var form = $(this).closest('form');//get the parent form
$.ajax({
url: form.attr('action'),//get url to send it to
type: "POST",
data: form.serialize(),//get data from the form
success: function(){
//do something with success
}
error: function(){
//do something with error
}
});
And now you can use the data in your controller by accessing $_POST try
var_dump($_POST);
to see what has been posted
I am not sure if this is the correct way as it POST repeatedly but does the work so far.
In my JS:
//GET SELECTED POSTS/PAGES FOR DELETION
$("#delete_selection").click(function(event) {
if(!confirm('Delete selected posts?')) return false;//ask user if they're sure
/* stop form from submitting normally */
event.preventDefault();
$.each($('input[name="delete_selection[]"]:checked'), function() {
$.ajax({
type: "POST",
url: 'post_delete_selection',
data:
{ selected: $(this).val() },
success: function(data){
setTimeout(function () {
window.location.href = window.location.href;
}, 1000);
$('#ajax_message').show().html('Successfully deleted.');
},
});
});
});
My Controller:
public function post_delete_selection(){
$selectedIds = $_POST['selected']; //THIS GRABS THE VALUES FROM THE AJAX
$this->posts_model->delete_post_selection($selectedIds);
}
My Model:
function delete_post_selection($selectedIds) {
$this->db->where_in('post_id', $selectedIds)->delete('posts');
return true;
}

issue with ajax event

i am using an ajax event which is triggered when i hit the submit button to add data to the database but since when i orignally created this page they were all in seprate files for testing purposes so now when i have put all the code together i have notice that 4 submit buttons i was using to refresh the page and then change the data being seen by filtering it are triggering the ajax query i have placed the code bellow.. i am quite stumped in what is the only way to go about this...
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(function()
{
$("input[type='checkbox']").on('click', function() {
var $this = $(this);
var isChecked = $this.prop('checked');
var checkVal = isChecked ? $this.attr('id') : $this.attr("value");
var process= $this.attr("value");
var userid = $this.attr('name');
$.ajax({
type: "GET",
url: 'request.php',
data: {
'uname': checkVal,
'id': userid
},
success: function(data) {
if(data == 1){//Success
alert('Sucess');
}
if(data == 0){//Failure
alert('Data was NOT saved in db!');
}
}
});
});
$('form').bind('submit', function(){ // it is triggering this peice of code when the submit buttons are clicked ???
$.ajax({
type: 'POST',
url: "requestadd.php",
data: $("form").serialize(),
success: function(data) {
if(data == 1){//Success
alert('Sucess');
}
if(data == 0){//Failure
alert('Data was NOT saved in db!');
}
}
});
return false;
});
$("#claim").change(function(){
$("#area").find(".field").remove();
//or
$('#area').remove('.field');
if( $(this).val()=="Insurance")
{
$("#area").append("<input class='field' name='cost' type='text' placeholder='Cost' />");
}
});
});
</script>
</head>
<body>
<div id="add">
<form name="form1aa" method="post" id="form1a" >
<div id="area">
<input type=text name="cases" placeholder="Cases ID">
<select id="claim" name="claim">
<option value="">Select a Claim</option>
<option value="Insurance">Insurance</option>
<option value="Warranty">Warranty</option>
</select>
</div>
<select name="type" onChange=" fill_damage (document.form1aa.type.selectedIndex); ">
<option value="">Select One</option>
<option value="Hardware">Hardware</option>
<option value="Software">Software</option>
</select>
<select name="damage">
</select>
<br />
<input type=text name="comment" placeholder="Comments Box">
<input type="submit" value="Submit" name="Submit">
</form>
</div>
<?
$sql="SELECT * FROM $tbl_name ORDER BY cases ASC";
if(isset($_POST['tpc'])){
$sql="select * from $tbl_name WHERE class LIKE '1%' ORDER BY cases ASC";
}
if(isset($_POST['drc'])){
$sql="select * from $tbl_name WHERE class LIKE 'D%' ORDER BY cases ASC";
}
if(isset($_POST['bsc'])){
$sql="select * from $tbl_name WHERE class LIKE 'B%' ORDER BY cases ASC";
}
$result=mysql_query($sql);
?>
<!-- Filter p1 (Start of) !-->
<form action="ajax-with-php.php" target="_self">
<input type="submit" name="all" value="All" /> // the issue is mainly occuring here when i click any of thesse meant to refesh the page and change the query with the if statements but is trigger the other code i commented
<input type="submit" name="tpc" value="TPC" />
<input type="submit" name="drc" value="DRC" />
<input type="submit" name="bsc" value="BSC" />
</form>
$('form').bind('submit', function(){ ...
will bind to all forms. Change it to
$('form#form1a').bind('submit', function(){ ...
and it will only bind to the first form, not the second.
$('form').bind('submit', function(event){
event.preventDefault();
$.ajax({...
Try making the changes above 1) adding the event argument to your callback 2) executing the .preventDefault() method. When using AJAX with the submit event this is neccessary to stop the page from reloading and interrupting your async request.
There may be more issues than that, but hopefully that will get you on the right track.

AJAX form submission issue in Internet Explorer

For some reason the newsletter sign-up form bar I'm creating is not working as it should in IE. In fact, it's not working at all. If you visit the link below in Chrome or Firefox it works like it should, but in any version of IE it doesn't.
Anyone have any leads to fix this?
Here's the code, summarized:
$(function() {
$('#name').textboxhint({
hint: 'First Name'
});
$('#email').textboxhint({
hint: 'Email Address'
});
$("#submitButton").click(function() {
// VALIDATE AND PROCESS FORM
var name = $("#name").val();
var email = $("#email").val();
var dataString = 'name='+ name + '&email=' + email;
// HANDLE DATA: SHOW ERROR IF FIELDS ARE BLANK
if (name=='' || name=='First Name' ){
$('.errorIconName').show();
return false;
}
if (email=='' || email=='Email Address'){
$('.errorIconEmail').show();
return false;
}
else {
$.ajax({
type: "POST",
url: "#",
data: dataString,
success: function(){
$('#signupWidget').fadeOut(400).hide();
$('#thankyouText').fadeIn(700).show();
$('.errorIcon').fadeOut(200).hide();
$('#signupWrap').delay(3000).fadeOut(800);
}
});
}
return false;
});
});
and...
<form action="" method="post">
<span id="sprytextfield1" class="pr20">
<input name="name" id="name" type="text"/>
<div class="errorIconName" style="display:none"></div>
</span>
<span id="sprytextfield2" class="pr20">
<input name="email" id="email" type="text"/>
<div class="errorIconEmail" style="display:none"></div>
</span>
<span>
<input type="submit" name="widgetButton" id="submitButton" value="SUBMIT"/>
</span>
</form>

Resources