jQuery, AJAX form processing - Radio button value issues, - php

I've got the following form - 2 radio buttons in my A.php
<form action="form_processing.php" method="post" id ="myForm">
<div class="radio-inline">
<label>
<input type="radio" name="direction" id="direction" value="up" checked>Up
</label>
</div>
<div class="radio-inline">
<label>
<input type="radio" name="direction" id="direction" value="down" >Down
</label>
</div>
<input type="hidden" name="status" value="false">
<br/>
<button type="submit" name="sub" id="sub">Submit</button>
</form>
Then I've got the following jQuery A.js,
$('#myForm').on('submit', function(){
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value){
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
console.log(response);
}
});
return false;
});
Then on my form_processing.php I've got,
<?php
print_r($_POST);
?>
When I monitor my console, no matter what I seem to do, I always end up getting...
Array
(
[direction] => down
[status] => false
)
I've spent 2 days trying to figure out but.. can't find the cause of the problem why values of the radios are not updated....
To be more specific - works on IE10/11, doesn't work on chrome (tried to clear the browsing data etc etc..still not working)
Can someone plz guide me on where I went wrong?
Thanks alot,

The problem is that you are manually looping over all your inputs, regardless whether a radio button is checked or not. So when you are at the second radio button with the same name as the first, you overwrite your previous value.
You should probably let jQuery handle this by using:
data: $(this).serialize(),
You could of course manually check for the type of input and whether it is checked as well...
As I mentioned in my comment, you should only use an ID once per page as the ID has to be unique but that is not related to your problem.

Related

JSON : Select Radio button base on response

