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);
Related
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.
How do I want to post a form using jquery serialize function? I tried to post the form value but on the php part, the value is not shown. Below are my codes:
html
<form name="myform">
ID : <input type="text" name="id_staff" id="id_staff">
<select name="sort" id="sort">
<option value="0">Choose Status</option>
<option value="1">All</option>
<option value="2">Pending</option>
<option value="3">Approve</option>
<option value="4">Not Approve</option>
</select> <input type="button" id="submit" value="Papar" />
<div id="loader"></div>
</form>
jQuery
$(document).on("click", "#submit", function(e){
e.preventDefault();
var sort = $("#sort").val(),
id_staff = $("#id_staff").val(),
data = $('form').serialize();
$.post('result.php',
{
data : data
}, function(data){
$("#loader").fadeOut(400);
$("#result").html(data);
});
});
PHP
if(isset($_REQUEST["sort"])){
$sort = $_REQUEST['sort'];
$id_staff = $_REQUEST['id_staff'];
echo "Your Id : $id_staff <p/>";
echo "You choose : $sort";
}
If I console.log(data), I get: id_staff=12345&sort=1
Your server is receiving a string that looks something like this (which it should if you're using jQuery serialize()):
"param1=someVal¶m2=someOtherVal"
...something like this is probably all you need:
$params = array();
parse_str($_GET, $params);
$params should then be an array that contains all the form element as indexes
If you are using .serialize, you can get rid of this:
var sort = $("#sort").val(),
id_staff = $("#id_staff").val(),
You data will be available as follows with .serialize:
your-url.com/sort=yoursortvalue&id_staff=youridstaff
It should be:
$(document).ready(function(e) {
$("#myform").submit(function() {
var datastring = $( this ).serialize();
$.post('result.php',
{
data : datastring
}, function(data){
$("#loader").fadeOut(400);
$("#result").html(data);
});
})
})
On PHP side you simple need to access it using the $_GET['sort'].
Edit:
To view the data, you should define a div with id result so that the result returned is displayed within this div.
Example:
<div id="result"></div>
<form name="myform">
ID : <input type="text" name="id_staff" id="id_staff">
<select name="sort" id="sort">
<option value="0">Choose Status</option>
<option value="1">All</option>
<option value="2">Pending</option>
<option value="3">Approve</option>
<option value="4">Not Approve</option>
</select> <input type="button" id="submit" value="Papar" />
<div id="loader"></div>
</form>
I am able to do it this way:
jQuery
<script type="text/javascript">
$(document).ready(function() {
var form = $("#myform");
$("#myform").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'result.php',
data: form.serialize(),
success: function(response) {
console.log(response);
$("#result").html(response);
},
error: function() {
alert('Error Submitting');
}
})
})
})
</script>
PHP
if(isset($_POST["id_staff"])){
$sort = $_POST['sort'];
$id_staff = $_POST['id_staff'];
echo "<p>Your Id : $id_staff</p>";
echo "You choose : $sort";
}
Do give a comment if it need improvement or better solution.
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 have a jQuery Ajax problem.
I have a select tag with options of courses, the select holds div id="course". I have a button with id of "go" and an empty div with id of "courseInfo". I need to make it so that when a course number is selected, the teacher name in my php file that goes with it is displayed on the page. I have all my Ajax written, everything is linked, but it wont work and no error when I debug.
$(document).ready(function(){
findCourse = function(){
var file = "Course.php?course="+$("#course").val();
$.ajax({
type: "GET",
url: file,
datatype : "text",
success : function(response) {
$("#courseInfo").html(response);
}
});
}
clear = function(){
$("#courseInfo").html("");
};
$("#course").click(clear);
$("#go").click(findCourse);
});
Form:
<form action="" method="post">
<select name="course" id="course">
<option value="420-121">420-121</option>
<option value="420-122">420-122</option>
<option value="420-123">420-123</option>
<option value="420-221">420-221</option>
<option value="420-222">420-222</option>
<option value="420-223">420-223</option>
<option value="420-224">420-224</option>
</select>
Select a course to see the course name and teacher assigned<br><br>
<input type="button" id="go" value="go!">
</form>
<br><br>
<div id="courseInfo"></div>
Assuming that the PHP side is working properly, the code below should fix the issue.
$(document).ready(function(){
findCourse = function(){
var file = "Course.php?course="+$("#course").val();
console.log(file);
$.ajax({
type: "GET",
url: file,
datatype : "text",
success : function(response) {
$("#courseInfo").html(response);
}
});
}
clear = function(){
$("#courseInfo").html("");
};
$("#course").click(clear);
$("#go").click(findCourse);
});
You miss the = in var file.
Yours was
var file = "Course.php?course"+$("#course").val();
It should be
var file = "Course.php?course="+$("#course").val();
I want to post some values from a simple HTML form, validate them with an ajax call and if successful submit to a PHP script and redirect to that script. I have got the ajax part set up, just not sure how to post and redirect (as if you would on a standard form submit without ajax).
Here's what I have:
HTML:
<div id=audiencesearch>
<h1>Audience Search</h1>
<form id="audiencesearchform">
<p>Passion Point</p>
<select id="passionselect">
<option selected="selected">Please select</option>
<option>3D</option>
<option>Music</option>
<option>Playstation</option>
</select>
<p>Gender Bias</p>
<select id="genderselect">
<option selected="selected">Please select</option>
<option>Male</option>
<option>Female</option>
</select>
<p>Sort Group By Age Range</p>
<select id="ageselect">
<option selected="selected">Please select</option>
<option>Under 21</option>
<option>21 - 30</option>
<option>31 - 40</option>
<option>41 - 50</option>
</select>
<br/>
<br/>
<input onClick="ajaxaudiencesearch()" class="submitaudiencesearch" value="Search" type="button"/>
Ajax Call:
<script type="text/javascript">
function ajaxaudiencesearch(){
var passionpoint = $("select#passionselect").val();
var genderbias = $("select#genderselect").val();
var agerange = $("select#ageselect").val();
var passedstring = 'passion='+ passionpoint + '&gender=' + genderbias + '&age=' + agerange;
$.ajax({
type: "POST",
url: "processaudiencesearch.php",
data: passedstring,
success:function(retval){
if (retval == 'oktoprocess'){
audiencesearchprocess();
} else {
audiencesearcherror();
}
}
})
}
function audiencesearcherror(){
$('#audienceerror').html('GOTTA SELECT EM ALL');
}
function audiencesearchprocess(){
window.location.href = "searchresults.php";
//THIS IS WHERE I WANT TO POST AND MOVE TO SEARCHRESULTS.PHP
}
</script>
PHP to handle Ajax:
<?php
include('sonymysqlconnect.php');
session_start();
$nullselection = "Please select";
//get the posted values
$postedpassion = ($_POST['passion']);
$postedgender = ($_POST['gender']);
$postedage = ($_POST['age']);
if (($postedpassion != $nullselection ) && ($postedgender != $nullselection ) && ($postedage != $nullselection)){
echo 'oktoprocess';
} else {
echo 'error';
}
?>
Preferably I could achieve this using jQuery. I'm sure it's extremely simple but I'm not sure how to do it?!
It's worth mentioning that this is all set up correctly. I have used PHP includes.
Thanks in advance...
Why not add action and method attributes to your form and then submit it with .submit()?
With plain html / php it is not even really a true redirect, its just the url value in "action" that can be found in the form element
<form action="/someUrl/someAction" method="POST">
...
</form>
If you're doing it with ajax (jquery), you'd say:
$.ajax({
url: '/someUrl/someAction',
type: 'POST',
data: {
argName1: 'argVal1',
argName2: 'argVal2'
},
success: function( response ) {
// keep in mind that response is usually in json...
// which means you'd be accessing
// the data in object notation: response.data.someVal
if(response == 'whatYouWanted') {
//do something... like redirect?
window.location = '/new/page';
}
});