I have made a simple page which uses jquerydatepicker, two dropdown comboboxes for selecting time values. I tried to post the values but the page gets redirected to itself with selected values shown in url and I get no values on the receiver page.
Here's the script:
<script type="text/javascript">
$(document).ready(function(){
var jQueryDatePicker1Opts = {
dateFormat: 'mm/dd/yy',
changeMonth: false,
changeYear: false,
showButtonPanel: true,
showAnim: 'fadeIn'
};
$("#jQueryDatePicker1").datepicker(jQueryDatePicker1Opts);
$("#jQueryDatePicker1").datepicker("setDate", "new Date()");
$('#submit').click(function() {
var startTime = parseInt($('#Combobox1 option:selected').text());
var endTime = parseInt($('#Combobox2 option:selected').text());
if(startTime>=endTime){
alert("End Time should not be less than Start Time !");
return false;
}
});
$("#Campaign_form").submit(function(){
$.post({type:'POST', url:'campaigndata.php' ,
data:$('#Campaign_form').serialize(), success: function(response) {
$('#Campaign_form').find('.form_result').html(response);
}});
var isValid = $.validate.form(this);
return isValid;
});
});
</script>
Here is the form script:
<form name="Campaign_form" id="Campaign_form" >
<input type="text" id="jQueryDatePicker1" name="jQueryDatePicker1" value="06/09/2012">
<select name="StartTime" size="1" id="Combobox1" >
<option value="1">01:00</option>
...
<option value="24">23:00</option>
</select>
<select name="EndTime" size="1" id="Combobox2" >
<option value="1">01:00</option>
...
<option value="24">00:00</option>
</select>
<select name="SelectApp" size="1" id="Combobox3" >
<?php
while($row = mysql_fetch_array($result)){
echo "<option value =".$row['AppName'].">".$row['AppName']."</option>";
}
?>
</select>
<input type="submit" id="submit" name="submit" value="submit" >
</form>
Here is the campaigndata.php script:
<?php
$campaignDate = $_POST['jQueryDatePicker1'];
$camp_Start_Time = mysql_real_escape_string($_POST['StartTime']);
$camp_End_Time = mysql_real_escape_string($_POST['EndTime']);
$campaignID = $appid.$campaignDate.$camp_Start_Time ;
?>
This campaigndata.php shows null values on echoing above php variables.
You need to connect to your database before you can use mysql_real_escape_string() and change the form method to post.
You have to return false if you don't refresh page by submitting form
$("#Campaign_form").submit(function () {
var isValid = $.validate.form(this);
if (isValid)
$.post({type:'POST', url:'campaigndata.php',
data:$('#Campaign_form').serialize(), success:function (response) {
$('#Campaign_form').find('.form_result').html(response);
}});
return false;
});
ur answers helped me a lot !!! i figured out the problem was in capaigndata.php
i was using mysql_real_escape_string() before $_POST[''] ;
which was creating problems .
I removed those and used normal $_POST[] and it worked magically !!! :)
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 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.
I'm having two pages with similar textboxes when user inserts data into first page and goes to next page, if he need to give same data am adding a checkbox, when user clicks it same data which is in session from before page has to be get into the second page variables through ajax. can someone help me please. thanks
Response for the Comment
I made sample code which will give you idea about how to can do this.
jQuery Code for checkbox change event
$(function(){
$('input:checkbox').change(function(){
if($(this).is(':checked'))
{
$.ajax({
url : 'script.php',
success : function(session)
{
$('input:text').val(session);
}
});
}
});
});
HTML
<input type="text" />
<input type="checkbox" />
script.php
<?php
session_start();
echo $_SESSION['name_of_the_session_variable'];
exit;
?>
EDIT
$("#checked").click(function()
{
if ($(this).is(':checked'))
{
$('#provisional_total_public_funding').val(<?php echo empty($this->session->store['actual_info']['actual_total_public_funding']) ? '' : $this->session->store['actual_info']['actual_total_public_funding']; ?>);
}
});
Ajax Request Response
<select name="fin_year" id="fin_year">
<option value="" >Please select an year</option>
<option value="<?= $actFinYr; ?>"><?= $actFinYr; ?></option>
</select>
<script type="text/javascript">
$(function(){
$('#fin_year').change(function()
{
var options = $(this);
if(options.val() != '')
{
$.ajax(
{
url : 'CODEIGNITER_HTTP_URL/'+options.val(),
beforeSend : function()
{
//show loading
},
success : function(response)
{
//play with the response from server.
}
});
}
});
});
</script>
I'd use jQuery like this:
HTML 1st page:
input1 <input type="text" id="input1" name="input1"/>
input2 <input type="text" id="input2" name="input2"/>
jQuery 1st page:
$input1 = $("#input1");
$input2 = $("#input2");
$input1.keydown(function(){
$.post("yourPHP.php", {input1: $input1.val()});
});
$input2.keydown(function(){
$.post("yourPHP.php", {input1: $input1.val()});
});
PHP 1st page:
if(session_id() == '') {
session_start();
}
if(isset($_POST['input1'])){
$_SESSION['input1'] = $_POST['input1'];
}
if(isset($_POST['input2'])){
$_SESSION['input2'] = $_POST['input2'];
}
HTML 2nd page:
input1 <input type="text" id="input1" name="input1"/>
input2 <input type="text" id="input2" name="input2"/>
<br/>
radio1 <input type="radio" id="radio1" name="radio"/>
radio2 <input type="radio" id="radio2" name="radio"/>
jQuery second page:
$input1 = $("#input1");
$input2 = $("#input2");
$radio1 = $("#radio1");
$radio2 = $("#radio2");
$radio.click(function(){
$.post("yourPHP.php", {request: "input1"}, function(data){
$input1.val(data);
});
});
$input2.keydown(function(){
$.post("yourPHP.php", {request: "input2"}, function(data){
$input2.val(data);
});
});
PHP 2nd page:
if(session_id() == '') {
session_start();
}
if(isset($_POST['request'])){
switch($POST['request']){
case 'input1':
echo $_SESSION['input1'];
break;
case 'input2':
echo $_SESSION['input2'];
break;
}
}
I hope it works.