using ajax to load from a database - php

every type i run this it calls the error: OnError function and i can't see why it doesn't call the success: OnSuccess,
JS:
$(document).ready(function () {
// retreving data on button click
$("#data-submit").click(LoadDataThroughAjaxCall);
//loading screen functionality - this part is additional - start
$("#divTable").ajaxStart(OnAjaxStart);
$("#divTable").ajaxError(OnAjaxError);
$("#divTable").ajaxSuccess(OnAjaxSuccess);
$("#divTable").ajaxStop(OnAjaxStop);
$("#divTable").ajaxComplete(OnAjaxComplete);
//loading screen functionality - this part is additional - end
});
// ajax call
function LoadDataThroughAjaxCall() {
$.ajax({
type: "POST",
url: "Ajax/dataloader.php",
data: '{}',
dataType: "json",
success: OnSuccess,
failure: OnFailure,
error: OnError
});
// this avoids page refresh on button click
return false;
}
// on sucess get the xml
function OnSuccess(response) {
//debugger;
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
var tweets = xml.find("Table");
showOnATable(tweets);
}
// show data on a table
function showOnATable(tweets) {
//debugger;
var headers = [];
var rows = [];
// header section
headers.push("<tr>");
headers.push("<td><b>tweets</b></td>");
headers.push("<td><b>created</b></td>");
headers.push("<td><b>source</b></td>");
headers.push("</tr>");
// rows section
$.each(tweets, function () {
var tweets = $(this);
rows.push("<tr>");
rows.push("<td>" + $(this).find("tweet_text").text() + "</td>");
rows.push("<td>" + $(this).find("created_at").text() + "</td>");
rows.push("<td>" + $(this).find("source").text() + "</td>");
rows.push("</tr>");
});
var top = "<table class='gridtable'>";
var bottom = "</table>";
var table = top + headers.join("") + rows.join("") + bottom;
$("#divTable").empty();
$("#divTable").html(table);
}
// loading screen functionality functions - this part is additional - start
function OnAjaxStart() {
//debugger;
//alert('Starting...');
$("#divLoading").css("display", "block");
}
function OnFailure(response) {
//debugger;
alert('Failure!!!' + '<br/>' + response.reponseText);
}
function OnError(response) {
//debugger;
var errorText = response.responseText;
alert('Error!!!' + '\n\n' + errorText);
}
function OnAjaxError() {
//debugger;
alert('Error!!!');
}
function OnAjaxSuccess() {
//debugger;
//alert('Sucess!!!');
$("#divLoading").css("display", "none");
}
function OnAjaxStop() {
//debugger;
//alert('Stop!!!');
$("#divLoading").css("display", "none");
}
function OnAjaxComplete() {
//debugger;
//alert('Completed!!!');
$("#divLoading").css("display", "none");
}
PHP:
<?php
//if(isset($_POST['data'])==true&&empty($_POST['data'])==false){
require_once('../connection.php');
function clean($str)
{
if(get_magic_quotes_gpc())
{
$str= stripslashes($str);
}
return str_replace("'", "''", $str);
}
//Sanitize the POST values
//$username = clean($_POST['data']);
//$result=sqlsrv_query($conn,"execute sp_ORDER_BY_name '$username'");
$result=sqlsrv_query($conn,"select tweet_text,source from tweets");
if($result) {
if(sqlsrv_has_rows($result) > 0) {
//Login Successful
while( $row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC) ) {
echo $row['tweet_text'].", ".$row['source']."<br />";
}
}else {
//Login failed
echo 'Name not found';
}
}
//}
?>
HTML FORM:
</head>
<body>
<div id="banner">
<h1>P-CAT version 0.1</h1>
</div>
<div id ="content">
<h2>Sreach Catigroies</h2>
<select id="data2">
<option value="">Plece select one of the follwing</option>
<option value="Name">Name</option>
<option value="Location">Location</option>
</select>
<input name="data" id="data" type="text" />
<input type="submit" id="data-submit" value="Grab">
<div id="divTable">
</div>
</div>
<div id="divLoading" style="display: none; position: absolute; top: 50%; left: 40%;
text-align: left;">
<span>
<img src="Images/ajax-loader.gif" alt="Image not found." /></span>
<br />
<span style="text-align: left; padding-left: 8px;">Loading ...</span>
</div>
<div id="navbar">
<input type="button" value="EDIT">
<input type="button" value="HISTORY">
<input type="button" value="SETTINGS">
<input type="button" value="SEARCH">
</div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="js/global.js"></script>
</body>

