How can I submit form using ajax - php

I want to show the output of polldemo1.php on poll.php page. But it is not happening. It is showing the poll.php page's form again as output.
Please correct it.Also if anyone can explain me php with ajax, it would be really nice
poll.php
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
</head>
<body>
<h3>SIG Polls</h3>
<form method="POST" id="myform" class="myform" >
C/C++
<input type="checkbox" name="vote[]" value="0" />
<br />
Java
<input type="checkbox" name="vote[]" value="1" />
<br />
Matlab
<input type="checkbox" name="vote[]" value="2" />
<br />
C#/.NET
<input type="checkbox" name="vote[]" value="3" />
<br />
PHOTOSHOP
<input type="checkbox" name="vote[]" value="4" />
<br />
CCNA
<input type="checkbox" name="vote[]" value="5" />
<br />
BASIC ELECTRONICS
<input type="checkbox" name="vote[]" value="6" />
<br />
<input type="submit" name="submit" value="vote" onclick="return submitForm()" />
</form>
<div id="myResponse"></div>
<script type="text/javascript">
function submitForm() {
var form = document.myform;
var dataString = $(form).serialize();
$.ajax({
type:'POST',
url:'polldemo1.php',
data: dataString,
success: function(data){
$('#myResponse').text(data);
}
});
return false;
}
</script>
</body>
</html>
polldemo1.php
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
</head>
<?php
echo "hello";
//error_reporting(0);
if(isset($_POST['submit']))
{
/*if (isset($_COOKIE["ieeepoll"]))
{
echo "<script>alert('You have already voted'); location.href='poll.php';</script>";
} */
//get content of textfile
$filename = "poll_result.txt";
$content = file($filename);
//put content in array
$array = explode("||", $content[0]);
$c = $array[0];
$java = $array[1];
$matlab = $array[2];
$net = $array[3];
$ph = $array[4];
$ccna = $array[5];
$be = $array[6];
foreach($_POST["vote"] as $vote)
{
if ($vote == 0)
{
$c = $c + 1;
}
if ($vote == 1)
{
$java = $java + 1;
}
if ($vote == 2)
{
$matlab = $matlab + 1;
}
if ($vote == 3)
{
$net = $net + 1;
}
if ($vote == 4)
{
$ph = $ph + 1;
}
if ($vote == 5)
{
$ccna = $ccna + 1;
}
if ($vote == 6)
{
$be = $be + 1;
}
}
//insert votes to txt file
$insert = $c."||".$java."||".$matlab."||".$net."||".$ph."||".$ccna."||".$be;
file_put_contents($filename,$insert);
echo $be;
}
?>

Add onsubmit event in for html form attribute as following
<form method="POST" id="myform" class="myform" onsubmit="return false" >
You can manage above thing by jQuery also, just need to modify your javascript code something like this.
$("#myform").on('submit', function (event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'polldemo1.php',
data: $("#myform").serialize(),
success: function (data, status) {
//do whatever you want to do
},
error: function (err) {
//do wahtever you want to do
}
});
});
//OR
$("#myform").on('submit', function (event) {
event.preventDefault();
submitForm();
});
Also you don't need to keep any html attribute in you php script. Remove all html tags from that script.

try this it should help you.it will display the content of the file on poll.php on submit of form.
poll.php
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
</head>
<body>
<h3>SIG Polls</h3>
<form method="POST" id="myform" class="myform" >
C/C++
<input type="checkbox" name="vote[]" value="0" />
<br />
Java
<input type="checkbox" name="vote[]" value="1" />
<br />
Matlab
<input type="checkbox" name="vote[]" value="2" />
<br />
C#/.NET
<input type="checkbox" name="vote[]" value="3" />
<br />
PHOTOSHOP
<input type="checkbox" name="vote[]" value="4" />
<br />
CCNA
<input type="checkbox" name="vote[]" value="5" />
<br />
BASIC ELECTRONICS
<input type="checkbox" name="vote[]" value="6" />
<br />
<input type="submit" name="submit" value="vote" onclick="return submitForm()" />
</form>
<div id="myResponse"></div>
<script type="text/javascript">
function submitForm() {
var dataString = $("#myform").serialize();
$.ajax({
type:'POST',
url:'index.php',
data: dataString,
success: function(data){
$('#myResponse').text(data);
}
});
return false;
}
</script>
</body>
</html>
polldemo1.php
<?php
echo "hello";
//error_reporting(0);
if(isset($_POST))// do not check for submit here it won't go with post
{
/*if (isset($_COOKIE["ieeepoll"]))
{
echo "<script>alert('You have already voted'); location.href='poll.php';</script>";
} */
//get content of textfile
$filename = "poll_result.txt";
$content = file($filename);
//put content in array
$array = explode("||", $content[0]);
$c = $array[0];
$java = $array[1];
$matlab = $array[2];
$net = $array[3];
$ph = $array[4];
$ccna = $array[5];
$be = $array[6];
foreach($_POST["vote"] as $vote)
{
if ($vote == 0)
{
$c = $c + 1;
}
if ($vote == 1)
{
$java = $java + 1;
}
if ($vote == 2)
{
$matlab = $matlab + 1;
}
if ($vote == 3)
{
$net = $net + 1;
}
if ($vote == 4)
{
$ph = $ph + 1;
}
if ($vote == 5)
{
$ccna = $ccna + 1;
}
if ($vote == 6)
{
$be = $be + 1;
}
}
//insert votes to txt file
$insert = $c."||".$java."||".$matlab."||".$net."||".$ph."||".$ccna."||".$be;
file_put_contents($filename,$insert);
echo $insert;
}
?>

