Failed to process checkbox values with AJAX in PHP - php

I have an HTML form with text, radio and checkbox inputs. When I submit it with AJAX, I only get the last checkbox value in array.
My HTML file:
<form class="ajaxonsubmit" action="process.php" method="post">
<label>Name</label><input type="text" name="name">
<label>Father's Name</label><input type="text" name="father_name">
<label>Gender</label>
<input type="radio" value="1" name="gender">Male <br>
<input type="radio" value="2" name="gender">Female <br>
<label>Options</label>
<select name="campus">
<option value="1">Option1 </option>
<option value="2">Option2 </option>
</select>
<label>Check List</label>
<input type="checkbox" name="check[]" value="1">
<input type="checkbox" name="check[]" value="2">
<input type="checkbox" name="check[]" value="3">
<button name="submit" type="submit">Submit</button>
My JS file.
$('.ajaxonsubmit').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(data) {
$("#wrap").html(data);
}
});
return false;
});
I am using var_dump($_POST); function in process.php to check the array and I get ["check"]=> array(1) { [0]=> string(1) "3" }

You can serialize the form data , and access in PHP side
$('.ajaxonsubmit').on('submit', function(e) {
e.preventdefault();
$.ajax({
url: url,
type: type,
data: $(this).serialize(),
success: function(data) {
$("#wrap").html(data);
}
});
});
in PHP
print_r($_POST);

Add class="checkBoxClass" to your checkbox,
Then in your js, just add the following code to add the data into your chkArray
var chkArray = [];
$(".checkBoxClass:checked").each(function() {
chkArray.push($(this).val());
});
Finally append the array to the data you are posting
Cheers.

Related

How to Send Text and Image File Data at The Same Time to MySQL Database Without Refreshing The Page

I don't know how to send text, checkbox, radio data and also image file at the same time using ajax jquery post (in order not to refresh the page).
Here are the codes I have.
index.php
<form action="save.php" method="POST">
Your Name : <input type="text" name="username" id="username">
<BR>
Your Sex :
<input type="radio" class="get_gender" name="gender" id="genderM" value="Male">Male
<input type="radio" class="get_gender" name="gender" id="genderF" value="Female">Female
<BR>
Your Hobbies :
<input type="checkbox" class="get_hobby" name="basket" id="basket" value="Basketball">Basketball
<input type="checkbox" class="get_hobby" name="foot" id="foot" value="Football">Football
<input type="checkbox" class="get_hobby" name="volley" id="volley" value="Volleyball">Volleyball
<BR>
Your Grade :
<select name="grade" id="grade">
<option value="1>1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<BR>
Upload Photo : <input type="file" name="image" id="image">
<BR>
<input type="button" name="save" id="save" value="Save" onclick="save()">
</form>
save.php
<?php
include "connection.php";
$usename = $_POST['username'];
$gender = $_POST['gender'];
$hobby = $_POST['hobby'];
$grade = $_POST['grade'];
$photo = $_FILES['image']['name'];
$sql = "insert into user
(username, gender, hobby, grade, photo)
values('$username','$gender','$hobby','$grade','$photo')";
$query = mysqli_query($con,$sql);
header("location: index.php");
?>
index.js
function save(){
var username = document.getElementById("username").value;
var grade = document.getElementById("grade").value;
var hobby = [];
$('.get_hobby').each(function(){
if($(this).is(":checked"))
{
hobby.push($(this).val());
}
});
hobby = hobby.toString();
var gender = [];
$('.get_gender').each(function(){
if($(this).is(":checked"))
{
gender.push($(this).val());
}
});
gender = gender.toString();
$.ajax({
type: "POST",
url: 'save.php',
data: {
username: username,
hobby: hobby,
hobby: hobby,
grade: grade
},
success: function(result){
}
});
}
Please help
You can simplify your save function - and send both form data and an image at the same time by using a FormData object:
function save_data() {
var formData = new FormData($('#userform')[0]);
$.ajax({
url: '/test13.php',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function (response) {
alert(response);
}
});
}
Note you need a couple of other changes. The form needs an id attribute e.g.
<form id="userform">
You should change the name attributes of the hobbies to hobby[] i.e.
<input type="checkbox" class="get_hobby" name="hobby[]" id="basket" value="Basketball">Basketball
<input type="checkbox" class="get_hobby" name="hobby[]" id="foot" value="Football">Football
<input type="checkbox" class="get_hobby" name="hobby[]" id="volley" value="Volleyball">Volleyball
And you need to add
processData: false,
contentType: false,
To your ajax object.
In your PHP code, you would need to assemble $hobby from the raw form values:
$hobby = implode(',', $_POST['hobby']);
and you should include a check for $_POST['gender'] being set:
$gender = $_POST['gender'] ?? '';
I needed to change the name of your function as save was causing conflicts. I renamed it to save_data. You may not find this is an issue.

