jQuery - Serialize Form Post Values - php

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&param2=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.

Related

How to create filter for options value using ajax in php and zf2

How to make filter using ajax i want to get single option value for each selection and when click on filter button it sends data to getproductlistcb controller.
please help
HTML CODE is-
<div class="filter-category">
<form>
<input type="submit" value="filter" class="btn filter-btn">
<div class="user-category-select">
<select required="" name="sort" form="filter-form" class="btn filter-form-select" >
<option value="" disabled="">Sort</option>
<option value="popularity" selected="">Most Popular</option>
<option value="highest-rated">Highest Rated</option>
<option value="newest">Newest</option>
<option id="aesc" value="price-low-to-high">Lowest Price</option>
<option id="desc" value="price-high-to-low">Highest Price</option>
</select>
<label class="filter-category-select"><i class="fa fa-angle-down" aria-hidden="true"></i></label>
</div>
</form>
</div>
AjaX-
<script type="text/javascript">
$(document).ready(function(){
$('.btn filter-form-select').on('change',function(){
var data=$('#search_form');
$.ajax({
type: "POST",
url: "<?php echo $this->url('page', array('controller' => 'page', 'action' => 'getproductlistcb')); ?>",
data:data,
success:function(data){
console.log(data);
alert(data);
$("#").html(data);
}
});
});
});
</script>
Did you try to use :option in selector? For example, in that way: $('select.filter-form-select option:selected').val();?
I think you are looking for DOM-selector like that:
$('.filter-form-select option:selected').
So, in your case, in your code the code below might be helpful:
var $formData = $('#search_form');
var $formFilters = $formData.find('select.filter-form-select');
var $firstFilter = $formFilters.first();
var $option = $firstFilter.find('option:selected');
var optionText = $option.length ? $option.text() : null;
var optionValue = $option.length ? $option.val() : null;
Be aware, that $formFilters is not just one element, it's jQuery object that represents a set of DOM elements.
An additional way, try to debug and check what you have in your this-context and event:
$('.btn filter-form-select').on('change',function(event) {
console.log('clicked: ' + event.target.nodeName);
console.log('Context: ' + this);
});
I hope, something from that will help you a bit.

Getting the value of textbox

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

Making a search of course/teacher with Ajax and jQuery

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();

HTML PHP show form submit results on same page

I am trying to make a set of webpages that will display a unique graph based on a simple form that only has a selector box and a submit button. Basically what I want to happen is when the user changes the month in the selector and presses submit, a new chart set will render on the same page.
Here is the HTML initial page:
<HTML>
<HEAD>
<SCRIPT src="http://code.jquery.com/jquery-1.10.1.min.js"></SCRIPT>
</HEAD>
<BODY>
<CENTER>
<FORM ID="form1" METHOD="post" ACTION="">
<SELECT NAME="monthSelector">
<OPTION VALUE="0">Select Month...</OPTION>
<OPTION VALUE="1">January</OPTION>
<OPTION VALUE="2">February</OPTION>
<OPTION VALUE="3">March</OPTION>
<OPTION VALUE="4">April</OPTION>
<OPTION VALUE="5">May</OPTION>
<OPTION VALUE="6">June</OPTION>
<OPTION VALUE="7">July</OPTION>
<OPTION VALUE="8">August</OPTION>
<OPTION VALUE="9">September</OPTION>
<OPTION VALUE="10">October</OPTION>
<OPTION VALUE="11">November</OPTION>
<OPTION VALUE="12">December</OPTION>
</SELECT>
<INPUT TYPE="submit" VALUE="Show Charts">
</FORM>
<DIV ID="response"></div>
<SCRIPT>
function submit()
{
$(function()
{
var month = 3;
var formdata = "month=" + month;
$.ajax({
type: 'POST',
url: 'showCharts.php',
data: formdata,
success: function(data) {
$("#response").html(data);
}
});
});
}
</SCRIPT>
</CENTER>
</BODY>
</HTML>
and here is showCharts.php:
<?php
include("../FusionCharts/FusionCharts.php");
include("../DBConnect.php");
$month = $_POST['month'];
echo $month;
//insert complex queries and fusioncharts code that already works!
?>
Someone please help me, I've been staring at this for hours and can't make any progress.
You can also use the .load method of jQuery:
function submit()
{
var month = 3;
var formdata = month;
$('#response').load('showCharts.php?month='+formdata);
}
Also, you will need to set:
$month = $_REQUEST['month'];
Another way to do it would be:
$('select').change(function() {
var formdata = { month: document.getElementsByName('monthSelector')[0].value };
$('#response').load( 'showCharts.php', formdata);
});
Try replacing
<FORM ID="form1" METHOD="post" ACTION="">
for
<FORM ID="form1" METHOD="post" ONSUBMIT="submit(); return false;">
It should work.
In the part of jQuery, put this:
function submit()
{
var month = $('select[name="monthSelector"]').val();
$.ajax({
type: 'POST',
url: 'showCharts.php',
data:{'month':month},
success: function(data)
{
$("#response").html(data);
}
});
}
One more thing: try to improve the HTML code, it will give a better image to your webpage.
Are you sure the submit function is even called? Do you bind the form's submit event at all?
I would do something like $("#form1").submit(submit);
Also, you should return false at the end of submit() to block the default form action (which is refresh the current page I believe)
Try to update the variable formdata to make it a json object rather than a string.
<SCRIPT>
function submit()
{
$(function()
{
var month = 3;
var formdata = {'month': month}; //change made here
$.ajax({
type: 'POST',
url: 'showCharts.php',
data: formdata,
success: function(data) {
$("#response").html(data);
}
});
});
}
</SCRIPT>
Your jQuery code should be as follows:
$(function() {
var month = 3;
var formdata = { month: month };
$('#response').load( 'showCharts.php', formdata );
$('#form1').submit(function( e ) {
e.preventDefault();
var formData = { month: this.monthSelector.value };
$('#response').load( 'showCharts.php', formData);
});
});
When using the ajax .load() method, here is what you should be aware of:
Request Method
The POST method is used if data is provided as an object; otherwise,
GET is assumed.
Therefore, with the above jQuery code, your PHP script need not be changed.

