HTML PHP show form submit results on same page - php

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.

Related

jQuery - Serialize Form Post Values

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.

Showing results on html using form en Ajax (OnChange)

This question is SOLVED - solution is on the bottom of the question.
Let's say I have this form:
<form id="form1" action="" method="POST">
<select name="cars">
<option value="">Choose a car</option>
<option value="Ferrari">Ferrari</option>
<option value="Lamborghini">Lamborghini</option>
</select>
<select name="colors">
<option value="">Choose a color</option>
<option value="Green">Green</option>
<option value="Red">Red</option>
</select>
Php:
$cars = $_POST['cars'];
$colors = $_POST['colors'];
echo "Car: ".$cars." - Color: ".$colors."";
Ajax:
<script type='text/javascript'>
$('select[name="colors"]').on('change', function(){
$.ajax({
type: "POST",
url: "phpfile.php",
data: $("#form1").serialize(),
success: function(data){
$('#target1').html(data);
}
});
return false;
})
</script>
I want to show on html the results:
<div id="target1"></div>
I want to show the results when I choose the color (The 2nd dropdown):
onchange="this.form.submit()"
IT IS DONE:)
I used this code and it I am getting what I want:
<script type='text/javascript'>
$("#colorID").on("change", function() {
var $form = $("#form1");
var method = $form.attr("method") ? $form.attr("method").toUpperCase() : "GET";
$.ajax({
url: 'phpfile.php',
data: $form.serialize(),
type: method,
success: function(data){
$('#target1').html(data);
}
});
});
</script>
Technically you dont need ajax to get what your asking for but heres jQuery ajax example:
Change your HTML to:
<select name="colors" onchange="this.form.submit()">
<option value="">Choose a color</option>
<option value="Green">Green</option>
<option value="Red">Red</option>
</select>
$( "#form1" ).submit(function( event ) {
event.preventDeafault();
alert('form submitted');
$.ajax({
type: "POST",
url: "<YOUR PHP FILE PATH>",
data: $("#form1").serialize(),
success: function(data){
alert('ajax success');
$('#target1').html(data);
}else{
alert('ajax error');
}
});
return false;
})
In your PHP:
print_r($_POST);
$car = $_POST['car'];
$color = $_POST['color'];
echo "<p>Car: ".$car." - Color: ".$color."</p>";
This is untested - I've just typed it out on my phone during my lunch break!
To debug the php add this line ( to unsure the post worked):
print_r($_POST);
Use your browser developer tools to debug your AJAX and JS
I've add alerts to help you debug - you can remove these when its working

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

AJAX/JS/PHP: Submitting value of a select box without page refresh or button click

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>

jQuery POST values to PHP script

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';
}
});

Categories