Issue passing value between javascript and php - Popup PHP Javascript HTML - javascript

I am trying to incorporate a popup into my project. It works up until I try and pass a value from javascript to the php script. I have included a link to the example I used and link to the original script. There were slight changes made to the original script. The area I am having an issue with is marked with a ---->
full script can be found here:
http://www.webdeveloper.com/forum/showthread.php?279111-Contact-form-popup-window
working example can be found here:
http://ilolo.ru/wd/contact_form/
I have the following in hello.html
<form id='form1' style='width: 1100px'>
<table>
<th>Email</th>
<th>Options</th>
<tr>
<td>
<input type='text' id='email1' size='25' value='bob#mail.com'>
</td>
<td><a id='1' href='#null' class='contactus'><img src= 'images/emailbutton.jpg' title='Email' border='0' height='24' width='24'></img></a>
</tr>
</table>
</form>
The following js is in a .js that I reference in my html.
I use the following since I have more than one form. Just showed one form in my example.
The alert below works....shows the correct email address when I click on the image link in the html.
function findCenter(obj) {
var deltaX = parseInt(obj.css('padding-left')),
deltaY = parseInt(obj.css('padding-top'));
obj.css('left', $(window).width() / 2 - obj.width() / 2 - deltaX + 'px').css('top', $(window).height() / 2 - obj.height() / 2 - deltaY + 'px');
}
$(document).ready(function () {
$('.contactus').click(function () {
var element = $(this);
var J = element.attr('id');
var email = document.getElementById('email'+J).value;
alert(email);
$('#result').html('<h3>Loading</h3>').css('display', 'block');
findCenter($('#result'));
$.get('email.php', function (data) {
$('#result').html(data);
findCenter($('#result'));
$('#snd').click(function () {
var subject = document.getElementById('subject').value;
var addy = document.getElementById('addy').value;
var comments = document.getElementById('comments').value;
$('#result').append('<br /><br /><div><i>Sending...</i></div>');
$.post('lbi_email.php',{mode: 'snd', subject: subject, addy: addy, comments: comments},function(data){
$('#result').html(data);
findCenter($('#result'));
});
});
});
});
});
email.php
This value below is not getting sent by the javascript and the input value=$email is not written correctly (I think)
<?php
include( 'connection.php');
function showForm(){
$email=$_POST[ 'email'];
echo '<form name="mf" id="mf" action="" method="post">
<h2>Send Email To Customer</h2><br />
<p><label>Address :</label><input type="text" size="35" name="addy" id="addy" value="'.$email.'"/></p>
<p><label>Subject : </label><input type="text" size="35" name="subject" id="subject" value=""/></p>
<label>Message:</label><textarea style="width: 100%;" cols="20" rows="10" id="comments" name="comments"></textarea>
<p><img src="submitbutton.jpg" title="Submit Email" border="0" height="25" width="75"></img></p></form>';
}
function sndForm(){
/* here goes checking data and so on... then sending if everything 's good and sending done show message to the user*/
echo '<h3>Everything\'s cool.
<br />
<br />Viva Cuba!</h3>
<script type="text/javascript">
setTimeout(\'$("#result").fadeOut("fast")\',3000);
</script>';
}
/*---------------------------------------------------------------------*/
$mode=(!empty($_GET['mode']))?$_GET['mode']:$_POST['mode'];
switch($mode)
{
case 'snd':sndForm();break;
default: showForm();break;
}
?>

In your javascript you are sending literal email instead of your email value -
$.post('email.php',{mode: 'snd', email: 'email'},function(data){
Change this to -
$.post('email.php',{mode: 'snd', email: email},function(data){
In your php code you have a variable scope issue - $email is outside the scope of your function
$email=$_POST[ 'email'];
function showForm(){
echo $email;
Try setting it inside
function showForm(){
$email=$_POST[ 'email'];
echo $email;
Finally, you have $email inside single quotes-
echo '<form name="mf" id="mf" action="" method="post">
<h2>Send Email To Customer</h2><br />
<input type='text ' value='$email '/>
...
Need to update to
echo '<form name="mf" id="mf" action="" method="post">
<h2>Send Email To Customer</h2><br />
<input type="text" value="'.$email.'"/>
...
Additionally, it looks like when you are submitting the for you are not sending the comments textarea, so you probably need to add that as well.
$('#snd').click(function () {
$('#result').append('<br /><br /><div><i>Sending...</i></div>');
var comments = document.getElementById('comments').value;
$.post('email.php',{mode: 'snd', email: email, comments: comments},function(data){
$('#result').html(data);
findCenter($('#result'));
});
});
Edit
You need to add the email value to your $.get() -
$.get('email.php', email: email, function (data) {
and then change it to $_GET['email'] in your php -
function showForm(){
$email=$_GET[ 'email'];

Related

Get entry from one form field and search for its corresponding data in database and auto fill other fields in form

I am writing a code for billing, here inside it rather to enter every entry by typing i wanted to do something like if record already exist then, enter one field other corresponding fields will automatically be filled with corresponding data. For eg: inside my form there is a section to display customer info and that is done by entering customer_id then a PHP file fetches name address phone number and other data corresponding to the entered customer_id and auto fill other customer fields of form.
HTML form
<form action="./manipulate/invoice.php" method="post" accept-charset="UTF-8">
<div style="width:15%;float:left">
Customer #
<br>
<input id="searchbox" style="width:98%;margin-left:1%;margin:right:1%" name="cust_id" type="text" placeholder="Customer ID">
</div>
<div class="w3-container">
<div style="width:100%;">
<h4>Contact Info About Customer</h4>
</div>
<div style="width:30%;float:left" >
<input id="cust_address" style="width:98%;margin-left:1%;margin:right:1%" type="text" placeholder="Customer_Address" >
</div>
<div style="width:15%;float:left">
<input style="width:98%;margin-left:1%;margin:right:1%" type="text" placeholder="City" id="cust_city">
</div>
<div style="width:15%;float:left">
<input style="width:98%;margin-left:1%;margin:right:1%" type="text" placeholder="State" id="cust_state">
</div>
<div style="width:15%;float:left">
<input style="width:98%;margin-left:1%;margin:right:1%" type="number" placeholder="Pincode" id="cust_pincode">
</div>
<div style="width:25%;float:left">
<input style="width:98%;margin-left:1%;margin:right:1%" type="number" placeholder="Phone Number" id="cust_phone">
</div>
</div>
</form>
Javascript function:
<script>
$(document).ready(function () {
function trial(s){
$('#searchbox').val(s);
$.ajax({
url:'./manipulate/get_addre.php',
type:'POST',
data:'cust_id='+s,
dataType:'json',
success:function(e){
//$('#cust_add').append(e['address']);
$('#cust_Address').val(e['address']);
$('#cust_city').val(e['city']);
$('#cust_state').val(e['state']);
$('#cust_pincode').val(e['pincode']);
$('#cust_phone').val(e['phone']);
$('#cust_Name').val(e['name']);
}
});
}
});
$('#searchbox').change(function() {
trail($(this).val());
});
</script>
get_addre.php is
<?php
$mysqli = new mysqli("localhost","root","","tssolutions");
if($mysqli->connect_errno){
echo "connection failed : $mysqli->connect_errno";
exit();
}
$cust_id = $_POST['cust_name'];
$query = "SELECT * FROM customer WHERE customerid = '".$cust_id."' ";
//echo 'hi';
if($result = $mysqli->query($query)){
/* fetch details*/
while($row = $result->fetch_assoc()){
$json = json_encode($row);
//return $json;
echo $json;
//echo "<b>Address : </b>".$row['address'].", ".$row['city'].", ".$row['state'].", ".$row['pincode'].", contact no. ".$row['phone'];
}
$result->free();
}
$mysqli->close();
?>
And in invoice.php these fields + some more fields are being inserted into another table in database.
The problem i am facing is whenever i enter into customer_id field in form rest all fields remains blank which were supposed to auto fill..
Anyone can correct it ? Thanks in advance.
The first thing i have to say is: Your code is vulnerable to SQL Injection. You should change this line:
$cust_id = $_POST['cust_name'];
to this line:
$cust_id = $mysqli->real_escape_string($_POST['cust_name']);
On the first glance i do not see any error, but oddly there is no event handler, that will acutally call your JavaScript trial function. It seems like you are missing this part of the code:
$('#searchbox').change(function() {
trial($(this).val());
});
Edit
After rebuilding your application i have found your error. You are sending data with the name 'cust_id' but you are requesting data with the name 'cust_name'. Once you change your names to the correct one, this will work.
You can use the web developer consoles (F12 in Chrome and Firefox) to have a look at the server response to your ajax calls in the newtwork tab.

PHP To Create Add Another Button

I am creating a php page for camp registration, very basic and I do not want to plaster the page with multiple Name label/textbox. What I was thinking was to by default have one textbox and one label, and possibly blue text that says add another (or even a button) that when pressed the page will keep the current data but add an additional label and textbox so that more info can be added in. This is how I am capturing the data for 1, could this easily be modified in order to achieve my above outcome?
<td><label for="lblName">Campers Name:</label></td>
<td class="style1"><input type="text" name="txtName"
maxlength="100" size="30"></td>
EDIT
The link ad does nothing when I click it, I am sure it is I am missing the obvious but here is full syntax, what should I alter to make it work?
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
<script type="text/javascript">
$("#newCamper").on('click', function() {
$('#Campers').after(
'<div id="Campers">' +
'<td><label for="lblName">Campers Name: </label></td>' +
'<td class="style1"><input type="text" name="txtName" maxlength="100" size="30"></td>' +
' remove this' +
'</div>'
);
});
$(document).on('click', '#rmCamper', function() {
$(this).closest('#Campers').remove();
});
</script>
</head>
<body>
<div id="Campers">
<td><label for="lblName">Campers Name:</label></td>
<td class="style1"><input type="text" name="txtName" maxlength="100" size="30"></td>
Add another
</div>
</body>
</html>
EDIT #2
when I go to localhost on my machine and push the Add button it changes the URL to localhost# but no additional fields are added to the page?
i think you can use a little of jquery code to do this job ;) all you have to do is include https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js
in your page.
<div id="Campers">
<td><label for="lblName">Campers Name:</label></td>
<td class="style1"><input type="text" name="txtName" maxlength="100" size="30"></td>
Add another
</div>
// jquery code below:
$("#newCamper").on('click', function() {
$('#Campers').after(
'<div id="Campers">' +
'<td><label for="lblName">Campers Name: </label></td>' +
'<td class="style1"><input type="text" name="txtName" maxlength="100" size="30"></td>' +
' remove this' +
'</div>'
);
});
$(document).on('click', '#rmCamper', function() {
$(this).closest('#Campers').remove();
});
https://jsfiddle.net/yb88s47s/
In real life one would probably be best of using javascript for this indeed. It is perfectly possible with just php however. Have a look at the following example:
<?php
$names = isset($_GET['txt']) ? $_GET['txt'] : [];
$i = 0;
?>
<form method="get">
<?php foreach ($names as $name) : ?>
<label for="txt<?= $i ?>">member</label>
<input name="txt[]" id="xt<?= $i ?>" value="<?= $name ?>">
<br>
<?php $i++ ?>
<?php endforeach; ?>
<label for="txt<?= $i ?>">member</label>
<input name="txt[]" id="xt<?= $i ?>">
<button type='submit'>
add
</button>
</form>
This form will submit to itself. It starts by getting the array of names (note the [] on the txt[] field). It then iterates over them and displays each of them as an input. After the loop you just add 1 extra, empty field.
This is obviously a very basic example, you'll probably want some validation, and a name on that add button to be able to distinguish it from the actual final submit. It is just a proof of concept.
Have a look at the code in action here. Feel free to ask if anything is unclear.
I know that you're looking for an answer in PHP, but for what you need to do (DOM manipulation), you'd be better off using JavaScript. You can create another input field and increment a variable to append to the ID field of same. See this question. If you keep track of the total number of input fields that have been created in this fashion, you could iterate over those on form submission to capture all of the data.

jQuery/JS/PHP - Disable Form and Submit button only after submit

I have a form that I would like to disable the submit button and form itself after it has submitted. The form currently submits to itself and all the solutions I've tried so far either disable the form and submit button, but the form is never submitted or the form is submitted but the button/form are not disabled.
PHP:
<?php
if(isset($_POST['send'])){
if(!isset($_SESSION))
{
session_start();
session_regenerate_id();
}
if($_SESSION['user_login_status']==false)
{header('Location:../index.php');}
$Firstname = $_POST["firstname"];
$Lastname = $_POST["lastname"];
$EmpID = $_POST["employeeid"];
$Ticket = $_POST["ticket"];
$Office = $_POST["office"];
$Division = $_POST["division"];
$Device = $_POST["device"];
$Secure = $_POST["secure"];
$Zendesk = $_POST["zendesk"];
$Agent = $_SESSION['user'];
$psPath = 'c:\\Windows\\System32\WindowsPowerShell\v1.0\\powershell.exe -version 5';
$psDIR = "d:\\wamp64\\www\\includes\\";
$psScript = "NewHire.ps1";
$runCMD = $psPath. ' -ExecutionPolicy RemoteSigned '.$psDIR.$psScript.' -Firstname ' .$Firstname. ' -Lastname '.$Lastname. ' -EmpID ' .$EmpID. ' -Ticket ' .$Ticket. ' -Office ' .$Office. ' -Division ' .$Division. ' -Device ' .$Device. ' -Secure ' .$Secure. ' -Zendesk ' .$Zendesk. ' -Agent ' .$Agent;
$createuser = exec($runCMD, $out);
}
?>
Trimmed down HTML:
<form class="rnd5" method="post" id="frm">
<div class="form-input clear">
<label class="one_third" for="firstname">Firstname <span class="required"><font color="red">*</font></span>
<input type="text" name="firstname" id="firstname" autofocus required>
</label>
</div>
<!-- ################################################################################################ -->
<div class="form-input clear">
<label class="one_third" for="lastname">Lastname <span class="required"><font color="red">*</font></span>
<input type="text" name="lastname" id="lastname" required>
</label>
</div>
<p>
<input type="submit" name="send" value="Submit">
<input type="reset" value="Reset">
</p>
</form>
</div>
<!-- ################################################################################################ -->
<div class="clear"></div>
</div>
</div>
<!-- Footer -->
<?php include('../footer.php'); ?>
</body>
</html>
I have tried different functions such as:
$(function () {
$(".send").click(function () {
$(".send").attr("disabled", true);
$('#frm').submit();
});
});
and
$('input:submit').click(function(){
$('input:submit').attr("disabled", true);
});
Nothing so far appears to be working. Anyone have ideas?
I can see two fundamental problems with your code. Firstly your jQuery selectors.
In the first function: The . selector (as in $(".send") works on the class attribute, not the name attribute. I would suggest you either change your Inputs to have class = send or you change the selector to $("[name=send]").
In the second function. I'm pretty sure $('input:submit') isn't a valid selector, and I'm not sure what is meant by it.
Check out: http://www.w3schools.com/jquery/jquery_ref_selectors.asp
The second problem is that you are submitting the form and thus triggering a page reload. I take it that this isn't the desired behaviour if you want to disable the form buttons? In which case you should disable the default behaviour of the button (There are many ways of doing that: Stop form refreshing page on submit ) and POST the data to the server yourself.
This would leave you with something like the following:
$(function () {
$("[name='send']").click(function () {
$(this).attr("disabled", true);
$("#frm").submit();
});
$("#frm").on("submit",function() {
$.post("http://example.com/your_php_file.php",$(this).serialize());
$(this).preventDefault();
});
});
I haven't been able to test this myself because I don't have much time nor a handy web server, but this should give you a good start.

Trouble with AJAX and PHP

I have a form, and it has a field for entering a PIN code. Here I am using ajax for finding place when enter PIN code. It works when that field is not enclose in a form. If it is enclosed in a form, AJAX is not working.
HTML CODE:
<form id="form" class="blocks" action="#" method="post" enctype="multipart/form-data">
<div class="col_4 right">
<label for="fullname">FirstName:</label>
<input name="fname" type="text" class="text" />
</div>
<div class="col_4 right">
<label for="pincode">Pin-Code:</label>
<input name="pincode" type="text" class="text" id="pincode" />
<div id="section1"></div>
</div>
</form>
JS CODE:
<script>
$(document).ready(function() {
$('#pincode').keyup(function (e) {
if (e.keyCode == 13) {
//ajax request
$.ajax({
url: "pincode_check.php",
data: {
'pincode' : $('#pincode').val()
},
dataType: 'json',
success: function(data) { <!--console.log(data.success);-->
if(data.success){
//console.log(data.results[0].formatted_address.split(','))
var long_address=data.results[0].formatted_address.split(',');
console.log(long_address[0]);
$('#section1').append(long_address[0]);
}
}
});
}
});
});
</script>
PHP CODE(pincode_check.php):
<?php
$pincode=$_REQUEST['pincode'];
$geocode=file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$pincode.'&sensor=false');
$response= json_decode($geocode); //Store values in variable
$lat = $response->results[0]->geometry->location->lat; //Returns Latitude
$long = $response->results[0]->geometry->location->lng; // Returns Longitude
$geocode=file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng='.$lat.','.$long.'&sensor=false');
$data= json_decode($geocode);
if($data==true)
{ // Check if address is available or not
$data->results[0]->formatted_address ;
$data->success=true;
echo json_encode($data);
}
else {
$data->success= false;
echo json_encode($data);
}
?>
The default content type in $.ajax is application/x-www-form-urlencoded. But you've set your form content to multipart/form-data.
multipart/form-data is normally used for sending files with POST. I don't think you need that, so you don't need to specify enctype at all, just remove it and use the default form encoding, which is application/x-www-form-urlencoded.
(Additionally, the default request type in $.ajax is GET, so if you do want to send a file, you'll need to change that too..as well as add the attribute type="file" to your form I believe...)

Jquery validate and submit more forms on one page

So I am dealing with some survey pages. First my makesurvey.php reads all questions and then create page for editing questions and creating new questions. Each question is in own form and it has own submit. Then admin of survey can on page makessurvey.php fix the existing questions and also can add new question which is subbmited to handlesurvey.php wich makes updates to database. That means on one page I have let's say 20 forms with submit button. Now I realise that I have encountered more problems. The survey will be handle only by one admin. And this survey apllication needs to work dynamic, because admin can enter some new question, later can delete some questions. After some time add new questions, then delete and so on.
PROBLEMS:
1.Problem: On page makesurvey when admin wants to edit survey how to make just one jQuery function, which will first validate then submmit form to handlesurvey.php. (admin will edit one question at time and press submit). The other option is to generate so many js functions for each form but I think that isn't appropriaty way, but I think it would work fine.
2.Problem: When admin adds/edits some question how should my handlesurvey.php know which variable is in $_POST[<some_variable>].
Generated makesurvey.php page:
<script type="text/javascript">
$("form#updateQuestion").submit(function(){
var SloQuestion = $("#SloQuestion").val();
var typeQuestion=$('#typeQuestion').val();
var RadioValue1=$('#RadioValue1').val();
var RadioValue2=$('#RadioValue2').val();
var RadioValue3=$('#RadioValue3').val();
var RadioValue4=$('#RadioValue4').val();
//HERE I WILL DO SOME VALIDATION
/* $.post( "editSurveyHandle.php", $("form#updateQuestion").serialize())
.done(function( data ) {
alert("You have changed question!");
/* });
return false;*/
});
</script>
</head>
<html>
<body>
<form id='updateQuestion1' name='updateQuestion1' method='post' action=''>
<input type='hidden' name='hidden' value='question1'/><table width='600px'><tr></tr>
<tr><td width='50%' valign='top'><label for='question1'><h2>CURRENT QUESTION: </h2></label></td></tr>
<tr><td>SLOVENIAN </td><td width='50%' valign='top'> <label for='question1'>Some question 1 *</label></td></tr>
<tr><td width='50%' valign='top'>TYPE QUESTION</td><td width='50%' valign='top'>RADIO BUTTON</td></tr>
<tr><td><h4>DELETE QUESTION</h4></td><td><input type='checkbox' id='deleteQuestion' name='deleteQuestion' value='delete'/></td></tr>
<tr><td><h4>CHANGE QUESTIOn</h4></td></tr>
<tr><td><label>SLOVENIAN</label></td><td><input type='text' id='SloQuestion' name='SloQuestion' size='50' value ='Velikost sobe *'></td></tr>
<tr><td>TYPE QUESTION </td><td><select id='typeQuestion' name='typeQuestion'>
<option value='text'>Malo vnosno polje</option>
<option value='textarea'>Textarea</option>
<option selected='selected' value='radio'>Izbirino polje</option>
</select></tr>
<tr><td></td><td><input type='text' id='RadioValue0' name='RadioValue10' size='50' value ='Bad'></td></tr>
<tr><td></td><td><input type='text' id='RadioValue1' name='RadioValue11' size='50' value ='Sufficiently'></td></tr>
<tr><td></td><td><input type='text' id='RadioValue2' name='RadioValue12' size='50' value ='Dobro'></td></tr>
<tr><td></td><td><input type='text' id='RadioValue3' name='RadioValue13' size='50' value ='Excelent'></td></tr>
<tr><td></td><td><input type ='submit' id='submit' name='submit' value='Izvedi spremembe'/></td></tr>
</table>
</form>
<form id='updateQuestion2' name='updateQuestion2' method='post' action=''>
<input type='hidden' name='hidden' value='question2'/><table width='600px'><tr></tr>
<tr><td width='50%' valign='top'><label for='question2'><h2>CURRENT QUESTION:</h2></label></td></tr>
<tr><td>SLOVENIAN </td><td width='50%' valign='top'> <label for='question2'>Some question 2</label></td></tr>
<tr><td width='50%' valign='top'>TYPE QUESTION</td><td width='50%' valign='top'>RADIO BUTTON</td></tr>
<tr><td><h4>DELETE QUESTION</h4></td><td><input type='checkbox' id='deleteQuestion' name='deleteQuestion' value='delete'/></td></tr>
<tr><td><h4>CHANGE QUESTIOn</h4></td></tr>
<tr><td><label>SLOVENIAN</label></td>
<td><input type='text' id='SloQuestion' name='SloQuestion' size='50' value ='Some question 2'></td></tr>
<tr><td>TYPE QUESTION </td><td><select id='typeQuestion' name='typeQuestion'><option value='text'>Text field</option>
<option value='textarea'>Textarea</option><option selected='selected' value='radio'>Radio</option></select></tr>
<tr><td></td><td><input type='text' id='RadioValue0' name='RadioValue10' size='50' value ='Bad'></td></tr>
<tr><td></td><td><input type='text' id='RadioValue1' name='RadioValue11' size='50' value ='Sufficiently'></td></tr>
<tr><td></td><td><input type='text' id='RadioValue2' name='RadioValue12' size='50' value ='Dobro'></td></tr>
<tr><td></td><td><input type='text' id='RadioValue3' name='RadioValue13' size='50' value ='Excelent'></td></tr>
<tr><td></td><td><input type ='submit' id='submit' name='submit' value='Izvedi spremembe'/></td></tr>
</table>
</form>
Still editSurvey.php page (I have add two because I can't put all text just in one textarea)
<form id='updateQuestion3' name='updateQuestion3' method='post' action=''>
<input type='hidden' name='hidden' value='question3'/>
<table width='600px'><tr></tr>
<tr><td width='50%' valign='top'><label for='question3'><h2>CURRENT QUESTION:</h2></label></td></tr>
<tr><td>SLOVENIAN </td><td width='50%' valign='top'> <label for='question3'>Some question 3</label></td></tr>
<tr><td width='50%' valign='top'>TYPE QUESTION</td><td width='50%' valign='top'>RADIO BUTTON</td></tr>
<tr><td><h4>DELETE QUESTION</h4></td><td><input type='checkbox' id='deleteQuestion' name='deleteQuestion' value='delete'/></td></tr>
<tr><td><h4>CHANGE QUESTIOn</h4></td></tr>
<tr><td><label>SLOVENIAN</label></td><td><input type='text' id='SloQuestion' name='SloQuestion' size='50' value ='Some question 3'></td></tr>
<tr><td>TYPE QUESTION </td><td><select id='typeQuestion' name='typeQuestion'><option value='text'>Textfield</option>
TextareaRadio
And my handlesurvey.php file:
if(isset($_POST["hiddenUpdateQuestion"])){
$username = 'root';
$password='';
$hostname='localhost';
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Ni se mogoče povezati na MySQL");
$selcetedDB = mysql_select_db("amon_survey",$dbhandle);
mysql_query("set names 'utf8'");
// HERE I WILL ENTER LATER SOME QUERY
mysql_close($dbhandle);
}
In your handlesurvey.php:
if(isset($_POST["hidden"]))
{
$username = 'root';
$password='';
$hostname='localhost';
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Ni se mogoče povezati na MySQL");
$selcetedDB = mysql_select_db("amon_survey",$dbhandle);
mysql_query("set names 'utf8'");
if($_POST["hidden"]=='question1'){
//Here will be question1's query;
}
if($_POST["hidden"]=='question2'){
//Here will be question2's query;
}
}
I think it's self-explanatory, comment if something's unclear.
Edited:
Am sorry, the $_POST was getting the right values, so I assumed the jQuery did too. Please see the updated code below:
In makesurvey.php:
<script type="text/javascript">
$(document).ready(function() {
$('form').submit(function(e){
e.preventDefault();
form_id = (this.id);
var SloQuestion =$("#"+form_id+" #SloQuestion").val(); // it's basically saying to fetch the input value of the submitted form
var typeQuestion=$("#"+form_id+" #typeQuestion").val();
var RadioValue1 =$("#"+form_id+" #RadioValue1").val();
var RadioValue2 =$("#"+form_id+" #RadioValue2").val();
var RadioValue3 =$("#"+form_id+" #RadioValue3").val();
var RadioValue4 =$("#"+form_id+" #RadioValue4").val();
alert(SloQuestion);
//If custom validation:
//if(form_id='updateQuestion1')
//{//validations for #updateQuestion1}
//if(form_id='updateQuestion2')
//{//validations for #updateQuestion2}
$.post( "handlesurvey.php", $("form").serialize())
.done(function( data ) {
alert("You have changed question!");
}); });
});
</script>
Edited (2nd time):
I'm guessing as per your comment below, you need to know whether the delete question checkbox is checked or not.
You can get to know through:
var delVal = $("#"+form_id+" #deleteQuestion ").is(':checked');
alert(delVal); //returns true if checked, false if not checked
A slight correction, please change your $.post to this so that it sends only the submitted form:
$.post( "handlesurvey.php", $("#"+form_id).serialize())
.done(function( data ) {
alert("You have changed question!");
});
And on your php:
if($_POST["hidden"]=='question1'){
if(isset($_POST["deleteQuestion"]) && ($_POST["deleteQuestion"]=="delete"))
{
//Your delete query for question1
}
}
if($_POST["hidden"]=='question2'){
if(isset($_POST["deleteQuestion"]) && ($_POST["deleteQuestion"]=="delete"))
{
//Your delete query for question2
}
}
You can use some common classes let say "form" for form tag and "input" for each input, textarea or radio. Then loop on each input element validate and send data.
This should be pretty generic:
$(".form").submit(function(){
var data = [];
var valid = true;
// get data & validate
$(this).find('.input').each(function () {
if ($(this).val().length)
data[] = $(this).val();
else
valid = false;
});
if (!valid)
// set some errors
return false;
// send form data ....
});
I am not going to give you the full answer but will guide you.
Step 1: Add a class to the form:
<form id='updateQuestion1' class="sq_form" name='updateQuestion1' method='post' action=''>
</form>
<form id='updateQuestion2' class="sq_form" name='updateQuestion1' method='post' action=''>
</form>
Step 2: bind onsubmit event to the form using the class selector
$(".sq_form").submit(function(event) {
var indata = $(this).serialize(); //the form data
//do whatever validations you need to do by using using this keyword
//Example: $(this).find('input')
});

Categories