PHP keeps picking up last element of radio buttons - php

I have the following problem:
I'm submitting my data from radio buttons to a ajax request so I can move the data to the database.
-html
<form class="siteInfo" action="ajax/site.php?nr=<?php echo $_GET['nr']; ?>" method="POST">
<input type="radio" name="transport_transport_id" value="1"> <span class="value">1</span><br/>
<input type="radio" name="transport_transport_id" value="2"> <span class="value">2</span><br/>
<input type="radio" name="transport_transport_id" value="3" tabindex="21"> <span class="value">3</span><br/>
-The page that ajax posts to
foreach($_POST as $key => $val) {
if(!empty($val)) {
$result[$key] = $val;
//This should be passed to database update function
}
}
var_dump($_POST);
$site->setSiteFields($siteNumber, $result);
-The ajax
$('.siteInfo').on('change', 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;
});
The ajax returns the response it gets from the pickup page but doesn't matter what radio button I pick, I only get the last value returned. Anybody can tell me what goes wrong?
Thanks in advance!

Try this
$('.siteInfo').on('change', function() {
var that = $(this);
url = that.attr('action'),
type = that.attr('method'),
data = {};
data[name] = that.find("input[name='transport_transport_id']:checked").val();
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
console.log(response);
}
});
return false;
});

Related

How to access form data as an array of a JSON object in PHP

