Get the radio button value through ajax to php file - javascript

After clicking the radio button, the value from the radio button is not being passed when the onclick event is triggered. Here is my code:
<form name="Form1" id="color" style="font-size: 100%" action="#">
<input type="radio" name="radio1" id="radio1" onclick = "MyAlert()" value="blue"/>Blue <br /></p>
<p> <input type="radio" name="radio1" id="radio1" onclick = "MyAlert()" value="red"/>Red
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
function MyAlert() {
var radio1=$('input[type="radio"]:checked').val();
var pass_data = {
'radio1' : radio1,
};
alert(pass_data);
$.ajax({
url : "",
type : "POST",
data : pass_data,
success : function(data) {
}
});
return false;
}
</script>
<?php
echo $radio1=$_GET['radio1'];
?>
When I click the radio button, I get the error
Undefined index: radio1
I want to display value of the radio button when clicking it within the same page.

Firstly make ajax to separate PHP page where you will access the radio value. Also make alert after you receive the data.
$.ajax({
url : "post.php",
type : "POST",
data: pass_data,
success : function(data) {
// alert radio value here
alert(data);
}
});
Crete a separate PHP file post.php where you access radio input. Since you are making POST request you need to use $_POST instead of $_GET to get radio button value.
<?php
$radio1 = $_POST['radio1'];
echo $radio1;
?>

<input type="radio" id="status" name="status" value="1" /> Mbyllur<br />
<input type="radio" id="status" name="status" value="0" /> Hapur<br />
function MyAlert()
{
var radio1=$('input[type="radio"]:checked').val();
var pass_data = {
'radio1' : $('input[name=status]:checked').val(),
};
alert(pass_data);
$.ajax({
url : "",
type : "POST",
data : pass_data,
success : function(data) {
}
});
return false;
}

I would use a newer version of jquery .
You can't give two elements the same id.
I would rewrite the code as follow :
$(function() {
$(document).on('change', '[name="radio1"]' , function(){
var val = $('[name="radio1"]:checked').val();
alert(val);
/*
Ajax code 1 (GET) :
$.get('/myurl?val=' + val, function(){
});
Ajax code 2 (POST) :
$.post('/myurl', {val : val}, function(){
});
*/
});
});
<form name="Form1" id="color" style="font-size: 100%" action="#" >
<input type="radio" name="radio1" value="blue"/>Blue <br />
<p> <input type="radio" name="radio1" value="red"/>Red
</form>
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>

Try This -->
<form name="Form1" id="color" style="font-size: 100%" action="#" >
<input type="radio" name="radio1" id="radio1" onclick = "MyAlert()" value="blue"/>Blue <br /></p>
<p> <input type="radio" name="radio1" id="radio1" onclick = "MyAlert()" value="red"/>Red
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
function MyAlert()
{
var radio1=$('input[type="radio"]:checked').val();
//alert(radio1);
var pass_data = {
'radio1' : radio1,
};
//alert(pass_data);
$.ajax({
url : "request.php", // create a new php page to handle ajax request
type : "POST",
data : pass_data,
success : function(data) {
}
});
return false;
}
</script>
request.php
<?php
if(isset($_POST['radio1']))
{
echo $radio1=$_POST['radio1'];
}
?>
Above code handle with ajax so, its not refresh the page.

<script>
$(document).ready(function() {
$("#Enviar").click(function (e) {
var cedula = document.getElementById("Cedula").value;
var Nombre = document.getElementById("Nombre").value;
var Apellido = document.getElementById("Apellido").value;
var Sexo = $('input:radio[name=SexoC]:checked').val();
var Edad = document.getElementById("Edad").value;
var FechaN = document.getElementById("date").value;
var Tele = document.getElementById("tel").value;
var Direccion = document.getElementById("Direccion").value;
var Invitacion = document.getElementById("Invitacion").value;
var CasaG = document.getElementById("CasaG").value;
var Rango = document.getElementById("Rango").value;
var cadena = "Cedula="+cedula+"&Nombre="+Nombre+"&Apellido="+Apellido+"&Sexo="+Sexo+"&Edad="+Edad+"&Fecha="+FechaN+"&Tele="+Tele+"&Direccion="+Direccion+"&Invitacion="+Invitacion+"&CasaG="+CasaG+"&Rango="+Rango;
$.ajax({
type:'POST',
url:'datos/Registrar.php',
data: cadena,
beforeSend: function(){
console.log(cadena);
},
success:function(Resp){
alert(Resp);
}
});
return false;
});
});
</script>

Related

checkbox checked when value same with data from database-javascript

