I need your help a bit.
I am trying to 'POST' form elements with ajax. When i get all elements by name i see the result on console of the browser and also it send the datas to databases. But the problem is. it sends checkbox values wrong. it always send "on" value even if i not checked.Select part is working corretly by the way.
Here is my form part
<div class="right-side" id="right-side-id">
<form action="criterias.inc.php" id="ajax" method="POST" class="ajax">
<br>
<center>
<h>Customize Your Experience</h>
</center>
<div class="right-side-options">
People interested in Friendship<input type="checkbox" class="checkmark" name="friendshipcheck"><br>
People interested in Practice<input type="checkbox" class="checkmark" name="practicecheck"><br><br>
Subject of Conversation
<select name="subjectName" class="select">
<option value="science">Science</option>
<option value="love">Love</option>
<option value="depressive">Deppressive</option>
<option value="anything">Anything</option>
</select><br><br>
Language
<select name="languageName" class="select">
<?php
include('connection.php');
$sql = "SELECT* FROM languages";
$query = mysqli_query($conn, $sql);
while ($result = mysqli_fetch_assoc($query)) {
$language = $result["language_name"];
echo "<option>" . $language . "</option>";
}
?>
</select>
<input type="submit" class="searchbutton" id="search-button-id" value="Search" onclick="showPartner();">
</div>
</form>
</div>
And here is my Javascript code.
$('form.ajax').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;
});
The issue is that you are trying to implement your own version of the serialize method, which does not include checkboxes if they are not checked. Your logic is including fields regardless, so long as they have a name field.
Rather than trying to write your own implementation and reinventing the wheel, use the serialize() method that is already implemented by jQuery.
$('form.ajax').on('submit', function (e) {
e.preventDefault();
var $this = $(this),
url = this.action,
type = this.method,
data = $this.serialize();
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
console.log(response);
}
});
});
This is the default behaviour in jQuery. What you need to do is explicitly handle the checkbox values to determine if its checked or not. Change your ajax method as follows. We'll modify the loop so it checks the checkbox value:
that.find('[name]').each(function(index, value){
var that = $(this),
name= that.attr('name'),
value = that.val();
if (that.attr('type') === 'checkbox') {
data[name] = that.is(':checked') // this will set the value to true or false
} else {
data[name] = value;
}
});
You should use;
$('#checkboxelement').is(":checked")
to read checked status of checkbox and radio elements.
Related
I m searching something of easy. I must pass value from a form html to a file PHP by jquery. I try this code with zero result. If someone can say me where i m mistaking. Thx
for JQUERY
$('#Save').click(function(){
var realvalues = new Array();//storing the selected values inside an array
$('#Privilege[] :selected').each(function(i, selected) {
realvalues[i] = $(selected).val();
});
$.ajax({
type: "POST",
url: "test5.php",
data: {"Privilege[]": realvalues},
success:function(data){
$("#subscrres").html(data)
}
});
});
For HTML
<form method="post">
<select id="Privilege[]" multiple>
<option value="yahoo">yahoo</option>
<option value="chrome">chrome</option>
<option value="mozilla">mozilla</option>
</select>
<input type="button" id="Save" Value="SEND"/>
For PHP. Content file test5.php
if(isset($_POST['Privilege'])){
$myvar =$_POST['Privilege'];
foreach($_POST['Privilege'] as $one)
echo $one."<br/>";
}
I don't receive nothing on PHP. Someone can help me ?
If you are trying to access multi select element using id the you don't need to set id like Privilege[], you can set any unique identity like privilege-selector but if you are giving name for any multi select element then name must be like Privilege[]
Here is the html :
<form id="form" method="post">
<select id="privilege-selector" multiple>
<option value="yahoo">yahoo</option>
<option value="chrome">chrome</option>
<option value="mozilla">mozilla</option>
</select>
<input type="button" id="Save" Value="SEND"/>
</form>
Please check this below ajax request to post selected data to the server
$("#Save").on("click",function(){
var selection = [];
$.each($("#privilege-selector option:selected"),function(index,element){
selection.push($(element).val());
})
$.ajax({
url : "test5.php",
type : "POST",
data : {Privilege:selection},
success : function(_response){
var res = JSON.parse(_response);
if(res.code == "1"){
console.log(res.data);
} else {
alert(res.message);
}
}
})
});
and here is your server file that will handle the incoming request data
$serverResponse = [];
if(isset($_POST['Privilege']) && !empty($_POST['Privilege'])){
$formattedData = [];
foreach($_POST['Privilege'] as $key => $value){
$formattedData[] = array(
"id" => $key+1,
"name" => $value
);
}
$serverResponse = ["code"=>"1","message"=>"formatted data","data"=>$formattedData];
} else {
$serverResponse = ["code"=>"0","message"=>"Please select at least on value"];
}
echo json_encode($serverResponse);
This is my index.php
$('#searchAdv').click(function() {
//What to be put here
$.ajax({
//what to be put here
url:"filter.php",
success: function(response){
$('#view').html(response);
}
});
});
<form>
<select id="adv1" name="task1">
<option value="blabla">Bla Bla</option>
.
.
.
</select>
<select id="adv2" name="task2">
<option value="blabla">Bla Bla</option>
.
.
.
</select>
<input type="submit" id="searchAdv" value="Filter">
</form>
<div id="view"></div>
How to pass the form id or submit button into ajax in order to send the form contents into another php page
First, you don't have an id of the form. So add that...
<form id="myForm">
Then I believe your problem would be resolved if you just bind to the submit call from the form and don't bind the click from the submit button.
$( "#myForm" ).submit(function( event ) {
// use ajax call in here, this will now refer to your form
var serialized = $(this).serialize();
});
You could keep the click bind, but it's just unusual for me. Then you'd just access the form using the $("#myForm") selector inside your current function.
you can do the altenative like this:
<form>
<select id="adv1" name="task1">
<option value="blabla">Bla Bla</option>
.
.
.
</select>
<select id="adv2" name="task2">
<option value="blabla">Bla Bla</option>
.
.
.
</select>
<input type="submit" onclick="add()" >
</form>
and then your ajax must add the datatype and data(what your data) like this :
function add(){
var username = $("#adv1").val();
var password = $("#adv2").val();
$.ajax({
dataType: 'html',
url: "filter.php>",
type: "POST",
data: username+password,
}).done(function(data) {
$('#view').html(response);
});
}
You can use jQuery's submit event handler to capture field values when the form is submitted and then send them to the ajax method. But first you need to attach an id to your form. Let's say we keep an id="form".
$('#form').on('submit',function(){
method = $(this).attr('method');
url = $(this).attr('action');
/*define these attributes in your form. Here you grab them and pass them to the ajax method later.*/
/* next you want the values of all your input fields.
* So we grab them values and assign them to their respective name attributes
* and we put the whole thing in the data object which we will send via ajax.
* It will look something like:
{ name_attribute_of_a_field:"value of that field",
name_attribute_of_another_field:"value of that field",
..and so on}
*/
data = {};
$(this).find('[name]').each(function(){
/*this will find all elements with a name attribute in it and loop through each of them.*/
name = $(this).attr('name');
value = $(this).val();
data[name] = value;
});
$.ajax({
url:url,
method:method,
data:data,
datatype:"type-of-response-data you expect",
success: function(data){
$('#view').html(data);
}
});
});
I have a select option, to get the value from this, I used jquery (please see below code). After I display the selected value in the textbox, I'm now having problem on how to get the value of textbox to process a such code. Even simply echo of the value is not working. What's the problem with the code? Please help. Thanks.
Select option:
<select name='shiptype' id='shiptype'>
<option value="0">Please select...</option>
<option value="LOC">LOCAL</option>
<option value="IM">IMPORT</option>
</select>
Jquery:
$('#shiptype').change(function () {
var selectedValue = $(this).val();
var strloc = "LOCAL";
var strimp = "IMPORT";
if (selectedValue == "LOC") {
$('#strkey').val(selectedValue);
} else if (selectedValue == "IM") {
$('#strkey').val(selectedValue);
}
});
Text Field:
<input type='text' id='strkey' name='keyname' />
Display the value:
$key = $_POST['keyname'];
echo $key;
Please try this code :
HTML file contains this below code. File name test.html.
Form to submit your data.
<form id="frm_post">
<select name='shiptype' id='shiptype'>
<option value="0">Please select...</option>
<option value="LOC">LOCAL</option>
<option value="IM">IMPORT</option>
</select>
<input type="text" name="name" id="strkey">
<input id="btn_post" type="button" name="submit" value="Submit">
</form>
This is a div for your output.
<div>
<p id="output"></p>
</div>
This is jquery for ajax call function.
<script>
$(document).ready(function(){
$('#shiptype').change(function() {
var selectedValue = $(this).val();
var strloc = "LOCAL";
var strimp = "IMPORT";
if (selectedValue == "LOC") {
$('#strkey').val(selectedValue);
//alert($('#strkey').val());
} else if (selectedValue == "IM") {
$('#strkey').val(selectedValue);
//alert($('#strkey').val());
}
});
$("#btn_post").click(function(){
var parm = $("#frm_post").serializeArray();
$.ajax({
type: 'POST',
url: 'your.php',
data: parm,
success: function (data,status,xhr) {
console.info(data);
$( "#output" ).html(data);
},
error: function (error) {
console.info("Error post : "+error);
$( "#output" ).html(error);
}
});
});
});
</script>
And for PHP File to get the post value like this below. File name your.php.
<?php
// $key = $_POST['keyname'];
// echo $key;
print_r($_POST);
?>
Your post result will be show up in output id. Hope this help you out. :D
I'm trying to use ajax on a select tag with 2 options, but it's not getting the $_POST for some reason. It prints out the "---", but it does not print out the $_POST value, which is either 1 or 2. I'm not sure what I did wrong. Please take a look at my code:
newtest.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function ajax(url,type,theName,id) {
$.ajax({
type: "POST",
url: url,
data: { select: $(type+'[name='+theName+']').val()},
error: function(xhr,status,error){alert(error);},
success:function(data) {
document.getElementById( id ).innerHTML = data;
}
});
}
</script>
<?php
echo "<select name = 'name' onchange = 'ajax(\"newtestx.php\",\"input\",\"name\",\"output\")'>";
echo "<option value = '1'> 1 </option>";
echo "<option value = '2'> 2 </option>";
echo "</select>";
echo "<div id = 'output'></div>";
?>
newtestx.php
<?php
$name = $_POST['name'];
echo $name."---";
?>
You are sending a POST parameter with the key "select" to the server in your AJAX call:
data: { select: $(type+'[name='+theName+']').val()},
In newtestx.php you are trying to retrieve the value from a POST parameter with the key "name" - which doesn't exist:
$name = $_POST['name'];
You could fix this easily by giving the parameter keys the same name. If you would look for $name = $_POST['select'] the parameter would be found.
Inline Javascript is considered bad practice and there's no need to echo out the HTML markup, it makes the mark up harder to work with.
newtest.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="[link to your javascript file here]"></script>
<select name='numbers' class="postValueOnChange" data-id-to-update="output" data-post-url="newtestx.php">
<option value='1'>1</option>
<option value='2'>2</option>
</select>
<div id='output'></div>
Javascript file
$(document).ready(function () {
$('.postValueOnChange').change(postSelectedValue);
function postSelectedValue(e) {
var $self = $(this);
var url = $self.data('post-url');
var $elementToUpdate = $('#' + $self.data('id-to-update'));
var jqxhr = $.ajax({
type: "POST",
url: url,
data: {
selected: $self.val()
}
});
jqxhr.done(function (data) {
$elementToUpdate.html(data);
});
jqxhr.fail(function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
});
}
});
newtestx.php
<?php
$name = $_POST['selected'];
echo $name."---";
?>
You are sending post param select and trying to receive as $_POST['name'].
Make sure they match...either both as name or as select
First, Since you are using jQuery, why are you still using inline javascript?
Well I suggest you first to restrucure your code around the jQuery change event:
$(document).ready(function() {
$('select').change(function(e) {
e.preventDefault();
var selected = $('.select option:selected').val();
var id, theName, url= ...// get it from the DOM
$.ajax({
type: "GET",
url: url,
data: { select: selected},
error: function(xhr,status,error){alert(error);},
success:function(data) {
$('#'+id).html(data);
}
});
});
});
Second, why are you coding HTML with PHP, you are making yourself struggle and lose time only with quotes and double quotes, and no-needed spaces.
<form action="">
<select name="name">
<option value="1">1</option>
<option value="1">1</option>
</select>
</form>
<div id="output"></div>
I am currently using Ajax to submit an input field without a page refresh or button click. The function works well with a text input field But it doesnt work with posting the value of a select box and then php echoing the result. I check with the firebug tool and nothing is being posted by Ajax/js function.
How can I submit the value of a select box so I can then echo with the php? EXAMPLE
JS
<script>
$(document).ready(function() {
var timer = null;
var dataString;
function submitForm(){
$.ajax({ type: "POST",
url: "index.php",
data: dataString,
success: function(result){
$('#item_input').text( $('#resultval', result).html());
}
});
return false;
}
$('#item_name').on('keyup', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 050);
var name = $("#item_name").val();
dataString = 'name='+ name;
});
});
</script>
PHP
<?php
if ($_POST)
{
$item_name = $_POST['name'];
echo ('<div id="item_input"><span id="resultval">'.$item_name.'</span></div>');
}
?>
HTML
<html>
<form method="post" id="form" name="form">
<select name="item_name" value="<? $item_name ?>" size="4" id="item_name">
<option value="">Item1</option>
<option value="">Item2</option>
<option value="">Item3</option>
<option value="">Item4</option>
</select>
</form>
<div id="item_input"></div>
</html>
select tags does not trigger keyup event , you should use change instead, try the following:
$('#item_name').on('change', function() {
clearTimeout(timer);
var name = $(this).val();
dataString = 'name='+ name;
timer = setTimeout(submitForm, 050);
});
$('#item_input').html(result);
Trigger submitForm() with an onchange event so that every time the value of <select> changes, it submits.
KeyUp is for input boxes and others that use the keyboard. Select boxes you can either use onClick or onChange, preferrably onChange:
$('#item_name').change(function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 050);
var name = $("#item_name").val();
dataString = 'name='+ name;
}
This will work for you.
Good Luck!
It seems that your js is right problem is in your html part. you not provided the select list values. pls provide values to select list options.
$(document).ready(function() {
var timer = null;
var dataString;
function submitForm(){
$.ajax({ type: "POST",
url: "index.php",
data: dataString,
success: function(result){
//$('#item_input').html( $('#resultval', result).html());
//$('#special').text(result);
//$('#item_input').html( $('#resultval').html() + '<p>' + result + '</p>');
$('#item_input').html(result);
}
});
return false;
}
$('#item_name').on('change', function() {
clearTimeout(timer);
var name = $(this).val();
dataString = 'name='+ name;
timer = setTimeout(submitForm, 050);
});
});
it should be like this or whatever values you want to post
<select name="item_name" value="" size="4" id="item_name">
<option value="item1">Item1</option>
<option value="item2">Item2</option>
<option value="item3">Item3</option>
<option value="item4">Item4</option>
</select>