You have to response a json from php like,
if(sqlsrv_has_rows($result) > 0) {
//Login Successful
$xml='<Table>';
while( $row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC) ) {
$xml.='<tweet_text>'.$row['tweet_text'].'</tweet_text>';
$xml.='<source>'.$row['source'].'</source>';
// create xml tag for created_at
}
$xml.='</Table>';
echo json_encode(array('d'=>$xml));
return TRUE;
} else {
//Login failed
echo json_encode(array('d'=>'Name not found'));
}

Related

Trying to post json content with button in php

I'm trying to post new data into my json file by using jquery by entering the values of the input but nothing happens when I do. I apologize in advance for this slightly dumb question and I'm very grateful for any help!
I'm very new to programming but I have no clue if this is even possible to do. Below is my 'index.php' file where my jquery and button is to add new data.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<input type="text" id="name">
<input type="text" id="grade">
<button id="btn">Add</button>
</body>
<script>
$(document).ready(function(){
$.getJSON('http://localhost/mytest/json.php', function(data) {
for (i=0; i < data.length; i++) {
if (data[i].grade < 5) {
document.write("<p style='color: red;'>Name: " + data[i].name + "<br>Grade: " + data[i].grade + "</p>");
} else {
document.write("<p style='color: green;'>Name: " + data[i].name + "<br>Grade: " + data[i].grade + "</p>");
}
}
});
// posting the orders
$('#button').on('click', function() {
var order = {
name: $('#name').val(),
grade: $('#grade').val(),
}
$.ajax({
type: 'POST',
url: 'http://localhost/mytest/json.php',
data: order,
success: function(newStudent) {
}
})
});
});
</script>
</html>
Here below is the JSON file I created with PHP (json.php):
<?php
$student1 = array(
"name"=>"ali",
"grade"=>"7"
);
$student2 = array(
"name"=>"John",
"grade"=>"4"
);
$student3 = array(
"name"=>"Martha",
"grade"=>"2"
);
$student4 = array(
"name"=>"Jullie",
"grade"=>"8"
);
$student5 = array(
"name"=>"Morgan",
"grade"=>"4"
);
$students = array($student1, $student2, $student3, $student4, $student5);
$j = json_encode($students); // we 'encode' the array into a JSON format
echo $j;
?>
Hello this is a fixed version of your code
Persisten data
Remove dumplicate code for pass grade
Create a div with students data(json content)
index.php
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
Name: <input type="text" id="name"><br>
Grade: <input type="text" id="grade"><br>
<button id="button">Add</button>
<div id="students">
</div>
</body>
<script>
$(document).ready(function () {
// fill students div content with document ready
updateStudents();
$('#button').on('click', function () {
var order = {
name: $('#name').val(),
grade: $('#grade').val(),
}
$.ajax({
type: 'POST',
url: 'json.php',
data: order,
success: function (newStudent) {
console.log("Success");
$("#students").append(setStudents($('#name').val(), $('#grade').val()));
}
})
});
function updateStudents() {
$.getJSON('students.json', function (data) {
for (i = 0; i < data.length; i++) {
$("#students").append(setStudents(data[i].name, data[i].grade));
}
});
}
function setStudents(name, grade) {
var color = 'green';
if (grade < 5) {
color = 'red';
}
return "<p style='color: " + color + ";'>Name: " + name + "<br>Grade: " + grade + "</p>"
}
});
</script>
</html>
json.php
<?php
$file = "students.json";
$content = file_get_contents($file);
if ($content == null) {
$data[] = $_POST;
$jsonData = json_encode($data);
file_put_contents($file, $jsonData);
} else {
$data = $_POST;
$tempArray = (array) json_decode($content);
array_push($tempArray, $data);
$jsonData = json_encode($tempArray);
file_put_contents($file, $jsonData);
}
echo $jsonData;
students.json
Note: the file could be empty this is just some data
[{"name":"Pedro","grade":"10"},{"name":"Juan","grade":"10"},{"name":"Lopez","grade":"10"},{"name":"Maria","grade":"5"},{"name":"Miguel","grade":"5"},{"name":"Juana","grade":"4"},{"name":"hugo","grade":"8"},{"name":"Nano","grade":"2"}]
If nothing is happening, it may be that you need to change
$('#button')
to
$('#btn')
And, no dumb questions! We're all in this together. Best of luck to you.

