PHP Ajax form store dropdown selection as variable - php

I have a php form where the user will select from a dropdown to see a data set. The data refreshes on the screen with the use of an ajax call. I am using the 'html' datatype so I can refresh the output into the appropriate div section.
The page refreshes with the correct data as expected, but I need to have the dropdown selection stored as a variable in php. I am not sure how to do this and spent the better part of a day doing research without success.
Here is the form:
<form action="" id="postForm" method="POST">
<select name="name" id="name">
<option value="1">1</option>
<option value="2">2</option>
</select>
<input type="submit" name="submit" id="submit" value="Go">
</form>
Here is the ajax:
$(document).ready(function(){
$('#submit').click(function() {
$('#waiting').show(500);
$('#Form').hide(0);
$('#message').hide(0);
$.ajax({
type : 'POST',
dataType : 'html',
url : '/?tmpl=component',
data: $('#postForm').serialize(),
success : function(data){
$('#waiting').hide(500);
$('#div-section-to-be-updated').html(data);
$('#message').text('Your data has been updated').show(500);
$('#message').hide(4000);
}
,
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#message').removeClass().addClass('error')
.text('There was an error.').show(500);
$('#Form').show(500);
}
});
return false;
});
});
I want to store "name" as $name when the user clicks submit.

create session variable and store data in it.
session_start();
$_SESSION]['name'] = $_POST['name'];
Now you can simply access Session as a PHP variable.

Related

AJAX stay on same page after submit, output on same page