hi everyone please help,
i'm new in javascript, i have checkbox with random value, so i want to when there is data from database same with value in checkbox, checkbox will checked,
this is my checkbox,
#foreach ($loin as $loin)
<div class="custom-control custom-checkbox">
<input class="custom-control-input loincode" type="checkbox" id="{{$loin->sap_code}}" name="sap_code[]"
value="{{$loin->sap_code}}">
<label for="{{$loin->sap_code}}" class="custom-control-label">{{$loin->sap_code}}
</label>
</div>
#endforeach
and this my js
$('.tampilModalUbahPts').on('click',function () {
var id = $(this).data('id');
$('.modal-body form').attr('action','/pts/'+id+'/update');
$.ajax({
url: '/ptspt/getubah',
data: {id : id},
method:'get',
dataType : 'json',
success: function (data) {
$('#lbs').val(data.lbs);
$('.loincode').attr("checked",data.loin== value);
}
});
});
sorry for bad english.
then use this
$('.loincode').each(function( index ) {
$(this).attr("checked",(data.loin && data.loin.filter(x=>(x==$(this).val())).length) ? true : false);
});
var data={loin:["108591","108592"]}
$('.loincode').each(function( index ) {
$(this).attr("checked",(data.loin && data.loin.filter(x=>(x==$(this).val())).length) ? true : false);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="loincode" value="108591" />
<input type="checkbox" class="loincode" value="108592" />
<input type="checkbox" class="loincode" value="108593" />

Submit value of a checkbox through javascript

I am trying to submit values of a form through javascript it contains both text and two checkboxes.
<script>
function SubmitFormData2() {
var preffered_loc = $("#preffered_loc").val();
var relocation = $(".relocation").val();
$.post("r_two.php", { preffered_loc: preffered_loc,relocation: relocation },
function(data) {
$('#results').html(data);
$('#myForm2')[0].reset();
});
}
</script>
<form id="myForm2" method="post" style="margin-left: -10%;">
<input type="text" class="form-control" id="preffered_loc" name="preffered_loc">
<input type="checkbox" name="relocation[]" class="relocation[]" value="Yes">
<input type="checkbox" name="relocation[]" class="relocation[]" value="No" >
<input type="button" id="submitFormData2" onclick="SubmitFormData2();" value="Submit" />
</form>
r_two.php
<?
$preffered_loc = $_POST['preffered_loc'];
$relocation = $_POST['relocation'];
?>
i am able to save the first value but i am not able to save relocation value, can anyone tell how i can save relocation. Important point here is that user can select both checkboxes also
The issue is that $relocation is picking only value yes even if i select 2nd selectbox. can anyone please correct my code
try this.
function SubmitFormData2() {
var preffered_loc = $("#preffered_loc").val();
var relocation = $("#relocation").is(":checked");
var relyn = "";
if(relocation){
relyn = "Yes";
}else{
relyn = "No";
}
$.post("r_two.php", { preffered_loc: preffered_loc,relocation: relyn },
function(data) {
$('#results').html(data);
$('#myForm2')[0].reset();
});
alert("{ preffered_loc: "+preffered_loc+",relocation: "+relyn+" }");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm2" method="post" style="margin-left: -10%;">
<input type="text" class="form-control" id="preffered_loc" name="preffered_loc">
<input type="checkbox" name="relocation[]" id="relocation" />
<input type="button" id="submitFormData2" onclick="SubmitFormData2();" value="Submit" />
</form>
As Satpal said:
You don't need two checkbox, maybe you want a radio button, but one checkbox can be checked = yes, not checked = no. I removed one of them.
You don't have an ID relocation. I changed it.
With the jQuery is(":checked") you get a true or false so I parse it to a Yes or No, following your code.
Since its a checkbox and not a radio user can have multiple selections, for eg:
<input type="checkbox" name="relocation[]" class="relocation" value="Yes">
<input type="checkbox" name="relocation[]" class="relocation" value="No" >
<input type="checkbox" name="relocation[]" class="relocation" value="Both" >
try using the :checked selector,
$( ".relocation:checked" ).each(function(i,v){
alert(v.value)
});
Demo here
I think you should use class for the check-boxes instead of id, because id must be unique for each field. You should try this:
<form id="myForm2" method="post" style="margin-left: -10%;">
<input type="text" class="form-control" id="preffered_loc" name="preffered_loc">
<input type="checkbox" name="relocation[]" class="relocation" value="Yes">
<input type="checkbox" name="relocation[]" class="relocation" value="No" >
<input type="button" id="submitFormData2" onclick="SubmitFormData2();" value="Submit" />
</form>
<script>
function SubmitFormData2() {
var preffered_loc = $("#preffered_loc").val();
var relocation = '';
var sap = '';
$( ".relocation" ).each(function() {
if($( this ).is(':checked')){
relocation = relocation+''+sap+''+$( this ).val();
sap = ',';
}
});
alert(rel);
$.post("r_two.php", { preffered_loc: preffered_loc,relocation: relocation },
function(data) {
$('#results').html(data);
$('#myForm2')[0].reset();
});
}
</script>
Here is a sample code for your reference
<form id="myForm" method="post">
Name: <input name="name" id="name" type="text" /><br />
Email: <input name="email" id="email" type="text" /><br />
Phone No:<input name="phone" id="phone" type="text" /><br />
Gender: <input name="gender" type="radio" value="male">Male
<input name="gender" type="radio" value="female">Female<br />
<input type="button" id="submitFormData" onclick="SubmitFormData();" value="Submit" />
</form>
function SubmitFormData() {
var name = $("#name").val();
var email = $("#email").val();
var phone = $("#phone").val();
var gender = $("input[type=radio]:checked").val();
$.post("submit.php", { name: name, email: email, phone: phone, gender: gender },
function(data) {
$('#results').html(data);
$('#myForm')[0].reset();
});
}
You couldn't select the checkbox elements at all because you weren't including the [] in the selector. You can either escape the brackets as described in this SO Q/A or simply remove the brackets (the example code below does the latter)
I'd suggest using radio buttons as the user can immediately see what the options are. (Have a third option for both)
The code below uses checkboxes and puts all selected options into an array that gets passed along. This will allow the user to use both options
<script>
function SubmitFormData2() {
var preffered_loc = $("#preffered_loc").val();
var relocation = [];
$(".relocation:checked").each(function () {
relocation.push ($this.vak ();
}); // :checked is provided by jquery and will only select a checkbox/radio button that is checked
$.post("r_two.php", { preffered_loc: preffered_loc,relocation: relocation },
function(data) {
$('#results').html(data);
$('#myForm2')[0].reset();
});
}
And don't forget to remove [] from the checkboxes class.
<script>
function SubmitFormData2() {
var preffered_loc = $("#preffered_loc").val();
var relocation = {};
$('.relocation').each(function(index) {
if ($(this).is(':checked')) {
relocation[index] = $(this).val();
}
});
relocation = JSON.stringify(relocation);
$.post("r_two.php", { preffered_loc: preffered_loc, relocation: relocation }, function(data) {
$('#results').html(data);
$('#myForm2')[0].reset();
});
}
</script>
Variable 'relocation' must be an object to contain multiple values, like you said a user can select both YES and NO. And change the checkbox class from relocation[] to relocation.

ajaxForm is not working and not returning error

I get a very weird problem when I want to use jQuery ajaxForm.
I want to set form and upload file with having progress percent.
my ajaxForm function is not fire at all.
here is my code but I cant find out where is the problem because I get no error.
function recieve(res,obj)
{
var frm = res.substr(1,res.length-8);
$('#'+frm).find('.error').each(function(){ $(this).remove(); });
if(obj['alert']!=undefined) $(res).html(obj['alert']);
if(obj['field']!=undefined) {
for(var i in obj['field'])
{
/*$("#"+i).next('.error').remove();*/
if(obj['field'][i]!='') $("#"+i).after('<div class="error avesome OC OBC">'+obj['field'][i]+'</div>');
}
}
if(obj['msgbox']!=undefined) alert(obj['msgbox']);
if(obj['location']!=undefined) document.location = obj['location'];
}
function sendAjax(form,response,loader,progress)
{
var frm = $(form);
frm.ajaxForm({
dataType: 'json',
data: frm.serialize()+'&_ajax=1',
beforeSend: function(){
$("input[type='submit']").attr('disabled','disabled');
$(progress).width('0%').parent('.progress').removeClass('hidd');
},
uploadProgress: function(event, position, total, percentComplete){
var pVel = percentComplete + '%';
$(progress).width(pVel);
},
complete: function(data){
recieve(response,unserialize(data));
$(progress).parent('.progress').addClass('hidd');
$("input[type='submit']").attr('disabled',null);
}
});
return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="setting_form" action="http://127.0.0.1/marketing/users/setting/" method="post" onsubmit="return sendAjax('#setting_form','#setting_form_result','#setting_form_loader','#setting_form_progress');">
<input type="hidden" name="_submit" value="1" />
<input type="hidden" name="data[setting][id]" id="setting_id" value="11" />
<input type="hidden" name="data[setting][data-token]" id="setting_data-token" value="8022735" />
<input type="hidden" name="data[setting][token]" id="setting_token" value="90e18fe55fbc38708456606f4b2b3f96" />
<input type="submit" name="data[setting][submit]" id="setting_submit" value="send" />
<div id="setting_form_progress" class="bar fade"></div>
<div id="setting_form_result"></div>
</form>
i guess you missing the this library
http://malsup.com/jquery/form/
insert the code after
jquery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>

Jquery autosuggest with ajax

I am trying to implement a way in which auto suggest would work with dynamically added input boxes. Everything is working fine with the static input types. i am able to request and retrieve result through ajax with static input types. But when i am trying to do the same thing with the dynamic inputs it is not working here is my code. any help would be appreciated.
<script src="js/jquery.js"></script>
<script src="js/jquery.autoSuggest.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<script type="text/javascript">
$.noConflict();
jQuery(function(){
var rows = 0;
jQuery('#addRow').click(function(){
jQuery('#userRows').append('<div class="userRow"><input type="text" name="users['+rows+'][name]" /><input type="text" name="country" id="inputBox" /><input type="text" name="id-holder" id="id-holder"> <input type="text" id="price" name="users['+rows+'][price]" />Remove name="users['+rows+'][name]"<div>');
rows++;
location.reload();
});
jQuery(document).on('click', '.removeRow', function(){
jQuery(this).closest('.userRow').remove();
});
// Below just used to show the string on submit
});
</script>
<script type="text/javascript">
<?php
$pluginConf = "";
if(isset($_GET) && count($_GET) > 0){
extract($_GET);
if($limit == "") $limit = "10";
if($width == "") $width = "auto";
$pluginConf = '
$(function() {
$("#inputBox").autoSuggest({
ajaxFilePath : "server.php",
ajaxParams : "dummydata=dummyData",
autoFill : "'.$autofill.'",
iwidth : "'.$width.'",
opacity : "0.9",
ilimit : "'.$limit.'",
idHolder : "id-holder",
prices : "price",
match : "'.$match.'"
});
alert("Worked");
});';
} else {
$pluginConf = '
$(function() {
$("#inputBox").autoSuggest({
ajaxFilePath : "server.php",
ajaxParams : "dummydata=dummyData",
autoFill : false,
iwidth : "auto",
opacity : "0.9",
ilimit : "10",
idHolder : "id-holder",
prices : "price",
match : "contains"
});
alert("Worked");
}); ';
}
echo $pluginConf;
?>
</script>
</head>
<body>
<div>
Item Name # Price
</div>
<form method="post" id="usersForm">
<div id="userRows">
Add Row<br />
</div>
<input type="submit" id="submit" value="Submit" />
<!--<input type="text" name="xxx" id="inputBox">
<input type="text" name="id-holder" id="id-holder">
<input type="text" name="price" id="price"> -->
</form>
</body>
</html>
https://github.com/wuyuntao/jquery-autosuggest/blob/master/jquery.autoSuggest.js
Looking at the code, it seems it only attaches these events (focus) to elements that are created on page load. You would need to write some additional code to add "suggests" to generated input elements.
https://api.jquery.com/on/ use this function.

How to Hide a ID that incrments

So I'm trying to hide a ID tag that increments depending on how many input fields there are.
I included the HTML at the bottom for the input forms
The numbers at the end of deviceTemplate_(incremented numbers)
ex. deviceTemplate_1 is input field 1
deviceTemplate_2 is input field 2
$(function () {
// Other Code
// Trying to use this to hide fields
var fieldlistSelect = '#deviceTemplate_' + pliPosition;
//var $loader = $('section[role="main"]');
var $loader = form.parent();
//if this exists, then it will execute the following. It will check the whole HTML page.
$loader && $loader.showLoading();
$.ajax({
type: "POST",
url: form.attr('action'),
data: form.serialize(),
dataType: 'html'
}).done(function(html) {
$loader && $loader.hideLoading();
$(fieldlistSelect).html(html);
$loader && $loader.hideLoading();
$(fieldlistSelect).html(html);
//Code I'm trying to get to work, not nessecary to use I'm just stuck
$('.vinCartApplyButton').click(function(ev) {
var aim = $(this);
var ap = aim.parent();
var newbk = ap.clone(true);
var apindex = $('[id^=deviceTemplate_]').index(ap);
var bkId = 'deviceTemplate_' + (apindex + 1);
newbk.addId('deviceTemplate_' + (apindex + 2));
ap.after(newbk);
});
//alert(html);
}).fail(function(jqXHR) {
//if this exists, then it will execute the following
$loader && $loader.hideLoading();
var html = jqXHR.responseText;
//alert(html);
});
});
});
<div class="vinCartFormStyling">
<form action="DeviceProcessing-AjaxValidate" method="post" onsubmit="return false;" id="deviceform1">
<fieldset id="deviceTemplate_1"><div class="vinBox">
<BR><div class="vinText"></div>
<BR><input type="text" onblur="convertCase(this)" name="DeviceId" maxlength="17" size="20"
value="" class="inputfield_en" />
</div>
</fieldset>
<input type="submit" class="device_form vinCartApplyButton" value="Apply">
<input type="hidden" name="Platform" value="ALP-HDD">
<input type="hidden" name="SKU" value="xxxxxxx">
<input type="hidden" name="Position" value="1">
<input type="hidden" name="PLIUUID" value="abcd1234" id="PLIUUID">
</form>
</div>

Categories

Resources