Send array data through AJAX

I have the following issue.
I'm trying to send a AJAX call whenever a checkbox is checked. The value of the checkbox is send to my PHP file where the DB will be checked to get all the data of that value.
The problem is, I would like to show the data on the page but I don't know how.
Below is my code:
HTML:
<input type="checkbox" name="category[]" id="1" value="1" /> <label for="1">Administratieve Sector</label><br />
<input type="checkbox" name="category[]" id="2" value="2" /> <label for="2">Bouw Sector</label><br />
<input type="checkbox" name="category[]" id="3" value="3" /> <label for="3">Financiele Sector</label><br />
<input type="checkbox" name="category[]" id="4" value="4" /> <label for="4">Gezondheidszorg Sector</label><br />
<input type="checkbox" name="category[]" id="5" value="5" /> <label for="5">Horeca- en toerisme Sector</label><br />
JQuery:
function calculate() {
var arr = $.map($('input:checkbox:checked'), function(e, i) {
return +e.value;
});
$.ajax({
url: '/company/test.php',
data: {key: arr, i: 1},
type: 'post',
success: function(output) {
obj = JSON.parse(output);
console.log(obj);
// Don't know where to go next
}
});
}
calculate();
$("div[class='col-md-12'").delegate("input:checkbox[name='category[]']", 'click', calculate);
PHP:
<?php
require_once '../core/init.php';
$v = new Vacatures();
if(isset($_POST['key']) && isset($_POST['i']) && !empty($_POST['key'])) {
$key = $_POST['key'];
$i = $_POST['i'];
$vacs = $v->getFiltered($key, $i);
echo json_encode($v->data());
exit();
}
require_once VIEW_ROOT . '/company/test_view.php';
UPDATE (Content of obj)
[Object]0: Objectcategory: "1"company: "c1"content: "test"foto: "test"id: "2"region: ""title: "Test"__proto__: Objectlength: 1__proto__: Array[0]
Something like
$('body').append('<div><ul id="output"></ul></div>');
obj.data.forEach(function(x) {
$('#output').append("<li>"+x+"</li>");
});
Edit:
was some typo in there
forEach or $.each works only on json arrays, so you have to look whats inside your obj
I fixed it using the following AJAX call:
$.ajax({
url: '/company/test.php',
data: {key: arr, i: 1},
type: 'post',
dataType: "json",
success: function(output) {
$.each(output, function(key, element) {
$('#output').append("<li>"+element.title+"</li>");
});
}
});

Jquery post not working , send multiple selected checkbox through jquery to php script

In the php script when I echo the $_POST['AllItems '] then it shows only the last selected value
instead of a whole string of values or array.
Below is the javascript am using :
$(function () {
$('#senditems').click(function () {
var items = $('input[name^="item"]:checked').map(function () {
return this.value;
}).get();
*****************************
//here when i do alert(items); ,
then it shows comma separated values - 1,22,321
****************************
$.post("saveitems.php", {
AllItems: items
});
});
});
Form is :
<form>
<input type="checkbox" name="items[1]" value="1" />
<input type="checkbox" name="items[22]" value="22" />
<input type="checkbox" name="items[321]" value="321" />
</form>
This is how your form should look.
<form id="my_form">
<input type="checkbox" name="items[]" value="1" />
<input type="checkbox" name="items[]" value="22" />
<input type="checkbox" name="items[]" value="321" />
</form>
Then in your php, you can iterate through all the $_POST['items']
If you want to use jQuery to post, you can use this, but is not necessary as you can add a method and action to the html in your form:
$('#senditems').on('click', function(){
var form_data = $('#my_form').serialize();
$.post({
url: "your_php.php",
data: form_data
});
});