Get the results of a form to a div without opening the results new page

How can I get the results of the result.php into the welcome div using ajax or any other method to prevent loading a new page?
<div id="welcome">
<form action="result.php" method="post">
<input type="hidden" id="date" name="selected"/>
<select id="city" class="cities" data-role="none" name="City">
<option value="">Anyplace</option>
.
.
.
</select>
<select id="type" class="cities" data-role="none" name="Event">
<option value="">Anything</option>
.
.
.
</select>
<input type="submit" class="button" value="Ok Go!"/>
<input id="current" name="current" type="hidden"/>​
</form>
</div>
If you are doing this through AJAX, then there is no need for the <form> codes. The <form> codes are only useful if you are posting to a different page and expecting the view to change/refresh anyways.
Also, using <form> codes in this example will cause the page to refresh (and values inserted by jQuery to be lost) for the additional bit with the "Set value for hidden field CURRENT" button. Not that it likely matters in your real world app, but just FYI.
Ajax goes in your javascript code, and looks like this:
$('#mySelect').change(function() {
var sel = $(this).val();
//alert('You picked: ' + sel);
$.ajax({
type: "POST",
url: "your_php_file.php",
data: 'theOption=' + sel,
success: function(whatigot) {
alert('Server-side response: ' + whatigot);
} //END success fn
}); //END $.ajax
}); //END dropdown change event
Note that the data ECHO 'd from the PHP file comes into your HTML document in the success function of the AJAX call, and must be dealt with there. So that's where you insert the received data into the DOM.
For example, suppose your HTML document has a DIV with the id="myDiv". To insert the data from PHP into the HTML document, replace the line: alert('Server-side response: ' + whatigot); with this:
$('#myDiv').html(whatIgot);
Presto! Your DIV now contains the data echoed from the PHP file.
Here is a working solution for your own example, using AJAX:
HTML MARKUP:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#mybutt').on('click', function(e){
e.preventDefault(); //prevent default action
var ct = $('#city').val();
var dt = $('#date').val()
var ty = $('#type').val();
var curr = $('#current').val();
$.ajax({
url: 'result.php',
type: 'POST',
data: 'ct=' +ct+ '&dat=' +dt+ '&t=' +ty+ '&curr=' +curr,
success: function(response){
$('#welcome').html(response);
}
});
});
$('#mycurr').click(function(){
var resp = prompt("Please type something:","Your name");
$('#current').val(resp);
});
}); //END $(document).ready()
</script>
</head>
<body>
<div id="welcome">
<input type="hidden" id="date" name="selected"/>
<select id="city" class="cities" data-role="none" name="City">
<option value="sumwhere">Anyplace</option>
<option value="anutherwhere">Another place</option>
</select>
<select id="type" class="cities" data-role="none" name="Event">
<option value="sumthing">Anything</option>
<option value="anutherthing">Another thing</option>
</select>
<input type="submit" id="mybutt" class="button" value="Ok Go!"/>
<input type="submit" id="mycurr" class="button" value="Set value for hidden field CURRENT"/>
<input id="current" name="current" type="hidden"/>
</div>
</body>
</html>
PHP Processor file: result.php
$ct = $_POST['ct'];
$date = $_POST['dat'];
$typ = $_POST['t'];
$cu = $_POST['curr'];
if ($date == '') {
$date = 'Some other date';
}
$r = '<h1>Results sent from PHP</h1>';
$r .= 'Selected city is: [' .$ct. ']<br />';
$r .= 'Selected date is: [' .$date. ']<br />';
$r .= 'Selected type is: [' .$typ. ']<br />';
$r .= 'Hidden field #CURRENT is: [' .$cu. ']<br />';
$r .= '<h2>And that\'s all she wrote....</h2>';
echo $r;
You can do something like this using jQuery Ajax
Use following code inside your head tag or footer
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type='text/javascript>
$('document').ready(function(){ //after page load
$('.button').on('click', function(e){
e.preventDefault(); //prevent default action
$.ajax({
'url': 'result.php',
'type: 'POST',
'success': function(response){
$('#welcome').html(response);
}
});
});
});
</script>
valit's the action="result.php" who makes your page reload
You shloud try to give an id to your form, and using a simple ajax call :
$("#formId").submit(function() {
$.ajax({
url: 'result.php',
success: function(response) {
$("#welcome").setValue(response); // update the DIV
}
});
return false; // prevent form submitting
});
Cheers

Categories