I'm currently building a system using ExpressionEngine that allows users to answer questions in exchange for points, they can then use these points to claim prizes.
I've been writing the functionality to claim a prize, it needs to do the following:
Check the prize is in stock
Check the user has enough points
If in stock and enough points submit a form which lets the admin know to send the prize out
I have the following code which I think is nearly there however I'm struggling with the last bit, the actual success/failure parts. I've used jQuery Ajax:
<script type="text/javascript">
$(function() {
$("#prizeClaim").submit(function() {
var data = "entry_id={entry_id}&member_id={logged_in_member_id}&prize_title={title}&prize_points={prize_points}";
$.ajax({
url: "/prizes/prize_validation/",
data: data,
success: function(html) {
alert(html); // alert the output from the PHP Script
}
});
return false;
});
});
</script>
This code currently just outputs the html of prize_validation in an alert, this is the code used on the validation page so far:
<?php
// All data required made into vars
$entry_id = ($_GET['entry_id']);
$member_id = ($_GET['member_id']);
$prize_title = ($_GET['prize_title']);
$prize_points = ($_GET['prize_points']);
// Select the stock column
$query = ee()->db->query("SELECT field_id_6 FROM exp_channel_data WHERE entry_id = $entry_id");
if ($query->num_rows() > 0)
{
foreach($query->result_array() as $row)
{
// define stock_total
$stock_total = $row['field_id_6'];
// If stock more than 0 go ahead
if($stock_total > 0) {
//remove 1 stock item
ee()->db->query("UPDATE exp_channel_data SET field_id_6 = field_id_6 - 1 WHERE entry_id = $entry_id");
//update users points
$data = array('member_id' => $member_id, 'prize_points' => $prize_points, 'prize_id' => $entry_id);
$sql = ee()->db->insert_string('exp_rmdy_member_prize_data', $data);
ee()->db->query($sql);
}
}
}
?>
{exp:freeform:form form_id="1" return="thanks"}
<input type="hidden" name="name" value="{username}" id="freeform_name" maxlength="150">
<input type="hidden" name="email" value="{email}" id="freeform_email" maxlength="150">
<input type="hidden" name="company" value="{exp:channel:entries channel='company' dynamic='no'}{if {member_code} == {company_code}}{title}: {company_address}{/if}{/exp:channel:entries}" id="freeform_company" maxlength="200">
<input type="hidden" name="prize" value="<?php echo $prize_title ?>" id="freeform_prize" maxlength="150">
<p><input type='submit' name='submit' value='Process order'></p>
{/exp:freeform:form}
This code checks the stock and if the item is in stock it then removes the amount of points from the users total points, this works. However once this has happened I want to submit the Freeform, I'm not 100% sure if this should be within the prize_validation file or in a third location. But after lots of experimentation I'm still not sure how to go about either!
Any hints/tips much appreciated!
Pjacks answer in the above comment helped me fix this.
Do you want to use ajax to submit or a normal form submit. This should submit the form if you put $("#freeform").submit(); in your call back instead of the alert. Thats assuming the id of your form is called freeform. If you want to do ajax, it's done a bit differently.
Related
I've been searching for this kind of problem and I couldn't find one. I am using ajax to solve this problem but it didn't work out. I really want to have this scenario where after the user scanned his/her QR code, its data (account ID) will be in the input field. Then the other input field will automatically show its corresponding data from the database based on the data from QR code. This is so far my code.
This is from the main page:
<label id="acc">Account ID
<input type="text" name="accId" id="accID" class="idnum" required="" value="">
</label>
<label id="label">QR ID
<input type="text" readonly=" " name="qrId" id="qrId" style="width: 108px;margin-right: 15px;" value="" >
</label>
Ajax:
<script>
$("#accID").change(function() {
var accID = $(this).val();
$.ajax({
url: 'loadata.php',
type: 'POST',
data: 'accID='+accID,
success: function(html) {
$("#qrId").html(html);
}
});
});
</script>
this is the loadata.php:
<?php
session_start();
include ('connection.php');
if(isset($_POST['accID']))
{
$accID = $_POST['accID'];
$sel = "SELECT * FROM qrcode WHERE Cus_IDNum = '$accID'";
$sel_run = $conn->query($sel);
if($sel_run->num_rows>0)
{
while($rows = $sel_run->fetch_assoc())
{
?>
<input type="text" readonly=" "id="qrId" name="qrId" style="width: 108px;margin-right: 15px;" value="" >
<?php
}
}
}
?>
Thank you very much for your time! :)
Are you getting any data to return? Have you tried changing your input field in loadata.php to a div with the same ID? Right now you're trying to place an input within an input.
Also, you don't need to wrap your inputs within the label. As long as the label and input share the same ID, they will always be together. Currently, you are not doing that.
Setting $("#qrId").html(html); will do nothing, as #qrId is an input field. I think, what you want to do is to set the value of the input field.
This should work like this: $("#qrId").val(html);
Then, there is a second problem as your PHP script returns HTML of an input field rather than just the value to set. Also, it may return multiple values as you loop through the database results.
You could try to change your script to something like this to just return the value of the first selected database record. Replace qrCodeValue with the real column name to use:
<?php
session_start();
include ('connection.php');
if(isset($_POST['accID']))
{
$accID = $_POST['accID'];
$sel = "SELECT * FROM qrcode WHERE Cus_IDNum = '$accID'";
$sel_run = $conn->query($sel);
if($sel_run->num_rows>0)
{
$row = $sel_run->fetch_assoc();
print $row['qrCodeValue'];
exit;
}
}
?>
I've been a lurker for some time, but this is my first post (and motivated me to sign up), I've searched countless posts, but can't find a solution that best works. This is part of a project where users search a database and have the option to add returned results to a saved location (posting the id, resid, to a separate mysql table).
The search function is in a separate php file, the relevant parts of the code are below (I've stripped out a lot of the formatting):
// Output HTML formats
$html ='<tr >
<form id="myForm" method="post">
<input type="hidden" id="resid" name="resid" value="ther3sidd">
<input type="hidden" id="lesid" name="lesid" value="liD1">
<input type="button" id="submitFormData" onclick="SubmitFormData()" value="Submit" />
</form>
</tr>';
The values "ther3sidd" and "liD1" get replaced with values unique to the item returned by the search, and are numerical values. There will also be multiple of the forms returned on the user facing page all with the same id of myForm (but different lesid and resid).
The search results are outputted to the page the user is on and a button can be pressed to add the result to a mysql table using the script below (stored in the page the user is on).
function SubmitFormData() {
var lesid = $('input[name="lesid"]').val();
var resid = $('input[name="resid"]').val();
var dataString = {lesid: lesid, resid: resid}
$.ajax({
type: "POST",
url: 'lesresadd.php',
data: dataString,
})}
Below is the php file lesresadd.php (without the connection info)
$lessonid = $_POST['lesid'];
$resourceid = $_POST['resid'];
$sql = "INSERT INTO lessons_resources (lesson_id, resource_id)
VALUES ('$lessonid', '$resourceid')";
$result = $conn->query($sql)
The code works fine and can submit data to the mysql table, however, the main issue is that the values for resid and lesid are for the first result from the search function (and not the one selected with the button click). I know that I need to use 'this' somewhere on the variable, however, I am not sure of the correct syntax. For example, I have tried the following (and many variants on it):
var lesid = $this().('input[name="lesid"]').val();
But this does not work. Maybe, there is more I need to do to the code, and it isn't as simple as just adding 'this' somewhere. I am reasonably new to AJAX and entirely self taught from visiting sites just like stack overflow. Any advice would be greatly appreciated.
It's not the neatest solution, but here goes:
$html = "";
$i = 1;
while($r = mysql_fetch_object($res))
{
$html .='<tr>
<input type="hidden" id="resid'.$i.'" name="resid" value="ther3sidd">
<input type="hidden" id="lesid'.$i.'" name="lesid" value="liD1">
<input type="button" class="submitFormData" onclick="SubmitFormData('.$i.')" value="Submit" />
</tr>';
$i++;
}
Then in your JavaScript:
function SubmitFormData(id) {
var lesid = $('#lesid'+id).val();
var resid = $('#resid'+id).val();
var dataString = {lesid: lesid, resid: resid}
$.ajax({
type: "POST",
url: 'lesresadd.php',
data: dataString,
})}
I have a page with a select list (gets successfully populated from mysql) and a text box. The text box has to be populated with a value from mysql based on the item selected in the list. But the ajax call to php is not working and i can not figure out what the issue is. I am just learning ajax and php, so a novice.. Please help. i am stuck with this for a long time.
<script>
$(document).ready(function() {
$('.selectpicker').on("change", function(){
var selected_data = $(this).find("option:selected").val();
alert(selected_data);
$.ajax ({
type: "POST",
data: { selected_data: selected_data },
url: "getoldcharity.php",
dataType: "json",
success: function(res) {
$('#charity_new').val(data.charity_new);
}
});
});
});
</script>
<form id="assign-fundraiser_form" class="form-horizontal" action="" method="post">
<div class="form-group">
<div class="col-md-3">
<select class="selectpicker form-control" id="fundraiser" name="fundraiser" required>
<option value="" selected disabled>Select a Fundraiser</option>
<?php
include('session.php');
$result1 = mysqli_query($db,"select concat(f_firstname,' ',f_lastname) fundraiser from fundraiser where f_company in (select contractor_name from contractor where company_name = '$_SESSION[login_user]') and f_status = 'Active' order by concat(f_firstname,' ',f_lastname)");
while ($rows = mysqli_fetch_array($result1))
{
echo "<option>" .$rows[fundraiser]. "</option>";
}
?>
</select>
</div>
</div>
<input type="text" name="charity" id="charity_new" />
</form>
<?php
include "session.php";
if (ISSET($_POST['.selectpicker'])) {
$ref = $_POST['.selectpicker'];
$query = $db->query("select f_charity charity_new from fundraiser limit 1");
$row = $query->fetch_assoc();
$charity_new = $row['charity_new'];
$json = array('charity_new' => $charity_new);
echo json_encode($json);
}
$db->close();
?>
There are a few problems that I've spotted from quick glance, so I've separated them below.
PHP
In your AJAX request, you are using data: { selected_data: selected_data } which means the PHP code will be expecting a POSTed key named selected_data but you're looking for .selectpicker. You seem to have mixed up a couple of things, so instead of:
$_POST['.selectpicker']
it should be:
$_POST['selected_data']
JavaScript
As Ravi pointed out in his answer, you also need to change your success function. The parameter passed through to this function is res not data, so instead of:
$('#charity_new').val(data.charity_new);
it should be:
$('#charity_new').val(res.charity_new);
MySQL
It also appears as though your query itself is invalid - you seem to be missing a comma in the column selection.
select f_charity charity_new from fundraiser limit 1
should be:
select f_charity, charity_new from fundraiser limit 1
or, seeing as you're not using the f_charity column in the results anyway:
select charity_new from fundraiser limit 1
You aren't using the value that is being POSTed either, meaning that whatever option is selected in the dropdown makes no difference to the query itself - it will always return the first record in the database.
Other
One other thing to be aware of is you're using a class selector on your change function. This means if you have multiple dropdowns with the same class name in your HTML, they will all be calling the same AJAX function and updating the textbox. I don't know if this is what you're aiming for, but from your code posted, you only have one dropdown in the form. If you only want that one dropdown to be calling the AJAX function, you should use an ID selector instead:
$('#fundraiser').on("change", function() {
// ...
}
I think, it should be
$('#charity_new').val(res.charity_new);
instead of
$('#charity_new').val(data.charity_new);
I've got an HTML form that uses jQuery serialize method and ajax to post results using PHP into a sqlite database. I've set the jQuery to run every minute to act as an autosave feature so users can return later to finish what they started. Because of the autosave, I can't force all inputs be required.
It works 99% of the time. However, in a few cases, the application sometimes posts blank data to the database even though there is data in the input fields. I've checked to make sure all the HTML input fields have name attributes. Any ideas why it works most of the time but in a few random cases, it doesn't?
I wish I had more to report why it doesn't work all the time. I haven't been able to replicate the bug myself, I'm just going on reports of users. But I know the form is posting blanks into the database because when I go into the database, it says " " instead of "null". So I know the database is receiving something, but it isn't receiving the data the user typed.
HTML
<form action="" method="post" id="evaluationForm">
<!-- this input is disabled since this user can't edit it -->
<label for="FirstName">First Name</label>
<input type="text" name="FirstName" value="<?php echo htmlspecialchars($data['FirstName']);?>" disabled >
<label for="WorkHabitsCommentsSuper">Comments </label><br>
<textarea name="WorkHabitsCommentsSuper" placeholder="Comments are optional">
<?php echo htmlspecialchars($data['WorkHabitsCommentsSuper']);?>
</textarea>
<label for="GoalsSuper">More Comments</label>
<textarea name="GoalsSuper" required>
<?php echo htmlspecialchars($data['GoalsSuper']);?>
</textarea>
<!-- and a whole bunch more fields but you get the idea -->
</form>
JavaScript
function saveEval() {
var datastring = $("form").serialize();
$.ajax({
type: "POST",
url: "autosave-s.php",
data: datastring,
success: function(text) {
if (text == "success") {
alert('It saved. Hooray!');
} else {
alert('Oh no. Something went wrong.');
}
}
});
}
window.onload = function() {
setInterval("saveEval()", 60000)
}
PHP
$db = new PDO('sqlite:evals.sqlite');
$sql = "UPDATE table SET
WorkHabitsCommentsSuper = :WorkHabitsCommentsSuper,
GoalsSuper = :GoalsSuper";
$query = $db->prepare($sql);
$query->execute(array(
':WorkHabitsCommentsSuper' => $_POST['WorkHabitsCommentsSuper'],
':GoalsSuper' => $_POST['GoalsSuper']
));
echo "success";
if(!in_array("",$_POST)){
$db = new PDO('sqlite:evals.sqlite');
$sql = "UPDATE table SET
WorkHabitsCommentsSuper = :WorkHabitsCommentsSuper,
GoalsSuper = :GoalsSuper";
$query = $db->prepare($sql);
$query->execute(array(
':WorkHabitsCommentsSuper' => $_POST['WorkHabitsCommentsSuper'],
':GoalsSuper' => $_POST['GoalsSuper']
));
echo "success";
}else{
echo "Empty";
}
This will check if the posting data is not empty if empty any of the field it will not update and will send 'Empty' response so alert on empty data posting.
Been struggling with this for a couple days now. Here's the set up - I have a parent page "support.php" there are tabs, and when you click a tab it brings in the appropriate form via ajax.
(the relevant code for each section:)
form input's on the AJAX page
<input type="text" class="numbers" name="captchaImage" id="SupportNumbers" size="6" value="" readonly>
<input type="text" class="numbers" name="SupportMath" id="SupportMath" size="6" maxlength="6" tabindex="9">
The parent page - support.php calls for "validation.js" which is my jQuery.validate script.
...
SupportMath: {
required: true,
equal: "<?php echo $randomNumTotal; ?>"
}
There is a .get command on the parent page for a file "random.php"
$.get('PHP/random.php', function (data){
$("#SupportNumbers").val(data);
});
<?php
$randomNum = rand(0,9);
$randomNum2 = rand(0,9);
echo $randomNum ."+". $randomNum2;
$randomNumTotal = $randomNum + $randomNum2;
?>
which generates two random numbers so you can add them together. The validation checks to make sure
the two numbers that are generated are added correctly. I just can't seem to get all these pieces to use the same numbers, i can get the text box "SupportNumbers" to populate with two random numbers say "2 + 5" but when I enter "7" into "#SupportMath" it displays the error msg. It should be $randomNumTotal but I can't get that to the page, and have the validation script check against that.
HELP.
I realize this is clear as mud so ill try and explain more
I have 5 forms on my support page. To reduce the chaos, I have them in a vertical tab set. I don't want my js validation script on the page and I don't want all 5 forms hidden/displayed on the page due to some issues we've had with some bots. So my solution was to bring in the forms with AJAX (done) and just link to the validation script (done) all is good except for our "random math captcha" I can put it in a file and use the ".get" command to populate the box that holds the two random math questions, but can't get the answer to validate. Hope this helps, code below.
EXPLANATION: ( step by step )
we use your method to generate two random number from 1 to 9 at page load
we have added an extra input <input type="hidden" name="math" id="math"/> this field is needed since you are using a readonly field, now the readonly fields are not submitted...by forms, this way we have the one shown to user and another one hidden, this one will be submitted;
we get the #math value that is a string ex: 5+2 so we need to transform this into two int and sum it.
finally we make the check the SUM against the user input #SupportMath
DEMO: https://so.lucafilosofi.com/php-jquery-validation/
PHP ( that check the match against... )
if ( isset($_POST['post']) ) {
$math = explode('+',trim($_POST['math']));
$sum = ( (int)$math[0] + (int)$math[1] );
$message = 'error';
if ( (int)$sum === (int)$_POST['SupportMath'] ) {
$message = 'success';
}
echo $message;
}
jQuery ( pseudo code...)
$(function() {
$.get('random.php',function(data) {
$("#SupportNumbers,#math").val(data);
});
$('#form').submit(function(e) {
e.preventDefault();
var query = $(this).serialize();
$.ajax({
type: "POST",
url: "post.php",
data: "post=post&" + query,
success: function(msg) {
if (msg.indexOf('success') == -1) {
alert('error');
} else {
alert('cURL');
}
}
});
});
});
HTML
<input type="text" class="numbers" name="captchaImage" id="SupportNumbers" size="6" readonly>
<input type="hidden" name="math" id="math"/>
<input type="text" class="numbers" name="SupportMath" id="SupportMath" size="6" maxlength="6" tabindex="9">
Here's a self-sufficient version of what I was referring to.
<?php
session_start();
if (isset($_GET['validate']))
{
$passed = (session_is_registered('validate') && (int)$_GET['validate'] == $_SESSION['validate']);
header('Content-Type: application/json');
echo sprintf('{"validation":"%s"}', $passed?'OK':'FAIL');
exit;
}
function generate_check()
{
// generate a result (incompleted)
$result = Array(
'num1' => rand(0,10), // first random number
'num2' => rand(0,10), // second random number
'problem' => null, // actual math problem
'answer' => null // the answer
);
// random method
switch (rand(0,999) % 3)
{
case 0: // addition
$result['problem'] = sprintf('%d + %d',$result['num1'],$result['num2']);
$result['answer'] = $result['num1'] + $result['num2'];
break;
case 1: // subtraction
$result['problem'] = sprintf('%d - %d',$result['num1'],$result['num2']);
$result['answer'] = $result['num1'] - $result['num2'];
break;
case 2: // multiplication
$result['problem'] = sprintf('%d * %d',$result['num1'],$result['num2']);
$result['answer'] = $result['num1'] * $result['num2'];
break;
}
return $result;
}
$check = generate_check();
session_register('validate');
$_SESSION['validate'] = $check['answer'];
?>
<html>
<head>
<title>Sample Validation</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<Script type="text/javascript">
$(function(){
$('#check').click(function(){
$('#result').css('color','').text('Checking...');
$.getJSON('<?php echo $_SERVER['PHP_SELF']; ?>',{'validate':$('#answer').val(),'_':(new Date()).toString()},function(data){
if (data.validation=='OK')
$('#result').css('color','green').text('PASSED!');
else
$('#result').css('color','red').text('FAILED!');
});
});
});
</script>
</head>
<body>
<p>What is <b><?php echo $check['problem']; ?></b>?</p>
<input type="text" name="answer" id="answer" /><input id="check" type="button" value="Check" />
<p id="result"></p>
<br /><br />
<form action="<?php echo $_SERVER['PHP_SELF']; ?>"><input type="submit" value="New problem" /></form>
</body>
</html>
I used to do pages like this until I found this wonderful inline Jquery validator You simply add a class with relevant information to your form objects and it does the rest. There's no need to fool around with redirecting or sessions for that matter. I've had it in production on about 25 sites for nearly a year without any issues whatsoever.
Edit: looks like you're trying to do a Captcha of sorts, maybe? Perhaps look at ReCaptcha which not only verifies a user is correct, but also helps improve OCR. Alternatively, you could do a slidelock
As we say in my shop, "No reason to go off and write a minivan...."