Passing form array data through jQuery AJAX

I have a form that allows you to add multiple listings at one time.
I also have to pass through an md5check.
I.E.)
<select name="master_id"></select>
<select name="id2[]"></select>
<select name="id3[]"></select>
<input name="text[]"></input>
<input name="text2[]"></text>
<input name="text3[]"></text>
<input name="check[]" type="checkbox"></input>
<select name="id2[]"></select>
<select name="id3[]"></select>
<input name="text[]"></input>
<input name="text2[]"></text>
<input name="text3[]"></text>
<input name="check[]" type="checkbox"></input>
<select name="id2[]"></select>
<select name="id3[]"></select>
<input name="text[]"></input>
<input name="text2[]"></text>
<input name="text3[]"></text>
<input name="check[]" type="checkbox"></input>
jQuery.ajax({
type: "POST",
url: ipb.vars['base_url'] + "app=main&module=ajax&section=upload&do=upload",
data: {
'md5check': ipb.vars['secure_hash'],
}
}).done(function() {
alert( "Data Saved:");
});
I want to pass in the master ID and the arrays through AJAX so that they then can be $_REQUEST'ed in PHP. The 'md5check' must be there.
data can also take a string so, you can used
jQuery.ajax({
type: "POST",
url: ipb.vars['base_url'] + "app=main&module=ajax&section=upload&do=upload",
data: $('input[name="username[]"],input[name="password[]"],input[name="rawtext[]"]').serialize()
+ '&md5check='+ipb.vars['secure_hash'],
}).done(function() {
alert( "Data Saved:");
});
HTML Form:
<form action="" method="POST" id="myform">
<input name="username[]">
<input name="password[]">
<input name="rawtext[]">
<input name="username[]">
<input name="password[]">
<input name="rawtext[]">
<input name="username[]">
<input name="password[]">
<input name="rawtext[]">
<input name="submit" type="submit" value="submit">
</form>
jQuery:
$('#myform').submit(function(event) {
event.preventDefault();
//comment this line out
alert($(this).serialize());
$.post(ipb.vars['base_url'] + "app=main&module=ajax&section=upload&do=upload&", {
$(this).serialize() })
.done(function(data) {
alert("Data Loaded: " + data);
});
return false;
});
You can use the following.
$('#myform').submit(function(e) {
e.preventDefault();
e.stopPropagation();
var formData = $(this).serializeObject();
var postData = $.extend({}, formData, {
app: main,
module: ajax,
section: upload,
do: upload
});
$.post(ipb.vars['base_url'], postData,
function(data) {
alert(data);
}
);
});
$.fn.serializeObject = function() {
var objectData = {};
var serializeArr = this.serializeArray();
$.each(serializeArr, function() {
if(objectData[this.name] !== undefined) {
if(!objectData[this.name].push) {
objectData[this.name] = [objectData[this.name]];
}
objectData[this.name].push($.trim(this.value) || '');
} else {
objectData[this.name] = $.trim(this.value) || '';
}
});
return objectData;
};

Doing an ajax call to a php page

