Submit form checkbox value without page refresh Ajax php - php

Still learning ajax.
Now i go stuck at this point.
Am trying to get the value of the checkbox on my form.
Below is my HTML code
<form method="post">
<input type="text" name="mytext" id="text">
<br>
<input type="checkbox" name="test" id="agreed" value="check">
<br>
<input type="submit" id="form4" name="submit" value="Send">
<p class="form-message"></p>
</form>
Below is my Ajax Script
$(document).ready(function() {
$("#form4").click(function(event) {
var action = 'another_test';
var text = $("#text").val();
var agreed = $("#agreed").val();
event.preventDefault();
$.ajax({
type: "POST",
url: "test3.php",
data: {
mytext:text,
test:agreed,
action:action
},
success: function (response)
{
$(".form-message").html(response);
}
});
});
});
Then this is my PHP code below which is on a different page
<?php
if (isset($_POST['action']))
{
if ($_POST['action'] == 'another_test') {
$test = $_POST["test"];
$mytext = $_POST["mytext"];
$errorEmpty = false;
if (empty($mytext)) {
echo "<p>enter your text</p>";
$errorEmpty = true;
}
elseif (empty($test)) {
echo "<p>Click the checkbox</p>";
$errorEmpty = true;
}
else {
echo "<p>Correct</p>";
}
} else {
echo "Error.. cant submit";
}
}
?>
<script>
var errorEmpty = "<?php echo $errorEmpty ?>";
</script>
It works for text, textarea input but not for checkbox. I know am wrong. Am still learning though.
Please help me. Thanks in advance.

Using $("#agreed").val() you only receive the value you setted in the "value" attribute on your input checkbox tag. To get a boolean value of checkbox's state you have to do use .is() function
$("#agreed").is(":checked");

Related

Input validation through AJAX

I have the following AJAX in my index.php:
$(document).ready(function() {
$('.buttono').click(load);
});
function load() {
$.ajax({
url: 'http://localhost/Generator/js/ajaxRequest.php'
}).done(function(data) {
$('#content').append(data);
});
}
HTML (part of index.php):
<form method="POST" action="">
<input type="text" name="input">
<input type="submit" name="submit" class="buttono" value="Convert">
</form>
<div id='content'></div>
And in my ajaxRequest.php I have the following PHP snippet:
if ($_POST['input'] == 'dog') {
echo 'Status 1';
} else if ($_POST['input'] == 'cat') {
echo 'Status 2';
}
How can I perform the PHP check through AJAX? So that if I click the submit button and have typed 'dog', to return the string Status 1?
Well what I see in your code is that:
first you have not specified your request method,
second you have not set $_POST['dog']
I would have gone with this ajax:
$.ajax({
type : "POST",
url : 'to/url',
data : { input : $("input[name='input']").val() },
success : function(data){
// do whatever you like
}
});
What you have to do is make the user fill out the form and then instead of clicking a type="submit" button just make them click a regular button. Then when that person clicks the regular button submit. You can do this by:
<!-- HTML -->
<form method="POST">
<input type="text" id="type"/>
<button id="submit">Sumbit</button>
</form>
<!-- JS -->
$(document).ready(function(){
$('#submit').click(onSubmitClicked);
});
function onSubmitClicked(){
var data = {
"input": $('#type').val()
};
$.ajax({
type: "POST",
url: "url/To/Your/Form/Action",
data: data,
success: success
});
function success(data){
if(data == 'status 1'){
//Do something
}
}
}
Try this:
in you php file:
$res = array();
if ($_POST['input'] == 'dog') {
$res['status'] = '1';
} elseif ($_POST['input'] == 'cat') {
$res['status'] = '2';
}
echo json_encode($res);
Then in your jquery:
function load(){
$.ajax({
type : "POST",
data : { input : $("input[name='input']").val() },
url:'http://localhost/Generator/js/ajaxRequest.php'
}).done(function(data){
$('#content').append(data.status);
});
}

jQuery AJAX POST to current page with attribute