PHP code to insert data into mysql database is not working

I'm trying to insert data without refreshing the page using ajax and php, but the data is not getting inserted into the database.
Here is my code
<?php
require 'validation_class.php';
$obj_menufacture = new Validation_Class();
if (isset($_POST['btn'])) {
$menufacture = $obj_menufacture->menufacture_add($_POST);
}
?>
<!DOCTYPE html>
<html>
<head>
<script src='js/jquery-3.0.0.js'></script>
</head>
<body>
<div id='form_id'>
<form action='' method='post'>
<input type='text' class='m_name' name='m_name' id='m_name' onchange="names('m_name')" onkeyup="names('m_name')"/>
<span style='color:red;' id='m_name_error'></span>
<input type="submit" name='btn' value="submit" id='save'/>
</form>
</div>
<div id='cool'></div>
<style>
.border_input{
border-color:red;
}
.border_input1{
border-color:green;
}
</style>
<script>
$(document).ready(function () {
$('#save').on('click', function (e) {
e.preventDefault();
var m_name = $.trim($('#m_name').val());
var dataString = 'name='+ m_name;
if (m_name === '') {
if (m_name == '') {
$('#m_name_error').html('Please enter your name');
$('#m_name').addClass('border_input');
}
} else {
$.ajax({
url: 'validation.php',
method: 'post',
data:dataString,
success: function () {
$("#form_id").slideUp("slow");
}
});
}
});
});
function names(id) {
var val = $.trim($('#' + id).val());
if (val === '') {
$('#' + id + '_error').html('');
$('#' + id).addClass('border_input');
} else {
$('#' + id + '_error').html('');
$('#' + id).addClass('border_input1');
}
}
</script>
</body>
</html>
Here is my insert code
<?php
class Validation_Class{
public $link;
public function __construct() {
$HOST = "localhost";
$USER = "root";
$PASS = "";
$DATABASE = "store";
$this->link = mysqli_connect($HOST, $USER, $PASS, $DATABASE);
if (!$this->link) {
die('database query problem' . mysqli_error($this->link));
}
}
public function menufacture_add($data) {
$sql = "INSERT INTO menufacture(m_name)VALUES('$data[m_name]')";
if (mysqli_query($this->link, $sql)) {
$menufacture = "Menufacture insert successfully";
return $menufacture;
} else {
die('menufacruere query problem' . mysqli_error($this->link));
}
}
}
please help me what can i do to solve this
<form name="signup" id="reg" action="" method="post"enctype="multipart/form-data">
<input type='text' class='m_name' name='m_name' id='m_name' onchange="names('m_name')" onkeyup="names('m_name')"/>
<span style='color:red;' id='m_name_error'></span>
<input type="submit" name='btn' value="submit" id='save'/>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$("#save").submit(function () {
var form_data = $('#reg').serialize();
$.ajax({
type: "POST",
url: 'setting.php',
data: $('#reg').serialize(),
success: function (data) {
alert('Data save Successfully');
}, error: function () {
alert('Some Internal Error.');
}
});
});`
</script>
settting.php
<?php
include("db_connection.php"); // include connection file
if(isset($_POST)) {
$fname = $_POST['m_name'];
$insert = "INSERT INTO `table_name`(`column_name`)VALUES('".$fname."')";
$insertion = mysqli_query($conn, $insert);
}
?>
$("#save").on("click", function () {
var form_data = $('#reg').serialize();
$.ajax({
type:"POST",
url:'setting.php',
data: $('#reg').serialize(),
success: function(data){
alert("Data save Successfully");
},error: function () {
alert('Some Internal Error.');
}
});
});

How does the following code work without the proper action attribute being set?

I have a code, in a file called service.php which does as follows:
if ((!empty($_POST)) && ($_POST['action'] == 'addRunner'))
{
// Code to add entry into database
}
function fail($message)
{
die(json_encode(array('status' => 'fail', 'message' => $message)));
}
function success($message)
{
die(json_encode(array('status' => 'success', 'message' => $message)));
}
And the file to send the data via POST method using AJAX is:
$("#btnSave").click(function()
{
var data = $("#addRunner :input").serialize();
$.post($("#addRunner").attr('action'), data, function(json)
{
if(json.status == 'fail')
alert(json.message);
if(json.status == 'success')
{
alert(json.message);
clearInputs();
}
},"json");
});
The action attribute of the form #addRunner is:
<form action="service.php" id="addRunner" name="addRunner" method="POST">
<!-- Form Elements -->
</form>
Note that the action attribute for the form element is simply service.php instead of service.php?action=addRunner. However, the form still works perfectly, and successfully adds new "runner" information into the database. How does this happen?
Shouldn't the condition ($_POST['action'] == 'addRunner') fail and prevent the code to enter data into the database from running?
For the sake of completeness, the entirity of my code is as below.
My HTML is:
<!DOCTYPE html>
<html>
<head>
<title>2011 Race Finishers</title>
<link href="styles/my_style.css" rel="stylesheet">
</head>
<body>
<header>
<h2>2011 Race Finishers!</h2>
</header>
<div id="main">
<ul class="idTabs">
<li>Male Finishers</li>
<li>Female Finishers</li>
<li>All Finishers</li>
<li>Add New Finishers</li>
</ul>
<div id="male">
<h4>Male Finishers</h4>
<ul id="finishers_m"></ul>
</div>
<div id="female">
<h4>Female Finishers</h4>
<ul id="finishers_f"></ul>
</div>
<div id="all">
<h4>All Finishers</h4>
<ul id="finishers_all"></ul>
</div>
<div id="new">
<h4>Add New Finishers</h4>
<form action="service.php" id="addRunner" name="addRunner" method="POST">
First Name: <input type="text" name="txtFirstName" id="txtFirstName"> <br>
Last Name: <input type="text" name="txtLastName" id="txtLastName"> <br>
Gender: <select name="ddlGender" id="ddlGender">
<option value="">--Please Select--</option>
<option value="m">Male</option>
<option value="f">Female</option>
</select> <br>
Finish Time:
<input type="text" id="txtMinutes" name="txtMinutes" size="10" maxlength="2">
<input type="text" id="txtSeconds" name="txtSeconds" size="10" maxlength="2">
<br><br>
<button id="btnSave" type="sumbit" name="btnSave">Add Runner</button>
<input type="hidden" id="action" name="action" value="addRunner">
</form>
</div>
</div>
<footer>
<h4>Congratulations to all our finishers!</h4>
<button id="btnStart">Start Page Updates</button>
<button id="btnStop">Stop Page Updates</button>
<br>
<span id="freq"></span><br><br>
Last Updated: <div id="updatedTime"></div>
</footer>
<script src="scripts/jquery-1.6.2.min.js"></script>
<script src="scripts/my_scripts.js"></script>
<script src="scripts/jquery.idTabs.min.js"></script>
</body>
</html>
My jQuery is:
$(document).ready(function(){
var FREQ = 10000 ;
var repeat = true;
function showFrequency(){
$("#freq").html( "Page refreshes every " + FREQ/1000 + " second(s).");
}
function startAJAXcalls(){
if(repeat){
setTimeout( function() {
getDBRacers();
startAJAXcalls();
},
FREQ
);
}
}
function getXMLRacers(){
$.ajax({
url: "finishers.xml",
cache: false,
dataType: "xml",
success: function(xml){
$('#finishers_m').empty();
$('#finishers_f').empty();
$('#finishers_all').empty();
$(xml).find("runner").each(function() {
var info = '<li>Name: ' + $(this).find("fname").text() + ' ' + $(this).find("lname").text() + '. Time: ' + $(this).find("time").text() + '</li>';
if( $(this).find("gender").text() == "m" ){
$('#finishers_m').append( info );
}else if ( $(this).find("gender").text() == "f" ){
$('#finishers_f').append( info );
}else{ }
$('#finishers_all').append( info );
});
getTimeAjax();
}
});
}
function getDBRacers()
{
$.getJSON("service.php?action=getRunners", function(json)
{
if(json.runners.length > 0)
{
$('#finishers_m').empty();
$('#finishers_f').empty();
$('#finishers_all').empty();
$.each(json.runners, function()
{
var info = '<li>Name: ' + this['fname'] + ' ' + this['lname'] + '. Time: ' + this['time'] + '</li>';
if(this['gender'] == 'm')
{
$('#finishers_m').append(info);
}
else if(this['gender'] == 'f')
{
$('#finishers_f').append(info);
}
else {}
$('#finishers_all').append(info);
});
}
});
getTimeAjax();
}
function getTimeAjax(){
var time = "";
$.ajax({
url: "time.php",
cache: false,
success: function(data){
$('#updatedTime').html(data);
}
});
}
$("#btnStop").click(function(){
repeat = false;
$("#freq").html( "Updates paused." );
});
$("#btnStart").click(function(){
repeat = true;
startAJAXcalls();
showFrequency();
});
showFrequency();
getDBRacers();
startAJAXcalls();
$("#btnSave").click(function()
{
var data = $("#addRunner :input").serialize();
$.post($("#addRunner").attr('action'), data, function(json)
{
if(json.status == 'fail')
alert(json.message);
if(json.status == 'success')
{
alert(json.message);
clearInputs();
}
},"json");
});
function clearInputs()
{
$("#addRunner:input").each(function(){
$(this).val('');
});
}
$("#addRunner").submit(function() {
return false;
});
});
And finally the contents of Service.php is:
<?php
if ((!empty($_POST)) && ($_POST['action'] == 'addRunner'))
{
$fname = htmlspecialchars($_POST['txtFirstName']);
$lname = htmlspecialchars($_POST['txtLastName']);
$gender = htmlspecialchars($_POST['ddlGender']);
$minutes = htmlspecialchars($_POST['txtMinutes']);
$seconds = htmlspecialchars($_POST['txtSeconds']);
if(preg_match('/[^\w\s]/i', $fname) || preg_match('/[^\w\s]/i', $lname))
{
fail('Invalid name provided.');
}
if( empty($fname) || empty($lname) )
{
fail('Please enter a first and last name.');
}
if( empty($gender) )
{
fail('Please select a gender.');
}
if( empty($minutes) || empty($seconds) ) {
fail('Please enter minutes and seconds.');
}
$time = $minutes.":".$seconds;
$query = "INSERT INTO runners SET first_name='$fname', last_name='$lname', gender='$gender', finish_time='$time'";
$result = db_connection($query);
if ($result)
{
$msg = "Runner: ".$fname." ".$lname." added successfully" ;
success($msg);
}
else
{
fail('Insert failed.');
}
exit;
}
else if($_GET['action'] == 'getRunners')
{
$query = "SELECT first_name, last_name, gender, finish_time FROM runners ORDER BY finish_time ASC";
$result = db_connection($query);
$runners = array();
while($row = mysqli_fetch_array($result))
{
array_push($runners, array('fname' => $row['first_name'], 'lname' => $row['last_name'], 'gender' => $row['gender'], 'time' => $row['finish_time']));
}
echo json_encode(array("runners" => $runners));
exit;
}
function db_connection($query)
{
$dbc = mysqli_connect('127.0.0.1','runner_db_user','runner_db_password','race_info')
or die('Error connecting to Database');
return mysqli_query($dbc,$query);
}
function fail($message)
{
die(json_encode(array('status' => 'fail', 'message' => $message)));
}
function success($message)
{
die(json_encode(array('status' => 'success', 'message' => $message)));
}
?>
It will work reason behind this is action is value of name attribute from hidden field. It is not the action of your form tag. If you want to make it fail for testing purpose you should change the value of hidden field to something else in your form and then check again.
This is your hidden field
<input type="hidden" id="action" name="action" value="addRunner">
You can do like this for testing only
<input type="hidden" id="action" name="action" value="addRunners">
It will not satisfy this if condition
if ((!empty($_POST)) && ($_POST['action'] == 'addRunner'))

Zen Cart Echo Customers email address in my html form

I would like to have a html form added in the create_account_success page. Since zen cart has put the customers email address in the db, so I would like to echo the customers email address in this form, so customers no need to key in again. However I have tried several method still cannot echo the customers_email_address, by any chance any people can help?
<div class="centerColumn" id="createAcctSuccess">
<h1 id="createAcctSuccessHeading"><?php echo HEADING_TITLE; ?></h1>
<div id="createAcctSuccessMainContent" class="content"><?php echo TEXT_ACCOUNT_CREATED; ?></div>
<?php
if(REWARD_POINTS_NEW_ACCOUNT_REWARD!=0 && isset($RewardPoints))
if(REWARD_POINTS_NEW_ACCOUNT_REWARD>0 && GetCustomersRewardPoints($_SESSION['customer_id'])==0)
$RewardPoints->AddRewardPoints($_SESSION['customer_id'],REWARD_POINTS_NEW_ACCOUNT_REWARD);
else
if(REWARD_POINTS_NEW_ACCOUNT_REWARD<0 && GetCustomersPendingPoints($_SESSION['customer_id'])==0)
$RewardPoints->AddPendingPoints($_SESSION['customer_id'],abs(REWARD_POINTS_NEW_ACCOUNT_REWARD));
?>
<fieldset>
<legend><?php echo PRIMARY_ADDRESS_TITLE; ?></legend>
<?php
/**
* Used to loop thru and display address book entries
*/
foreach ($addressArray as $addresses) {
?>
<h3 class="addressBookDefaultName"><?php echo zen_output_string_protected($addresses['firstname'] . ' ' . $addresses['lastname']); ?></h3>
<address><?php echo zen_address_format($addresses['format_id'], $addresses['address'], true, ' ', '<br />'); ?></address>
<div class="buttonRow forward"><?php echo '' . zen_image_button(BUTTON_IMAGE_EDIT_SMALL, BUTTON_EDIT_SMALL_ALT) . ' ' . zen_image_button(BUTTON_IMAGE_DELETE, BUTTON_DELETE_ALT) . ''; ?></div>
<br class="clearBoth">
<?php
}
?>
</fieldset>
<div class="buttonRow forward"><?php echo '' . zen_image_button(BUTTON_IMAGE_CONTINUE, BUTTON_CONTINUE_ALT) . ''; ?></div>
</div>
Form
<!-- Begin MailChimp Signup Form -->
<link href="//cdn-images.mailchimp.com/embedcode/classic-081711.css" rel="stylesheet" type="text/css">
<style type="text/css">
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
</style>
<div id="mc_embed_signup">
<form action="http://c.us7.list-manage.com/subscribe/post?u=8e1a686f2e7899f845cd4208c&id=79af0d8b9f" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
<h2>Subscribe to our mailing list</h2>
<div class="indicates-required"><span class="asterisk">*</span> indicates required</div>
<div class="mc-field-group">
<label for="mce-EMAIL">Email Address <span class="asterisk">*</span>
</label>
<input type="email" value="<?php echo $customers_email_address;?>" name="EMAIL" class="required email" id="mce-EMAIL">
</div>
<div class="mc-field-group">
<label for="mce-FNAME">First Name <span class="asterisk">*</span>
</label>
<input type="text" value="" name="FNAME" class="required" id="mce-FNAME">
</div>
<div class="mc-field-group">
<label for="mce-LNAME">Last Name <span class="asterisk">*</span>
</label>
<input type="text" value="" name="LNAME" class="required" id="mce-LNAME">
</div>
<div class="mc-field-group">
<label for="mce-MMERGE4">Where did you hear about us? <span class="asterisk">*</span>
</label>
<input type="text" value="" name="MMERGE4" class="required" id="mce-MMERGE4">
</div>
<div id="mce-responses" class="clear">
<div class="response" id="mce-error-response" style="display:none"></div>
<div class="response" id="mce-success-response" style="display:none"></div>
</div> <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;"><input type="text" name="b_8e1a686f2e7899f845cd4208c_79af0d8b9f" value=""></div>
<div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
</form>
</div>
<script type="text/javascript">
var fnames = new Array();var ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';fnames[2]='LNAME';ftypes[2]='text';fnames[4]='MMERGE4';ftypes[4]='text';
try {
var jqueryLoaded=jQuery;
jqueryLoaded=true;
} catch(err) {
var jqueryLoaded=false;
}
var head= document.getElementsByTagName('head')[0];
if (!jqueryLoaded) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js';
head.appendChild(script);
if (script.readyState && script.onload!==null){
script.onreadystatechange= function () {
if (this.readyState == 'complete') mce_preload_check();
}
}
}
var err_style = '';
try{
err_style = mc_custom_error_style;
} catch(e){
err_style = '#mc_embed_signup input.mce_inline_error{border-color:#6B0505;} #mc_embed_signup div.mce_inline_error{margin: 0 0 1em 0; padding: 5px 10px; background-color:#6B0505; font-weight: bold; z-index: 1; color:#fff;}';
}
var head= document.getElementsByTagName('head')[0];
var style= document.createElement('style');
style.type= 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = err_style;
} else {
style.appendChild(document.createTextNode(err_style));
}
head.appendChild(style);
setTimeout('mce_preload_check();', 250);
var mce_preload_checks = 0;
function mce_preload_check(){
if (mce_preload_checks>40) return;
mce_preload_checks++;
try {
var jqueryLoaded=jQuery;
} catch(err) {
setTimeout('mce_preload_check();', 250);
return;
}
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://downloads.mailchimp.com/js/jquery.form-n-validate.js';
head.appendChild(script);
try {
var validatorLoaded=jQuery("#fake-form").validate({});
} catch(err) {
setTimeout('mce_preload_check();', 250);
return;
}
mce_init_form();
}
function mce_init_form(){
jQuery(document).ready( function($) {
var options = { errorClass: 'mce_inline_error', errorElement: 'div', onkeyup: function(){}, onfocusout:function(){}, onblur:function(){} };
var mce_validator = $("#mc-embedded-subscribe-form").validate(options);
$("#mc-embedded-subscribe-form").unbind('submit');//remove the validator so we can get into beforeSubmit on the ajaxform, which then calls the validator
options = { url: 'http://candles.us7.list-manage.com/subscribe/post-json?u=8e1a686f2e7899f845cd4208c&id=79af0d8b9f&c=?', type: 'GET', dataType: 'json', contentType: "application/json; charset=utf-8",
beforeSubmit: function(){
$('#mce_tmp_error_msg').remove();
$('.datefield','#mc_embed_signup').each(
function(){
var txt = 'filled';
var fields = new Array();
var i = 0;
$(':text', this).each(
function(){
fields[i] = this;
i++;
});
$(':hidden', this).each(
function(){
var bday = false;
if (fields.length == 2){
bday = true;
fields[2] = {'value':1970};//trick birthdays into having years
}
if ( fields[0].value=='MM' && fields[1].value=='DD' && (fields[2].value=='YYYY' || (bday && fields[2].value==1970) ) ){
this.value = '';
} else if ( fields[0].value=='' && fields[1].value=='' && (fields[2].value=='' || (bday && fields[2].value==1970) ) ){
this.value = '';
} else {
if (/\[day\]/.test(fields[0].name)){
this.value = fields[1].value+'/'+fields[0].value+'/'+fields[2].value;
} else {
this.value = fields[0].value+'/'+fields[1].value+'/'+fields[2].value;
}
}
});
});
$('.phonefield-us','#mc_embed_signup').each(
function(){
var fields = new Array();
var i = 0;
$(':text', this).each(
function(){
fields[i] = this;
i++;
});
$(':hidden', this).each(
function(){
if ( fields[0].value.length != 3 || fields[1].value.length!=3 || fields[2].value.length!=4 ){
this.value = '';
} else {
this.value = 'filled';
}
});
});
return mce_validator.form();
},
success: mce_success_cb
};
$('#mc-embedded-subscribe-form').ajaxForm(options);
});
}
function mce_success_cb(resp){
$('#mce-success-response').hide();
$('#mce-error-response').hide();
if (resp.result=="success"){
$('#mce-'+resp.result+'-response').show();
$('#mce-'+resp.result+'-response').html(resp.msg);
$('#mc-embedded-subscribe-form').each(function(){
this.reset();
});
} else {
var index = -1;
var msg;
try {
var parts = resp.msg.split(' - ',2);
if (parts[1]==undefined){
msg = resp.msg;
} else {
i = parseInt(parts[0]);
if (i.toString() == parts[0]){
index = parts[0];
msg = parts[1];
} else {
index = -1;
msg = resp.msg;
}
}
} catch(e){
index = -1;
msg = resp.msg;
}
try{
if (index== -1){
$('#mce-'+resp.result+'-response').show();
$('#mce-'+resp.result+'-response').html(msg);
} else {
err_id = 'mce_tmp_error_msg';
html = '<div id="'+err_id+'" style="'+err_style+'"> '+msg+'</div>';
var input_id = '#mc_embed_signup';
var f = $(input_id);
if (ftypes[index]=='address'){
input_id = '#mce-'+fnames[index]+'-addr1';
f = $(input_id).parent().parent().get(0);
} else if (ftypes[index]=='date'){
input_id = '#mce-'+fnames[index]+'-month';
f = $(input_id).parent().parent().get(0);
} else {
input_id = '#mce-'+fnames[index];
f = $().parent(input_id).get(0);
}
if (f){
$(f).append(html);
$(input_id).focus();
} else {
$('#mce-'+resp.result+'-response').show();
$('#mce-'+resp.result+'-response').html(msg);
}
}
} catch(e){
$('#mce-'+resp.result+'-response').show();
$('#mce-'+resp.result+'-response').html(msg);
}
}
}
</script>
<!--End mc_embed_signup-->
Try this:
// Query the database for customers email address by (logged in) customer's ID
$email_results = $db->Execute('SELECT customers_email_address FROM customers WHERE customers_id = ' . $_SESSION['customer_id']);
// The customer's Email Address is now in the PHP variable $email_addr
$email_addr = $email_results->fields['customers_email_address'];

adding Reset button to reset checkboxes using PHP or javascript

I need assistance in figure out the method to provide a button to reset these checkboxes.
UPDATEL: I have more information to share:
The answers provided will only work with checkboxes that are selected with that instance and not checkboxes that are enabled onLoad. This is a perferences page were people can choose genre's they like and save them.
<div class="grid_13">
<form method="post" id="updatePreferedGenres" action="/account/update/preferences/genres">
<h2 class="alt blue no-margin-top margin-bottom">Check off genres you like:</h2>
<?php
$this->load->library('GenreLib');
$genreArray = $this->genrelib->getGenreList();
foreach ($genreArray as $parentID => $genreSegment){
$isChecked = "";
if (isset($customerPrefs['genres']) && is_array($customerPrefs['genres']) && sizeof($customerPrefs['genres']) > 0 && in_array($parentID, array_keys($customerPrefs['genres']))) {
$isChecked = "CHECKED";
}
echo '<p class="grid_3 no-margins-left no-margins-right"><input type="checkbox" class="margin-right" name="' . $genreSegment['parentGenreName'] . '" value="' . $parentID . '"' . $isChecked . '/>' . $genreSegment['parentGenreName'] . '</p>';
}
?>
<div class="clear"></div>
<input type="button" class="button right" value="Save" />
<div class="clear"></div>
</form>
// Rig the preferences form
$("#updateDHOverride").submit(function(event) {
event.preventDefault();
if ( $(this).find("#downloadHubOverride").is(':checked')){
document.cookie = 'downloadHubOverride=TRUE; expires=Thursday, 25-Jul-2030 23:59:59 GMT; path=/';
}
else {
document.cookie = 'downloadHubOverride=FALSE; expires=Thursday, 25-Jul-2030 23:59:59 GMT; path=/';
}
});
// Rig the submit for genre preferences form
$("#updatePreferedGenres").each(function() {
var linkedForm = $(this);
$(this).find("#prefSave").click( function(event) {
event.preventDefault();
var getGenreIds = "";
linkedForm.find("input[type=checkbox]").each( function() {
if ( $(this).is(":checked") ) {
if ( getGenreIds.length > 0) {
getGenreIds += ',' + $(this).attr('value');
}
else {
getGenreIds += $(this).attr('value');
}
}
});
$.post(
linkedForm.attr('action'),
{ genreIds : getGenreIds },
function (status) {
status = $.parseJSON(status);
if ( status.status == "success" ) {
$.prompt('<h4>Preferences updated successfully!</h4>', {
top: '34%',
zIndex: '10000'
});
if ( linkedForm.hasClass('goHome') ) window.location = "/";
}
else {
$.prompt('<h4>' + status.message + '</h4>', {
top: '34%',
zIndex: '10000'
});
}
}
);
});
});
// REMOVE checkboxes Script - need to place into onClick Function
// $('input:checkbox').removeAttr('checked');
$('#activateAccount').submit( function(event) {
event.preventDefault();
// update form update action
$.post(
$(this).attr('action'),
$(this).serialize(),
function (status) {
//console.log(status);
status = $.parseJSON(status);
if ( status.status == "success" ) {
$.prompt('<h4>Account updated successfully!</h4>', {
top: '34%',
zIndex: '10000',
buttons: { OK:true },
submit: function(v,m,f){
location.reload(true);
}
});
}
else {
if ( status.data != "" ) {
//if there are form validation errors
displayValidation(status.data);
}
else {
//generic error message
$.prompt('<h4>' + status.message + '</h4>', {
top: '34%',
zIndex: '10000'
});
}
}
}
);
});
I have a basic Idea of what needs to happen, I'm just not sure on the syntax.
since you seem to only have checkboxes :
<input type='reset' value='resetButton'>
No need for PHP, nor Javascript:
<input type="reset" value="Reset checkboxes" />

Categories