How I could populate the checked state of radio buttons depending on data loaded from the database?
I want to get data radio button for this form
<div class="col-md-4">
<label>
<input type="radio" name="menu_status" class="flat-red" value="1"> Enable
</label>
<label>
<input type="radio" name="menu_status" class="flat-red" value="0"> Disable
</label>
this my array result
{"menu_id":"00001","parent_id":"0 ","menu_name":"Dashboard","menu_title":"Dashboard","url":"dashboard_c","position_menu":"1","parent_status":"0","menu_status":"1","fa_icon":"fa-dashboard","type":"1"}
and I am pass that result through ajax like this
$.ajax({
url : "<?php echo site_url('cpanel/form_c/data_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="menu_id"]').val(data.id);
$('[name="parent_id"]').val(data.parent_id);
$('[name="menu_name"]').val(data.menu_name);
$('[name="menu_title"]').val(data.menu_title);
$('[name="url"]').val(data.url);
$('[name="order"]').val(data.position_menu);
$('[name="parent_status"]').val(data.parent_status);
//$('[name="menu_status"]').val(data.menu_status);
$('[name="fa_icon"]').val(data.fa_icon);
$('[name="type_form"]').val(data.type);
$.each (data, function (i, obj) {
$(':radio[name="menu_status"][value=' + obj.menu_status + ']').prop('checked', true);
});
/*if (data.parent_status===1) {
$('[name="menu_status"]').val("1").prop('checked',true);
} else {
$('[name="menu_status"]').val("0").prop('checked',true);
}*/
$('#modal_form').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Menu'); // Set title to Bootstrap modal title
},
Can someone help me to take the json data to select the appropriate choices?
var data = {"menu_id":"00001","parent_id":"0 ","menu_name":"Dashboard","menu_title":"Dashboard","url":"dashboard_c","position_menu":"1","parent_status":"0","menu_status":"1","fa_icon":"fa-dashboard","type":"1"}
console.log(data.menu_status)
$('input[name=menu_status][value='+data.menu_status+']').prop('checked', true)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-4">
<label>
<input type="radio" name="menu_status" class="flat-red" value="1">Enable
</label>
<label>
<input type="radio" name="menu_status" class="flat-red" value="0">Disable
</label>
</div>
try this way, the check radio button will be equal to what data.menu_status value is
Looks like the radio button class is flat-red. You could simply use this one instead of going with complex selectors.
You could use a condition instead.
if (data.parent_status == 1) {
$('.flat-red').checked = true;
}

what makes isset null/empty

I have several places that's returning empty and I am not sure why.
One place is using ajax. When an user clicks on the radio button, the value Y or N is sent upon clicking the radio button. When I go to my controller and do echo $_POST['vote']; it is always returning an empty value.
var value = $(this).val();
$.ajax( {
type: "POST",
url: url,
data: {'vote':value},
success: function(data){
alert(data);
}
})
Another place is when i do an ajax upload on a file using a form. On change of the upload field, it always return empty as well. So when I tried isset$_POST[Image] I am always getting a blank. It sees that all my file upload instance is blank.
So what would be the cause of these blanks? I also tried $_GET doesn't help much.
*****[EDIT]*********
<form id="vote-form" action="/some/path?r=shop/vote" method="post">
<input id="ytvote" type="hidden" value="" name="vote[hot_not]">
<span id="vote_hot_not">
<input class="fire-toggle" value="Y" type="radio" name="Vote[hot_not]" data-radio-fx="Vote[hot_not]" style="display: none;"><a title=" " data-radio-fx="Vote[hot_not]" class="radio-fx" href="#"><span class="radio"></span></a>
<label style="display:inline" for="Vote_hot_not_0"><img src=" /images/site/red-hot-not.png" id="hot-i"> </label>
<!--input class… fire-toggle-->
<input class="fire-toggle" value="N" type="radio" name="Vote[hot_not]" data-radio-fx="Vote[hot_not]" style="display: none;"><a data-radio-fx="Vote[hot_not]" class="radio-fx" href="#"><span class="radio"></span></a> <label style="display:inline" for="Vote_hot_not_1"><img src=” /images/site/hot-not.png" id="not-i"></label></span>
</form>
Now in my fire-toggle I have:
$(".fire-toggle").click(function() {
var value = $(this).val();
var url = "<?php echo Yii::app()->createUrl('shop/vote');?>";
$.ajax( {
type: "POST",
url: url,
data: {'vote':value},
success: function(data){
alert(data)
}
})
});
So value actually gives me the expected value..
and here in the controller... I simplified everything down to this:
$pid =Yii::app()->request->getQuery('id');
$uid = yii::app()->user->user_id;
$model = PrototypeReview::model()->getUserVote($uid, $pid);//also tried hard code numbers
$response = $_POST['vote']; //there's nothing in here!
echo $_POST['vote'];

jQuery send post variable using ajax and submit form

I have html form with dynamical number of fields, for example:
<form id="myform">
<input type="text" id="input1">
<input type="text" id="input2">
<input type="text" id="input3">
...
<input type="text" id="inputN">
<span id="button_click"> CLICK </span>
</form>
and jQuery which is:
$("#button_click").click(function(){
$.post("myfile.php",
{
XXXX:YYYY
},
function(data,status){
// do anyting
});
});
I don't know the exact number of fields, so I can't fill XXXX - post variable name, and YYYY - field data from web page.... so I can't count/write one by one...
How can I submit whole form, through post variables, using AJAX and click button?
Sounds like you're looking for the .serialize() method:
$.post("myfile.php",
$("#myform").serialize(),
function(data,status){
// do anyting
});
http://api.jquery.com/serialize/
//rough code for general puporse of storing values for post
var obj = $("#myform"),
data = {};//to hold the values
obj.find('[name]').each(function(index, value) {
name = obj.attr('name'),
value = obj.val();
data[name] = value;
});
$.post("myfile.php",
data: data,
function(data,status){
// do anyting
});

Submit checkbox ID and textfield value without refreshing browser using Ajax

i'm new to programming. I need to develop a rating system with check boxes and text-fields where user clicks the subjects from the list and add his rating/experience in the text field as shown in below image.
This is my HTML code.
<form action="" method="post">
<input type="checkbox" id="1" name="cb[1]" value="" onclick="document.getElementById('t1').disabled=!this.checked;" />
<label for="1">Checkbox No. 1</label>
<input type="number" max="5" min="1" id="t1" name="t[1]" value="" disabled="disabled" /><br /><br />
<input type="checkbox" id="2" name="cb[2]" value="" onclick="document.getElementById('t2').disabled=!this.checked;"/>
<label for="2">Checkbox No. 2</label>
<input type="number" max="5" min="1"id="t2" name="t[2]" value="" disabled="disabled" /><br /><br />
<input type="checkbox" id="3" name="cb[3]" value="" onclick="document.getElementById('t3').disabled=!this.checked;"/>
<label for="3">Checkbox No. 3</label>
<input type="number" max="5" min="1"id="t3" name="t[3]" value="" disabled="disabled" /><br /><br />
<input type="checkbox" id="4" name="cb[4]" value="" onclick="document.getElementById('t4').disabled=!this.checked;"/>
<label for="4">Checkbox No. 4</label>
<input type="number" max="5" min="1"id="t4" name="t[4]" value="" disabled="disabled" /><br /><br />
<input name="submit" type="submit" value="Submit" />
</form>
This is my php function.
global $usedTexts;
$usedTexts = array();
function postdata(){
if ( isset($_POST['submit']) && array_key_exists("t", $_POST) && is_array($_POST["t"]) && array_key_exists("cb", $_POST) && is_array($_POST["cb"])) {
$usedTexts = array_intersect_key($_POST["t"], $_POST["cb"]);
foreach($usedTexts as $subjectId=>$subjectExp){
if($subjectExp!=null){
echo "This is checkbox id = " . $subjectId . " and This is text field value = " . $subjectExp . "<br />";
}
}
}
}
I'm using wordpress and I want to submit checkbox ID and text Field value without refreshing the browser using Ajax. And also I want to display check box id and value as shown in the picture. I would be very much appreciated if someone can provide ajax code for this. Thanks :)
You can code this using XMLHttpRequest Object or an easier not necessary better is using JQuery. JQUERY AJAX API
Then you can do something like this
$('form').submit(function(event) { //make sure you give your form an ID
event.preventDefault();
$.ajax({ // Initiate an ajax call
type: "POST", // You seem to want post HTTP call
url: "URLPATH/youphpcode.php",
dataType: "json", // this is the data type to return usually JSON
data: votes,//data to send USUALLY JSON or hashmap/array
success: function(d)
{
$('#displayMSG').HTML('Your Votes have been submitted') // Maybe display a message or error.
}
});
});
To find out what fields they enabled and selected the values I have added a script here.
http://jsfiddle.net/eMEYP/10/
var votes = {}; // initialize it globally
$('#form').submit(function (event) {
event.preventDefault();
var votes = {}; // reset and empty the votes
$('input[type=number]:enabled').each(function (i) { // Check inputs by type and which are enabled and run a for each
votes[$(this).attr('id')] = $(this).val(); // Add items to the hashmap
});
var json = JSON.stringify(votes); //you can send DATA as the HASH or stringify it.
});
FULL CODE *
$('form').submit(function(event) { //make sure you give your form an ID
event.preventDefault();
var votes = {}; // reset and empty the votes
$('input[type=number]:enabled').each(function (i) { // Check inputs by type and which are enabled and run a for each
votes[$(this).attr('id')] = $(this).val(); // Add items to the hashmap
});
$.ajax({ // Initiate an ajax call
type: "POST", // You seem to want post HTTP call
url: "URLPATH/youphpcode.php",
dataType: "json", // this is the data type to return usually JSON
data: votes,//data to send USUALLY JSON or hashmap/array
success: function(d)
{
$('#displayMSG').HTML('Your Votes have been submitted') // Maybe display a message or error.
}
});
});
Use JQuery to prevent the default submit behavior of the form when you click the Submit button. It is like this but it is incomplete:
$('#form').submit(function(event){
event.preventDefault(); //This line prevents the default submit action of the id #form
//Put your AJAX code here that will submit your checkbox and textbox data
})
See http://api.jquery.com/submit/

Issue with posting data in PHP

Issue
I have a script that's been running fine since forever. It never gave any issues. It was last used in December with no issues whatsoever. No one changed anything. But now, it doesn't work. What it's supposed to do is submit a review and then notify users about the review. But it's not entering that section were it saves and notifies.
What I Have Done And Results
I have taken out that specific piece of the script that saves and notifies users, and tested it. It doesn't return anything which means it doesn't enter it. I've checked the post data, and that displays correct. I have also forced correct data to be posted (by changing params = $('#reviewForm').serialize(); to params = 'counter=1'.
My Code
Here is the form that is filled in by the user:
<form id="reviewForm">
Employee that will be reviewed: <input type="text" id="reviewed" name="reviewed" class="items"/><br>
<div id="openReviews" class="ui-corner-all ui-state-error" style="padding: 5 5 5 5"></div>
Employees that will do the review:<br>
<div id="reviewee_1">
<ul><b>Employee 1:</b>
<li>Name: <input type="text" id="reviewer_1" name="reviewer_1" class="items"/></li>
<li>Position: <select id="position_1" name="position_1" class="items">
<option value="sup">Supervisor</option>
<option value="supp">Peers: Support</option>
<option value="tech">Peers: Technical</option>
<option value="sub">Sub-Ordinate</option>
</select></li>
</ul>
</div>
<input type="hidden" id="counter" name="counter" value="1" class="items"/>
Add Another Reviewer <input type="button" id="add" value="Go >>"/><br>
<input type="button" onClick="sendInfo()" value="Create Review"/>
</form>
When Create Review is clicked, it calls this piece of jQuery code:
function sendInfo()
{
if($('#reviewed').val() != "")
{
var params = $("#reviewForm").serialize();
$.post('reviews.php',
params, // as stated, even if I change this to counter = 1, it doesn't work
function(data) {
$('#reviewForm').hide();
$('<p>' + data + '</p>').insertBefore('#reviewForm');
});
}
else
{
alert("Please complete all fields in this form!");
}
}
And then lastly, the code that processes the request:
if($_POST['counter'] > 0) // check if review was submitted
{
// do stuff...
// it doesn't even enter this...
}
Question
Did something change in the PHP or jQuery specs that could cause this to stop working?
Is there something that I'm missing?
What's going on!?
Please help!
All depends on what JQuery version you use.
I would replace:
var params = $("#reviewForm").serialize();
to
var params = {};
$.each($("#reviewForm").serializeArray(),function(key, elem){ params[elem.name] = elem.value });
and for post i would use
$.ajax({
type: "POST",
'url': 'reviews.php',
'cache': false,
'async': true,
'data': params
}).done(function( data ) {
$('#reviewForm').hide();
$('<p>' + data + '</p>').insertBefore('#reviewForm');
}); //before ; you can use 'fail' methot to catch errors

Categories