Related

Cant Submit Form ( Saas, Paas, Iaas)

When I try to click on the submit or cancel the form nothing happens.
Here is part of the register_company.php code.
enter code here
<script type="text/JavaScript">
<!--
function getArrays() {
if (validateForm()) {
loadArray('appcatindex');
loadArray('targetindindex');
loadArray('managedservices');
document.getElementById('company').action = "<?php echo BASE_URL_JCM; ?>/save_company.php";
document.getElementById('company').submit();
} else {
return false;
}
}
function loadArray (tcIndex) {
if (document.getElementById(tcIndex) != null) {
lnLength = document.getElementById(tcIndex).length;
} else {
return true;
}
if (tcIndex == 'docindex') {
textDelim = "";
} else {
textDelim = "";
}
var lcIDs = "";
lcDelim = "";
for (var i=0;i<lnLength;i++) {
if (document.getElementById(tcIndex).options[i].selected) {
lcIDs = lcIDs + lcDelim + textDelim + document.getElementById(tcIndex).options[i].value + textDelim;
lcDelim = ",";
}
}
document.getElementById('a'+tcIndex).value = lcIDs;
}
function validateForm() {
lcReturn = "";
lcReturn = lcReturn + checkText('companyName','Company Name');
lcReturn = lcReturn + checkText('firstName','First Name');
lcReturn = lcReturn + checkText('contactEmail','Contact E-mail Address');
lcReturn = lcReturn + checkSelect('appcatindex','Application Categories');
lcReturn = lcReturn + checkSelect('targetindindex','Target Industries');
lcReturn = lcReturn + checkSelect('managedservices','Managed Services');
lcReturn = lcReturn + checkTextArea('hardwareTech','Hardware Technology');
lcReturn = lcReturn + checkTextArea('softwareTech','Software Technology');
lcReturn = lcReturn + checkTextArea('serviceSolution','Service Solutions');
lcReturn = lcReturn + checkTextArea('iaassolution','Infrastructure-as-Service(IaaS) Solution');
lcReturn = lcReturn + checkTextArea('paassolution','Platform-as-Service(PaaS) Solution');
lcReturn = lcReturn + checkTextArea('keyDiff','Key Differentiators');
lcReturn = lcReturn + checkTextArea('sampleCust','Sample Customer Names');
if (lcReturn != "") {
lcReturn = lcReturn + "\nPlease correct these fields and resubmit.";
alert(lcReturn);
return false;
}
return true;
}
function checkTextArea(tcField,tcLabel) {
lctext = "";
if (document.getElementById(tcField)) {
lctest = document.getElementById(tcField).value;
if (lctest.length > 250) {
lctext = tcLabel + " is greater than 250 characters ("+lctest.length+" used).\n";
}
}
return lctext;
}
function checkSelect(tcField,tcLabel) {
lctext = "";
if (document.getElementById(tcField)) {
lnLength = document.getElementById(tcField).length;
var lnSelCnt = 0;
for (var i=0;i<lnLength;i++) {
if (document.getElementById(tcField).options[i].selected) {
lnSelCnt++;
}
}
if (tcField!='appcatindex') {
if (tcField!='targetindindex') {
if (lnSelCnt > 5) {
lctext = tcLabel + " has more than 5 options selected ("+lnSelCnt+" selected).\n";
}
}
}
if (tcField=='appcatindex') {
if (lnSelCnt > <?php echo $saasAppCoLimit ?>)
{
lctext = tcLabel + " has more than <?php echo $saasAppCoLimit ?> options selected ("+lnSelCnt+" selected).\n";
}
}
if (tcField=='targetindindex' ) {
if (lnSelCnt > <?php echo $saasIndCoLimit ?>)
{
lctext = tcLabel + " has more than <?php echo $saasIndCoLimit ?> options selected ("+lnSelCnt+" selected).\n";
}
}
}
return lctext;
}
function checkText(tcField,tcLabel) {
lctext = "";
if (document.getElementById(tcField)) {
lctest = document.getElementById(tcField).value;
if (lctest == "") {
lctext = tcLabel + " is empty. This field is required.\n";
}
}
return lctext;
}
function updateStatus (toOption) {
lcStatus = toOption.value;
lcStatus = lcStatus.substring(0,1);
document.getElementById('status').value = lcStatus;
}
-->
</script>
<div id="divMain" align="center">
<div id="divContent" align="left">
<!--img src="<?php echo DOMAIN_URL ?>/343/images/company.jpg" border="0" width="670px" align="top" -->
<form name='company' id='company' method='post' action=''>
<!-- h3><?php echo $headtitle ?></h3 -->
<input type='button' value='Submit' onclick='getArrays();return false;' /> <input type='button' value='Cancel' onclick='self.close();' />
<input type="hidden" name="companyid" id="companyid" value="<?php echo $companyid ?>"><input type="hidden" name="querytype" id="querytype" value="<?php echo $querytype ?>">
<input type="hidden" name="profiletype" id="profiletype" value="<?php echo $profiletype ?>"><input type="hidden" name="status" id="status" value="<?php echo $status ?>">
<input type="hidden" name="key" id="key" value="<?php echo $key ?>"><input type="hidden" name="createDate" id="createDate" value="<?php echo $createDate ?>">
<input type="hidden" name="updateDate" id="updateDate" value="<?php echo $updateDate ?>"><input type="hidden" name="enablingTech" id="enablingTech" value="<?php echo $enablingTech ?>">
<input type="hidden" name="paas" id="paas" value="<?php echo $paas ?>"><input type="hidden" name="iaas" id="iaas" value="<?php echo $iaas ?>">
<input type="hidden" name="aappcatindex" id="aappcatindex" value=""><input type="hidden" name="atargetindindex" id="atargetindindex" value="">
<input type="hidden" name="amanagedservices" id="amanagedservices" value=""><input type="hidden" name="request_uri" id="request_uri" value="<?php echo $request_uri ?>">
</form>
</div>
</div>
Problem is only related to submit button it does nothing, I googled it but didn't find any posible solution.
Here is the web link http://www.cloudshowplace.com/saas/
You have a </form> tag but no <form> tag. Something like <form action="action_page.php" method="post"> should work. You could also attach javascript actions to the submit button.
Here the answer to my problem.
Changed input type "button" to "submit", and it started working like a charm.
<input type='submit' value='Submit' onclick='getArrays();return false;' />
<input type='submit' value='Cancel' onclick='self.close();' />