I have some drop downs looks like this in my HTML form:
<form name="fee" method="POST" action="">
<p><span class="title">Number of artists:</span>
<select name="Number">
<option value="" rel="none" selected disabled>Please select an option..</option>
<option value="one" rel="one_art">One artist only</option>
<option value="more" rel="more_arts">More than one artists</option>
</p>
A table of summery will be generated after I click the submit button.
<input type="submit" value="Calculate">
My question is: Whenever I click the button, the previously selected option will be reset. And only the summery show up at the end of the page. Is there a way to output the summery on the same page without the previously selected option gets cleared?
Thanks in advance!!
I think your best option is to use AJAX POST to post the form data, and JQuery to keep the same option selected:
$(document).ready(function() {
$("#fee").on('submit',(function(e) {
e.preventDefault();
var selectedOption = $( "#Number option:selected" ).text();
$.ajax({
url: "here put the url to the php page handling your form data",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function ()
{
$("#Number").val(selectedOption);
}
});
}
});

Getting a default value from dropdown and display a table

I am trying to display a HTML table in my index.php page with user registration data which process in table.php page. I am sending a value from a dropdown to the server for processing the data. These everything working for me. But my problem is when my index page load it is not display my table. If I need to display the table I want to select a value from the dropdown.
So anybody tell me how can I make a default value for dropdown (example 05) to display table when page is always loading.
This is my Jquery :
$('#filter-value').change(function(){
var filterValue = $(this).val();
//console.log(filterValue);
$.ajax({
type: 'post',
url: 'table.php',
dataType: 'html',
data: {filter: filterValue},
success:function(data){
$('#response').html(data);
//alert(data);
},
error:function (xhr, ajaxOptions, thrownError){
//On error, we alert user
alert(thrownError);
},
complete: function(){
//alert('update success');
}
});
});
This is HTML
<div id="manage_user">
<form action="" method="">
<div id="response"></div>
<button id="FormSubmit">Add New User</button>
</form>
</div>
<br />
<div style="margin: 0 20px 20px;">
<form method="post" action="">
<select id="filter-value" name="filter">
<option value="5">5</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
</select>
</form>
</div>
Thank you.
The easiest way to do this without rewriting your code would be to change the value of the drop down and then trigger the change event so that the your existing event handler gets called when the DOM is ready. Something like:
$(document).ready(function() {
$('#filter-value').val(5).change();
});

retrieve value from database when onchange in dropdownbox by jquery

This is my html code
<select name="course" id="course" onchange="valuesOfAll(this.value)">
<option value=""> select </option>
<option value="1"> Diploma in Computing</option>
</select>
<input name="course_credits" id="course_credits" type="text" />
and my database table is like this
courseId courseName courseCredits
1 Diploma in Computing 5
So my request is, if i change the value in the 'select' the 'courseCredits' value should appear in the textbox. for this how can i write jquery code?
"Ajax with Jquery" is what your are looking for. It will work like this:
the user chooses an option from the select box
you submit via Javascript the chosen option to a PHP script
the php script fetches the data from the database
the php script returns the result as json encoded data
there is a callback function in your javascript code. This js code will manipulate the HTML in whatever way you want, e.g. "add the option to your select box"
There are tons of tutorials on how to do Ajax requests in detail, e.g. http://openenergymonitor.org/emon/node/107
Check out one of those tutorials - eventually you will want to update your question so that it becomes a bit more specific? :-)
it is good practice to seperate you html from scripts so i would like to change :
<select name="course" id="course" onchange="valuesOfAll(this.value)">
to
<select name="course" id="course" >
then my script will be following (hoping you add reference of latest jquery )
<script>
$(document).ready(function(){
//bind change event once DOM is ready
$('#course').change(function(){});
getResult($(this).val());
});
function getResult(selectedValue){
//call ajax method to get data from database
$.ajax({
type: "POST",
url: url,//this should be replace by your server side method
data: "{'value': '"+ selectedValue +"'}", //this is parameter name , make sure parameter name is sure as of your sever side method
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (Result) {
alert(Result.d);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
</script>
use $.post.. (ajax or get)... i am using post here....go through the docs if you want to read more about jquery post..
javascript
function valuesofAll(val){
$.post('test.php',{data:val},function(result){
$('#course_credits').val(result.coursecredit)
}, "json"); //expect response as json..
}
test.php
$data=$_POST['data']; //this is the value posted
//make you query in db get result..
$courseCredits= $row; //db returned courseCreadit value
echo json_encode(array('coursecredit'=>$courseCreadits)); //send response as json
this will helps you .....
<script>
function valuesOfAll(value)
{
var base_url="http://.../../hello.php";
var ip=new Object();
ip.course=value;
var inputParam=JSON.stringify(ip);
var module="getcourseCredits"
$.ajax({
type: "POST",
url: base_url,
data: {coursevalue:inputParam,module :module},
dataType: "json",
success: function(msg)
{
$("#course_credits").val(msg.credit);
}
});
}
</script>
<body>
<select name="course" id="course" onchange="valuesOfAll(this.value)">
<option value=""> select </option>
<option value="1"> Diploma in Computing</option>
</select>
<input name="course_credits" id="course_credits" type="text" />
</body>
In your PHP file
<?php
if(isset($_POST['module']))
{
if($_POST['module']=='getcourseCredits')
{
$val=json_decode($_POST['coursevalue'],true);
$courseval=$val['course'];
// do the connectivity and query here and finally echo the result as json format that is the response to the ajax call
.
.
.
.
}
}
?>

How to access individual values of form data, passed from an HTML page with jQuery.ajax(), inside a PHP script?

I'm passing form data to a PHP script for processing via JS(jQuery.ajax()).
Problem is - I can't figure out a way to access individual form control values inside PHP( e.g. $_POST['zipcode'] ).
Instead I can only access the data with $_POST['form'], which is an entire form represented as one long string( e.g. string(89)"color=red&color=blue&zipcode=12345..." ).
How can I access individual values of form data inside PHP script passed from a HTML form via JS?
index.php(form)
<form id="myform">
<select name="color" id="color">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<input type="text" id="zipcode" name="zipcode" />
<input type="submit" id="submit" name="submit" value="Submit" />
</form>
index.php(JS)
$('#myform').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
dataType: 'html',
url : 'PHPscript.php',
data: {form : $('#myform').serialize()}
}).done(function(data) {
var myJSONresult = data;
alert(myJSONresult);
});
});
PHPscript
<?php
if(isset($_POST["form"])){
$form = $_POST["form"];
$myzipcode = $_POST['zipcode']; // won't work; will be null or empty
echo json_encode($form);
}
?>
EDIT: The zipcode field:
$("#zipcode").focus(function(){
if(this.value == "zipcode"){
$(this).val("");
}
}).blur(function(){
if(this.value == ""){
$(this).val("zipcode");
}
});
You need to use serializeArray() on the form data instead of serialize. That will submit as an array.
data: $('#myform').serializeArray()
HTML
<input type="hidden" name="action" value="submit" />
PHP
if(isset($_POST["action"]))
{
//code
}
Add dataType: 'json' to your ajax handler and further modify your code like this:
$.ajax({
type: 'POST',
dataType: 'json', // changed to json
url : 'PHPscript.php',
data: {form : $('#myform').serialize()},
success : function(data){ // added success handler
var myJSONresult = data;
alert(myJSONresult.yourFieldName);
}
});
set traditional to true like
$.ajax({
traditional:true,
//your rest of the ajax code
});
on the php end you are getting the value fine the problem is at the form serialization end

Popping an alert when Getting Information

How can i display an alert message or alert box when getting the information(not submitting)
i have few form structures(text type) in my html when i enter the id in one of the form and press get button all the other forms will be filled based on the form submitted.
for the above i am using json and jquery
Ex:
Jquery
$(document).ready(function(){
$("#button1").click(function(){
$.post('script_1.php', { id: $('input[name="id"]', '#myForm').val() },
function(json) {
$("input[name='title']").val(json.title);
$("input[name='name']").val(json.name);
$("input[name='age']").val(json.age);
$("#institution").val(json.institution);
}, "json");
});
json:
$abc_output = array('title' => $row['title'],'name' => $row['name'],'age' => $row['age'], 'institution' => $row['institution']);
echo json_encode($abc_output);
now the problem is all the id's will not be having information so when the user enters some id with no information pop up or alert box need to be submitted saying no id.
How can i do that?
Note: as it is get info the result will be displayed on the same page, if its submit i could have echoed id not found in DB in the server side php(script_1.php) which is not the case here.
Html:
id: <input type="text" name="id"/>
<div id="hidden" style="display: none;">
<p>Title:<input type="text" name="title"/></p>
<p>name:<input type="text" name="rno"/></p>
<p>age:<input type="text" name="age"/></p>
Institution: <select id="institution" name="institution">
<option value="None">-- Select --</option>
<option value="ab">ab</option>
<option value="bc">bc</option>
</select>
</div>
<br/>
<input type="button" id="button1" value ="Get Info" onclick="document.getElementById('hidden').style.display = '';"/>
</form>
<div id="age"></div>
</body>
</html>
It may be helpful to set up an AJAX error handler, to handle things like session timeouts, json 'parseerror', etc.
$(document).ajaxError(function() {
alert( "Triggered ajaxError handler." );
});
This can help you to determine if the problem is with the success callback not being called.
You didn't post your opening <form> tag, but i'm assuming it has an id of 'myForm' (which you won't need).
I checked your javascript, and found a syntax error (a missing });). Try this:
$(document).ready(function(){
$("#button1").click(function(){
$.post('script_1.php', { id: $('input[name="id"]').val() }, function(json) {
$("input[name='title']").val(json.title);
$("input[name='name']").val(json.name);
$("input[name='age']").val(json.age);
$("#institution").val(json.institution);
}, "json");
});
});
Notice I removed #myForm from the part that passes the values to php. The form itself does not have a value, the individual fields do.

Categories