I have this star rating, I implemented from jQuery and I need to save the comments, the user id and the value of the star clicked. What I do not know is how to pass that through the ajax call and what the PHP should have at the least to process the call? Here is my code
stars code - as you can see it has a comments box , the stars with star value and the user id is stored in a variable called
$user_id
Here is the code
<tr>
<td style="padding:10px;">
<span style="font-size: 20px; vertical-align:top;">Comments</span>
</td>
<td style="padding:10px;">
<textarea name="comments1" cols="60" rows="2"></textarea>
</td>
<td>
<div>
<input name="star1" value "1" type="radio" class="star"/>
<input name="star1" value="2" type="radio" class="star"/>
<input name="star1" value="3" type="radio" class="star"/>
<input name="star1" value="4" type="radio" class="star"/>
<input name="star1" value="5" type="radio" class="star"/>
</div>
</td>
<tr>
The ajax call - This is the attempted call to the page where I am sending the request, but how can I include the comments and user id on this call?
$('.star').rating({
callback: function(value, link) {
var name = $(this).attr('name');
$.ajax({
url: "ajax.php",
data: "name=" + name + "&value=" + value,
cache: false,
success: function(response) {
try {
console.log(response);
} catch (err) {
alert(response);
}
}
});
}
});
Now, ajax.php has variables $passed_user_id, $passed_comments, $passed_ratingval. How am I retrieving these values when the call is triggered in php? something like
$passed_comments = //get the value being passed from ajax call
$passed_ratingval = //get the value being passed for the rating value
$passed_user_id = //get the value being passed for the user_id`
I do have all set up, the insert query, connection everything works. I'm just not sure how to make this work with the ajax call.
Kinda hacky, but this will work for you. It also will allow for multiple ratings on one page (which I assume you might be doing considering the TR).
HTML:
<tr>
<td style="padding:10px;">
<input type="hidden" name="userID" value="<?php echo $user_id ?>">
<span style="font-size: 20px; vertical-align:top;">Comments</span>
</td>
<td style="padding:10px;">
<textarea name="comments" cols="60" rows="2"></textarea>
</td>
<td>
<div>
<input name="star1" value "1" type="radio" class="star"/>
<input name="star1" value="2" type="radio" class="star"/>
<input name="star1" value="3" type="radio" class="star"/>
<input name="star1" value="4" type="radio" class="star"/>
<input name="star1" value="5" type="radio" class="star"/>
</div>
</td>
<tr>
JS:
$('.star').rating({
callback: function(value, link) {
var name = $(this).attr('name');
var userID = $(this).closest('tr').find('input[name="userID"]').val();
var comments = $(this).closest('tr').find('textarea[name="comments"]').val();
$.ajax({
url: "ajax.php",
data: "name=" + name + "&value=" + value + "&userID=" + userID + "&comments=" + comments,
cache: false,
success: function(response) {
try {
console.log(response);
} catch (err) {
alert(response);
}
}
});
}
});
Also, if you use POST instead of GET, you can format your ajax call a bit nicer like below. Remember to use $_POST[] in your ajax.php file.
$('.star').rating({
callback: function(value, link) {
var name = $(this).attr('name');
var userID = $(this).closest('tr').find('input[name="userID"]').val();
var comments = $(this).closest('tr').find('textarea[name="comments"]').val();
$.ajax({
url: "ajax.php",
type: "POST",
data: {
name: name,
value: value,
userID: userID,
comments: comments
},
cache: false,
success: function(response) {
try {
console.log(response);
} catch (err) {
alert(response);
}
}
});
}
});
Here is example code of mine, which I use on one project:
jQuery.post("load.php", {
op_type : opType,
xor : xor.toString(),
or : or.toString(),
and : and.toString(),
from : seeds.toString(),
last_id : jQuery("input[type=hidden]:last").val(),
last_update : last_update_time
}, function(data) {
var json = jQuery.parseJSON(data);
if (json.list.length > 0) {
last_update_time = Math.floor(new Date().getTime() / 1000);
jQuery("div#list_content ul.no-list").append(json.list);
}
});
And in PHP to receive data I use:
$_POST['op_type']
and in this manner I get other variables too.
To return something I do like this:
echo json_encode(array("list"=>$html));
So afyer jQuery parses JSON it can get access to $html variable via list property.
So what you need is to specify request type in jQuery and get that request type in PHP. Sending data in JSON is one of the options. jQuery and PHP also support XML, but I didn't worked with it.

Categories