Echoing multiple checkbox values with different names

My HTML+JS :
<head>
<script type="text/javascript">
function passList() {
var p=[];
$('input.first').each( function() {
if($(this).attr('checked')) {
p.push($(this).attr('rel'));
}
} );
$.ajax( {
url:'process.php',
type:'POST',
data: {list:p},
success: function(res) {
$("#result").html(res);
}
});
}
function passType() {
var q=[];
$('input.second').each( function() {
if($(this).attr('checked')) {
q.push($(this).attr('rel'));
}
} );
$.ajax( {
url:'process.php',
type:'POST',
data: {type:q},
success: function(res) {
$("#result").html(res);
}
});
}
</script>
</head>
<body>
<input type="checkbox" class="first" rel="list1" onclick="passList()">list1<br />
<input type="checkbox" class="first" rel="list2" onclick="passList()">list2<br />
<input type="checkbox" class="first" rel="list3" onclick="passList()">list3<br />
<input type="checkbox" class="first" rel="list4" onclick="passList()">list4<br />
<br><br><br>
<input type="checkbox" class="second" rel="type1" onclick="passType()">type1<br />
<input type="checkbox" class="second" rel="type2" onclick="passType()">type2<br />
<input type="checkbox" class="second" rel="type3" onclick="passType()">type3<br />
<br><br><br>
<div id="result"> </div>
</body>
I am able to get the value in the div "result" thru the following script :
if(isset($_POST['list']) && !isset($_POST['type'])) {
foreach ($_POST['list'] as $list) {
echo "this is $list<br />";
}
}
else if(!isset($_POST['list']) && isset($_POST['type'])) {
foreach ($_POST['type'] as $type) {
echo "type is : $type<br />";
}
}
else if(isset($_POST['list']) && isset($_POST['type'])) {
foreach ($_POST['list'] as $list) {
echo "Showing ads for $list<br />";
foreach ($_POST['type'] as $type) {
echo "type is : $type<br />";
}
}
}
But i get the value of either the list or the type.
I want to be able to get the value of both at the same time. I dont want to use a .
Please help.
Thank you.