This is an example of my own page.
<?php
$do = $_GET['do'];
switch($do){
case 'finalTask':
if(isset($_POST['url'])){
echo "It's Ok!";
}else{
echo "Problem!";
}
}
This is also written in the same page.
<input type='text' id='siteName'>
<button type='submit' id='send'>Send</button>
<div id='info'></div>
<script>
$(document).ready(function(e){
$('#send').click(function(){
var name = $('#siteName').val();
var dataStr = 'url=' + name;
$.ajax({
url:"index.php?do=finalTask",
cache:false,
data:dataStr,
type:"POST",
success:function(data){
$('#info').html(data);
}
});
});
});
</script>
When I try to input and press the send button. Nothing happened..... What's wrong with the code?
Make sure file name is index.php
You need to make sure that you check in the php code when to output the form and when the
Format of ajax post request is incorrect in your case.
You forgot to import JQuery JS script, without that you can not use JQuery. (at least at this point of time)
-
<?php
if (!isset($_GET['do'])) { // Make sure that you don't get the form twice after submitting the data
?>
<input type='text' id='siteName'>
<button type='submit' id='send'>Send</button>
<div id='info'></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function (e) {
$('#send').click(function () {
var name = $('#siteName').val();
var dataStr = 'url=' + name;
$.ajax({
url: "index.php?do=finalTask",
cache: false,
data: {url: dataStr}, // you need to send as name:value format.
type: "POST",
success: function (data) {
$('#info').html(data);
}
});
});
});
</script>
<?php
} else {
error_reporting(E_ERROR); // Disable warning and enable only error reports.
$do = $_GET['do'];
switch ($do) {
case 'finalTask':
if (isset($_POST['url'])) {
echo "It's Ok!";
} else {
echo "Problem!";
}
}
}
?>
There seems to be no form in your page, just form elements. Can you wrap them in a form:
<form method="POST" onSubmit="return false;">
<input type='text' id='siteName'>
<button type='submit' id='send'>Send</button>
</form>

how to get session values to textbox when checkbox is clicked in jquery

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.

JQuery issue on Ipad