I have jQuery Ajax sending form data to a WordPress function.
The PHP function gets the data as a string, like "navn=A&navn2=B", and I use the explode() function to access individual form elements.
I think there is a better way where I can access the form data as an array of JSON objects directly. But I can't figure that out.
How can I fix it?
This is my HTML/jQuery:
<form id='minForm' method="post" action="">
<input type="text" name="navn" value="A">
<input type="text" name="navn2" value="B">
<button>Send</button>
</form>
<script>
jQuery(document).ready(function($) {
var form = $('#minForm');
$(form).submit(function(event) {
event.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: "POST",
url: '/wp-admin/admin-ajax.php',
data: {
action : 'my_ajax_action',
formData : formData,
},
success:function(data) {
console.log(data);
},
});
});
});
</script>
This is my PHP:
add_action('wp_ajax_my_ajax_action', 'my_ajax_action_callback');
function my_ajax_action_callback() {
$form_data = $_POST['formData'];
$form_data_array = explode('&', $form_data);
foreach ($form_data_array as $i) {
echo explode('=', $i)[1] . '<BR>';
}
wp_die(); // Required. to end Ajax request.
}
Serialize your form as an array. Then pass it in the Ajax request.
In the client side:
jQuery(document).ready(function($) {
var form = $('#minForm');
$(form).submit(function(event) {
event.preventDefault();
var formData = $(form).serializeArray();
$.ajax({
type: "POST",
url: '/wp-admin/admin-ajax.php',
dataType: 'json',
data: {
action : 'my_ajax_action',
formData : formData,
},
success:function(data) {
console.log(data);
},
});
});
});
On the server side:
add_action('wp_ajax_my_ajax_action', 'my_ajax_action_callback');
function my_ajax_action_callback() {
$response = ["success" => true];
$form_data = json_decode($_POST['formData']);
error_log(print_r($form_data, 1)); // Log to see the array properties.
if (empty($form_data) {
$response["success"] = false;
}
echo json_encode($response);
//wp_die(); // required. to end AJAX request.
}
Note: The $(form).serializeArray() will give you the form as an array of objects, and it might not be what you expect in the server side to extract data. You can handle the form array before sending to the server by convert it to a simple object:
var formData = $(form).serializeArray().reduce(function(obj,item){
obj[item.key] = item.value;
return obj;
}, {});

AJAX live search working with radio button

I'm able to get jQuery AJAX live search working on an input field and it returns the desired result that I want.
for example : Search for my word returns the desired result .
But Now I want to do a compound search on two fields.
for example :
Search for the word + today
or
Search for the word + tomorrow
This is what I have but it is not working or does not returning any errors.
index.php
<form>
<input placeholder="Search the area" class="input-large search-query" type="text" id="key">
<input type="radio" name="b_selected" class="radio" value="1" > Today
<input type="radio" name="b_selected" class="radio" value="2" > Tomorrow<br>
<div class="result"><div class="loading"></div></div>
</form>
quicksearch.php
include('config.php');
$count= 0;
if(isset($_POST["b_selected"]))
{ $b_selected = $_POST['b_selected']; }
$key = $_POST['key'];
$b_selected = $_POST['b_selected'];
$key = addslashes($key);
$sql = mysql_query("select * from account WHERE b_today='1' and title LIKE '%$key%' ") or die(mysql_error());
While($row = mysql_fetch_array($sql)) {
$count++;
$id= $row['id'];
$title=$row['title'];
if($count<= 10){
search.js
/*quick search*/
$(document).ready( function() {
$(".result").hide();
$("#key").keyup( function(event){
var key = $("#key").val();
if( key != 0){
$.ajax({
type: "POST",
data:{ key: key },
url:"quicksearch.php",
success: function(response) {
$(".result").slideDown().html(response);
}
})
}else{
$(".result").slideUp();
$(".result").val("");
}
})
})
/* Search for work plan for today or Tomorrow*/
$(document).ready(function(){
$('input[type="radio"]').click(function(){
var b_selected = $(this).val();
$.ajax({
url:"quicksearch.php",
method:"POST",
data:{b_selected:b_selected},
success:function(data){
$('#result').html(data);
}
});
});
});
You should POST both variables - the word plus the value of the radio-button. If you POST only the word or only the radio-button - you won't get what you want:
$(document).ready( function()
{
$(".result").hide();
/*quick search*/
$("#key").keyup( function()
{
var key = $(this).val();
var b_selected = $('input[type="radio"]').val();
$.ajax({
method: "POST",
url: "quicksearch.php",
data:
{
key: key,
b_selected: b_selected
},
success: function(response)
{
$(".result").slideDown().html(response);
}
});
});
/* Search for work plan for today or Tomorrow*/
$('input[type="radio"]').click(function()
{
var key = $('#key').val();
var b_selected = $(this).val();
$.ajax({
method: "POST",
url: "quicksearch.php",
data:
{
key: key,
b_selected: b_selected
},
success: function(response)
{
$('#result').slideDown().html(response);
}
});
});
})

Make Checkbox that checked after submit to be visible using ajax

I have a form that takes the attendance of staffs. After submit I need the checkbox to be checked for the selected staffs. The form is submitted through ajax. Below is the code that inserts the attendence of the whole staffs.
var _data = new FormData($('#formaction')[0]);
$.ajax({
type: 'POST',
dataType:"json",
processData: false,
contentType: false,
url: '<?php echo base_url();?>SchoolAdmin/insertAttendance',
data: _data,
success: function (result) {
console.log(result);
staffattendance();
}
});
function staffattendance()
{
var fullDate = new Date();
var twoDigitMonth = ((fullDate.getMonth().length+1) === 1)? (fullDate.getMonth()+1) : '0' + (fullDate.getMonth()+1);
//var currentDate = fullDate.getDate() + "/" + twoDigitMonth + "/" + fullDate.getFullYear();
var currentDate = fullDate.getFullYear()+"-"+ twoDigitMonth +"-"+fullDate.getDate();
$.ajax({
type: 'POST',
dataType:"json",
url: '<?php echo base_url();?>SchoolAdmin/staffattendance',
data: {currentDate:currentDate},
success: function (result) {
$.each(result, function (i, item) {
console.log(result[i].staff_id);
$('.teachers').prop('checked', true);
});
}
});
}
Here I called a function staffattendance(), to get the staff id of staffs who is present on the current day. So i need to match the staff id I received through this function with the checkbox field and should be in checked mode. Below is the code that dynamically generates checkboxes with staff name.
<?php foreach($teacher as $row)
{?>
<tr><td>
<?php echo $row->name;?>
</td>
<td>
<input type="checkbox" name="teachers[]" class="teachers" value="<?php echo $row->staff_id;?>" >
<input type="hidden" name="teachers1[]" class="teachers1" value="<?php echo $row->staff_id;?>">
</td>
</tr>
<?php }?>
So I need to retain the checkbox of the staff_id that i got from staffattendance() fuction .
How this can be achieved.
Rose, the question is bit unclear as you do not specify when your table with names and checkboxes are generated and will this table be affected by ajax success..
you could try:
$.each(result, function (i, item) {
console.log(result[i].staff_id);
$('.teachers[value="'+result[i].staff_id+'"]').prop('checked', true);
});

Saving form value along with form in Session

I am using jQuery & ajax to save a entire form in session which is being generated.
when I press the search button the
onclick="updateContentdata();
is called. which is doing following.
function updateContentdata() {
var updateSearchContent = $('#savelistdata').html();
var rowNumb = rowCount;
var inFileds = JSON.stringify(field_options);
// var inputValue = $('inptval_' + rowCount).val();
$.ajax({
type: "POST",
url: "<?= $HOMEPAGE_ROOT; ?>/ajax_listuser.php",
data: {
rowNum: rowNumb,
field_options: inFileds,
html: updateSearchContent
},
success: function (data) {
$('#searchusers').submit();
},
error: function (req, status, error) {
console.log(error)
}
});
}
ajax_listuser.php
<?php
session_start();
if(isset($_POST['html']) && isset($_POST['rowNum'])){
$_SESSION['searchContent'] = $_POST['html'] ;
$_SESSION['rowNumber'] = $_POST['rowNum'] ;
$_SESSION['field_options'] = $_POST['field_options'];
}
?>
Form is being saved in the session but I want to keep form values in the session. but it only keeping the form.
So basically I need
<input class="form-control" type="text" id="inptval_2" name="search_input_value[]" value="71347">
instead of
<input class="form-control" type="text" id="inptval_2" name="search_input_value[]">
Create this function first:-
function getHtml(div){
div.find("input, select, textarea").each(function () {
var $this = $(this);
if ($this.is("[type='radio']") || $this.is("[type='checkbox']")) {
if ($this.prop("checked")) {
$this.attr("checked", "checked");
}
} else {
if ($this.is("select")) {
$this.find(":selected").attr("selected", "selected");
} else {
$this.attr("value", $this.val());
}
}
});
return div.html();
}
and then modify your funciton:-
function updateContentdata() {
var updateSearchContent = getHtml($('#savelistdata'));
var rowNumb = rowCount;
var inFileds = JSON.stringify(field_options);
// var inputValue = $('inptval_' + rowCount).val();
$.ajax({
type: "POST",
url: "<?= $HOMEPAGE_ROOT; ?>/ajax_listuser.php",
data: {
rowNum: rowNumb,
field_options: inFileds,
html: updateSearchContent
},
success: function (data) {
$('#searchusers').submit();
},
error: function (req, status, error) {
console.log(error)
}
});
}
You will probably have to put those values back in the form, since the value="123" is not part of the html when someone fills the form. Iterate over the values you have and find the corresponding form-element, and set its value

Ajax form Issue

I am trying to do a simple ajax form post. I think there is an issue with my code at the $.ajax lines. Once the code hits the $.ajax portion, console.log() fails to work and the form just redirects conventionally to the ajax-report-comment.php page and not through ajax. Up to this part my console.log function reports data and doesn't redirect to the page.
Does any one see what I am doing wrong here? Essentially on success I want it to alert the user of successful report.
Thanks in advance!
Code:
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('form.ajax').on('submit',function() {
var that = $(this),
url = that.attr('action'),
method = 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;
});
});
</script>
</head>
<body>
<form method="post" action="ajax-report-comment.php" class="ajax">
<input type="submit" value="Report" />
<input class="field" type="hidden" name="report_user_id" id="report_user_id" value="5"/>
<input class="field" type="hidden" name="report_comment_id" id="report_comment_id" value="33543"/>
</form>
</body>
</html>
I'm pretty sure return false; to cancel default actions is deprecated in modern versions of jQuery (if you use the migrate plugin, you will see warnings about that), so you should use:
$('form.ajax').on('submit',function(e) {
e.preventDefault();
// the rest of your code
I wanted to add to #jeroen answer a bit:
Use event.preventDefault() as he suggests, but also check into .serialize().
You could replace this entire block of code (from your code above):
// Replace this entire block with jQuery's serialize
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
With:
var data = $(this).serialize();
Thanks to Jeroen I was able to find that error of anonymous function. I had method where I should have had type in the var.
Corrected functioning js code:
$(document).ready(function(){
$('form.ajax').on('submit',function(e) {
e.preventDefault();
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;
});
});

Categories