form $_POST error, dynamic fields

I have an error that I can't figure out...
Om my webpage there is a form that the user has the ability to add some new input fields to. If the user is submitting the form, then the optional fields is empty when the php-file is handing them, why?
HTML:
<form method="post" action="newRequest.php">
<input type="text" name="title" />
<input type="hidden" name="fname" value="0" />
<input type="checkbox" name="fname" value="1"/>
<input type="hidden" name="ename" value="0" />
<input type="checkbox" name="ename" value="1" />
<input type="hidden" name="seat" value="0" />
<input type="checkbox" name="seat" value="1" />
<input type="hidden" name="fields" value="0" />
<input type="text" id="fields" name="fields" />
<input type="submit" />
</form>
PHP:
if (strlen($_POST[title]) > 2) {
$toDb[title] = $_POST[title];
} else {
error('title');
}
$toDb[fname] = $_POST[fname];
$toDb[ename] = $_POST[ename];
$toDb[seat] = $_POST[seat];
if ($_POST[fields] > 0) {
$i = 0;
while ($i < $_POST[fields]) {
$toDb[optional][$i] = $_POST[optional-$i];
$i++;
}
$toDb[optional] = serialize($toDb[optional]);
} else {
$toDb[optional] = 0;
}
newEvent($toDb,$dbh);
JQuery that is adding dynamical fields:
$(document).ready(function() {
$('#fields').focusout(function(){
var fields = $('#fields').val();
var i = 0;
while(i < fields) {
$('#fields').after("Valfritt fält "+(i+1)+":<input type='text' name='optional"+i+"' />");
i++;
}
})
})
You should quote array indexes. It should be
$toDb['optional'][$i] = $_POST['optional'.$i];
You are missing commas in $_POST
$toDb['fname'] = $_POST['fname'];
$toDb['ename'] = $_POST['ename'];
$toDb['seat'] = $_POST['seat'];
Here is your modified code
if (strlen($_POST['title']) > 2) {
$toDb['title'] = $_POST['title'];
} else {
error('title');
}
$toDb['fname'] = $_POST['fname'];
$toDb['ename'] = $_POST['ename'];
$toDb['seat'] = $_POST['seat'];
if (count($_POST) > 0) {
$i = 0;
while ($i < count($_POST)) {
$toDb['optional'][$i] = $_POST['optional-'.$i];
$i++;
}
$toDb['optional'] = serialize($toDb['optional']);
} else {
$toDb['optional'] = 0;
}
newEvent($toDb,$dbh);
Also use count() to check if $_POST has values > 0.
I faced the same problem and I solved it using Javascript, like this :
add a new text field every time a button is pressed

Check/Uncheck all checkboxes with Javascript in a PHP array with keys