I have a popup form on which a user provides a key to get access to the site. I validate the user provided key with Jquery. It is working fine on my local system but when I submit the form using ipad it does not work. The form is even nor submitted.
My Form is
<form name="form" method="post">
<div style="width:530px;">
<input style="display:none; height:25px;" id="downloadkey" name="downloadkey" type="text" />
<input style="display:none;" type="submit" id="submit" name="submit" value="<?php echo $variable['QUESTION_BUTTON']['value'] ?>"/>
</div>
<input type="hidden" id ="box_id" value="<?php echo $box_id ?>" />
</form>
JQuery is
$(document).ready(function() {
$('#submit').click(function(e) {
var key = $('#downloadkey').val();
var box_id = $('#box_id').val();
var dataString = {KEY:key, BID:box_id};
$.ajax({
url: "/home/validate_key",
type: 'POST',
data: dataString,
success: function(msg) {
if(msg=="false"){
alert("Your download key is either wrong or missing");
}
else{
$('#popupContact').hide();
$('#backgroundPopup').hide();
}
}
});
e.preventDefault();
});
});
In my controller the validate function is
function validate_key(){
$key = strtolower($this->input->post('KEY'));
$id = $this->input->post('BID');
$query = $this->db->get_where('mc_boxes', array('idmc_boxes' => $id));
$row = $query->row();
$download_key = strtolower($row->downloadkey);
if($download_key == $key){
$_SESSION['download_key'] = $key;
$_SESSION['timeout'] = time();
}
else{
echo 'false';
}
}
Do i need something special to make it working on ipad?
Thanks
jQuery.click() doesn't function properly on iOS.
Try using jQuery.on() or by binding other events like touchstart
.bind("click touch tap", function(){
// code
});
Is what I've seen used when dealing with iPad.
(It's not a CodeIgniter issue for sure.)

jQuery / php - Multply forms on page, submit only one

I have two forms on my website, and I use jQuery to submit them, to my PHP script.
These are the forms:
<form method="post" class="settings-form" id="passwordSettings">
<label id="npasswordbox" class="infoLabel">New Password: </label>
<input type="password" name="npassword" size="50" value="" >
<div class="move"></div>
<label id="cnpasswordbox" class="infoLabel">Confirm: </label>
<input type="password" name="cnpassword" size="50" value="" >
<button class="btn" name="passwordSetings" style="margin-left:185px" type="submit">Save </button>
</form><!-- end form -->
And the next:
<form method="post" class="settings-form" id="normalSettings">
<label id="npasswordbox" class="infoLabel">New Username: </label>
<input type="text" name="username" size="50" value="" >
<div class="move"></div>
<button class="btn" name="normalSettings" style="margin-left:185px" type="submit">Save </button>
</form><!-- end form -->
Here is the jQuery I have written for these two forms:
$(function() {
$('form#passwordSettings').submit(function(){
$('#status').hide();
$.post(
'index.php?i=a&p=s',
$('form#passwordSettings').serialize(),
function (data) {
proccessPWData(data);
}
);
return false;
});
});
function proccessPWData (data) {
$('#status').hide().html('');
if(data=='success'){
$('form#normalSettings').fadeOut();
$('html, body').animate({scrollTop:0});
$("#status").removeClass();
$('#status').addClass('alert alert-success').html('You have successfully changed your personal settings.<br />').slideDown().delay(5000);
redirect("/account");
}
else {
$('html, body').animate({scrollTop:0});
$('#status').removeClass().addClass('alert alert-error').html(data).fadeIn();
setTimeout(function(){
$('#status').slideUp("slow");
},7000);
}
}
$(function() {
$('form#normalSettings').submit(function(){
$('#status').hide();
$.post(
'index.php?i=a&p=s',
$('form#normalSettings').serialize(),
function (data) {
proccessData(data);
}
);
return false;
});
});
function proccessData (data) {
$('#status').hide().html('');
if(data=='success'){
$('form#normalSettings').fadeOut();
$('html, body').animate({scrollTop:0});
$("#status").removeClass();
$('#status').addClass('alert alert-success').html('You have successfully changed your personal settings.<br />').slideDown().delay(5000);
redirect("/account");
}
else {
$('html, body').animate({scrollTop:0});
$('#status').removeClass().addClass('alert alert-error').html(data).fadeIn();
setTimeout(function(){
$('#status').slideUp("slow");
},7000);
}
}
And then the PHP code:
if(isset($_POST['normalSettings']))
{
$username = inputFilter($_POST['username']);
if(!$username){
$error ="no username";
}
if(!$error){
echo "success!";
}
}
if(isset($_POST['passwordSettings']))
{
$password = inputFilter($_POST['npassword']);
if(!$username){
$error ="no pw";
}
if(!$error){
echo "success!";
}
}
My problem is, that whenever I submit one of these forms, I see the form with my $error in the #status div.
How can I have multiply forms on one page, but submit the correct ones?
$(function() {
$('form#passwordSettings').submit(function(e){
e.preventDefault(); // prevents the default action (in this case, submitting the form)
$('#status').hide();
$.post(
'index.php?i=a&p=s',
$('form#passwordSettings').serialize(),
function (data) {
proccessPWData(data);
}
);
return false;
});
});
or you could just give an hidden input-field with it
<input type="hidden" name="_normalSettings">
and check in your PHP
if (isset($_POST['_normalSettings']) // ...
This is basically just answer to your question: "How can I have multiple forms on one page, but submit the correct ones?"
I have many dynamically generated forms on a single page and I send them to process file one by one. This is one form simplified:
<form name="form" id="form">
<!--form fields
hidden field could be used to trigger wanted process in the process file
-->
<input type="hidden" name="secret_process_id" value="1" />
<a class="button_ajax">Send form</a>
</form>
<div id="process_msg<?php echo $id; ?>"></div>
And here's the form submit function:
$(document).ready(function() {
$('.submit_ajax').click(function() { //serializes the parent form
//alert($(this).serialize());
dataString = $(this).parent().serialize();
//if you want to echo some message right below the processed form
var id = /id=\d+/.exec(dataString);
var id = /\d+/.exec(id);
$.ajax({
type: 'post',
url: '_process.php?ajax=1', //some or none parameters
data: dataString,
dataType: 'html',
success: function(data) {
$('#process_msg' + id).fadeIn(400);
$('#process_msg' + id).html(data);
}
}); //end of $.ajax
return false;
});
});
All you need is a process file/function and you are ready to go. Works just fine with one or dozens of forms. There you can do something like this:
if ($_POST['secret_process_id']==1){
//do something
}
if ($_POST['secret_process_id']==2){
//do something else
}
//etc.

Categories