I have the following code:
Check All |
Uncheck All |
Invert Selection<br />
<table>
<tr>
<td><input type="checkbox" name="names[8]" value="yes" />Paul</td>
<td><input type="checkbox" name="names[11]" value="yes" />Bob</td>
<td><input type="checkbox" name="names[44]" value="yes" />Tom</td>
</tr>
</table>
And the following script:
function setCheckboxes3(act)
{
elts = document.getElementsByName("names[]");
var elts_cnt = (typeof(elts.length) != 'undefined') ? elts.length : 0;
if (elts_cnt)
{
for (var i = 0; i < elts_cnt; i++)
{
elts[i].checked = (act == 1 || act == 0) ? act : (elts[i].checked ? 0 : 1);
}
}
}
The script is working with other arrays without keys, but I can't get it to work with this array which has keys.
Thanks in advance
You can use getElementsByClassName:
<script type="text/javascript" language="javascript">
function setCheckboxes3(act) {
var e = document.getElementsByClassName('names');
var elts_cnt = (typeof(e.length) != 'undefined') ? e.length : 0;
if (!elts_cnt) {
return;
}
for (var i = 0; i < elts_cnt; i++) {
e[i].checked = (act == 1 || act == 0) ? act : (e[i].checked ? 0 : 1);
}
}
</script>
Check All |
Uncheck All |
Invert Selection<br />
<input type="checkbox" name="names[8]" class="names" value="yes" />Paul
<input type="checkbox" name="names[11]" class="names" value="yes" />Bob
<input type="checkbox" name="names[44]" class="names" value="yes" />Tom
OR you can use: getElementsByTagName
<script type="text/javascript" language="javascript">
function setCheckboxes3(act) {
var e = document.getElementsByTagName('input');
var elts_cnt = (typeof(e.length) != 'undefined') ? e.length : 0;
if (!elts_cnt) {
return;
}
for (var i = 0; i < elts_cnt; i++) {
if((e[i].type) == 'checkbox') {
e[i].checked = (act == 1 || act == 0) ? act : (e[i].checked ? 0 : 1);
}
}
}
</script>
Check All |
Uncheck All |
Invert Selection<br />
<input type="checkbox" name="names[8]" value="yes" />Paul
<input type="checkbox" name="names[11]" value="yes" />Bob
<input type="checkbox" name="names[44]" value="yes" />Tom
Did you get a chance to try jQuery?

How can i get checkboxes values while transfering in second page?Javascript

i have 5 checkboex. How can I get the value of them if any of them is checked and submited into the second page.
here is my html code.
<form action="test.php" method="post" onSubmit="return checkCheckBoxes(this);">
<input type="CHECKBOX" name="CHECKBOX_1" value="1">y
<input type="CHECKBOX" name="CHECKBOX_2" value="2">o
<input type="CHECKBOX" name="CHECKBOX_3" value="3">t
<input type="SUBMIT" value="Submit!">
</form>
here is Javascript code
<script type="text/javascript" language="javascript">
function checkCheckBoxes(theForm) {
if (
theForm.CHECKBOX_1.checked == false &&
theForm.CHECKBOX_2.checked == false &&
theForm.CHECKBOX_3.checked == false)
{
alert ('Please make sure to check a checkboxe!');
return false;
} else {
return true;
}
}
</script>
My dear first you need to change the names of your checkboxes to any array like this
<form action="test.php" method="post" onSubmit="return checkCheckBoxes(this);">
<input type="CHECKBOX" name="CHECKBOX[]" value="1">y
<input type="CHECKBOX" name="CHECKBOX[]" value="2">o
<input type="CHECKBOX" name="CHECKBOX[]" value="3">t
<input type="SUBMIT" value="Submit!">
</form>
On your test.php just traverse the whole array of CHECKBOX like this
for($_POST['CHECKBOX'] as $key=>$value)
{
if(isset($key))
echo('check box is checked and do some thing with '.$value);
else
echo('check box is not checked');
}
<script type="text/javascript" language="javascript">
function checkCheckBoxes(theForm) {
if(theForm.CHECKBOX_1.checked == false &&
theForm.CHECKBOX_2.checked == false &&
theForm.CHECKBOX_3.checked == false )
{
alert ('Please make sure to check a checkboxe!');
return false;
} else {
var val=''; var arr = new Array();
if(theForm.CHECKBOX_1.checked == true){
val += theForm.CHECKBOX_1.value; arr.push(/*push val*/);
}
if(theForm.CHECKBOX_2.checked == true){
val += theForm.CHECKBOX_2.value;
}
if(theForm.CHECKBOX_3.checked == true){
val += theForm.CHECKBOX_3.value;
}
alert(val); //echo out array elements
}
}
</script>
<form action="test.php" method="post" onSubmit="return checkCheckBoxes(this);">
<input type="CHECKBOX" name="CHECKBOX_1" value="1"/>y
<input type="CHECKBOX" name="CHECKBOX_2" value="2"/>o
<input type="CHECKBOX" name="CHECKBOX_3" value="3"/>t
<input type="SUBMIT" value="Submit!">
</form>
[UPDATE]::
<?php
for($_POST['CHECKBOX'] as $key=>$value)
{
if(isset($key))
echo "var val[".++$count."] = '".$value."'";
}
?>
<script type="text/javascript">
for(var i=0; i<val.length; i++)
alert(val[i]);
</script>

Categories