My form on wordpress page doesn't execute - php

I have a page made on wordpress with edited by me custom theme.
I've tried to make my own form using ajax without any plugin.
The problem is that I don't have any errors etc. and form still doesn't do anything (just reloads page). I did everything like on tutorial page and still don't know what to do. I figured out that php code doesn't execute. As you can see there are input conditions that doesn't execute :/
This is what i have done so far:
html:
<section id="contact_content">
<form name="contact_me" action="" method="post">
<?php if( get_field('contact_header') ): ?>
<div id="contact_header"><?php the_field('contact_header'); ?></div>
<?php endif; ?>
<input type="text" name="form_name" placeholder="<?php the_field('contact_name'); ?>" id="contact_name"> <br />
<input type="number" name="form_phone_number" placeholder="<?php the_field('contact_phone'); ?>" id="contact_phone"> <br />
<input type="email" name="form_email" placeholder="<?php the_field('contact_mail'); ?>" id="contact_mail"> <br />
<input type="text" name="form_comment" placeholder="<?php the_field('contact_message'); ?>" id="contact_message" style="height: 190px;"><br />
<input type="hidden" name="action" value="send_form" style="display: none; visibility: hidden; opacity: 0;">
<button type="submit" id="contact_button">wyślij</button>
</form>
</section>
function.php
function javascript_variables(){ ?>
<script type="text/javascript">
let ajax_url = '<?php echo admin_url( "admin-ajax.php" ); ?>';
let ajax_nonce = '<?php echo wp_create_nonce( "secure_nonce_name" ); ?>';
//form AJAX validation
$( 'form[name="contact_me"]' ).on( 'submit', function() {
let form_data = $( this ).serializeArray();
form_data.push( { "name" : "security", "value" : ajax_nonce } );
$.ajax({
url : ajax_url,
type : 'post',
data : form_data,
success : function( response ) {
console.log( response );
},
fail : function( err ) {
console.log( "Błąd: " + err );
}
});
return false;
});
</script><?php
}
add_action ( 'wp_head', 'javascript_variables' );
add_action('wp_ajax_send_form', 'send_form');
add_action('wp_ajax_nopriv_send_form', 'send_form');
function send_form(){
check_ajax_referer( 'secure-nonce-name', 'security' );
if ( empty( $_POST["form_name"] ) ) {
echo "Wprowadź imię i nazwisko.";
wp_die();
}
if ( ! filter_var( $_POST["form_email"], FILTER_VALIDATE_EMAIL ) ) {
echo "Wprowadź poprawny adres e-mail.";
wp_die();
}
if ( empty( $_POST["form_comment"] ) ) {
echo "Wprowadź wiadomość.";
wp_die();
}
if ( empty($_POST["form_phone_number"] ) ) {
echo 'Wprowadź numer telefonu';
wp_die();
}
$to = 'dawidt9882#gmail.com';
$subject = 'Now message from a client!';
$body = 'From: ' . $_POST['form_name'] . '\n';
$body .= 'Number: ' . $_POST['form_phone_number'] . '\n';
$body .= 'Email: ' . $_POST['form_email'] . '\n';
$body .= 'Message: ' . $_POST['form_comment'] . '\n';
$headers = array('Content-Type: text/html; charset=UTF-8');
wp_mail( $to, $subject, $body, $headers );
echo 'Wiadomość została wysłana! ;p';
wp_die();
}
Any ideas? :c

Try this:
$( 'form[name="contact_me"]' ).on( 'submit', function(ev) {
ev.preventDefault();
let form_data = $( this ).serializeArray();
form_data.push( { "name" : "security", "value" : ajax_nonce, "action" : "send_form" } );
$.ajax({
url : ajax_url,
type : 'post',
data : form_data,
success : function( response ) {
console.log( response );
},
fail : function( err ) {
console.log( "Błąd: " + err );
}
});
return false;
});

So now js looks like this:
let ajax_url = '<?php echo admin_url( "admin-ajax.php" ); ?>';
let ajax_nonce = '<?php echo wp_create_nonce( "secure_nonce_name" ); ?>';
//form AJAX validation
$( '#contact_button' ).on( 'click', function(ev) {
ev.preventDefault();
let form_data = $( this ).serializeArray();
form_data.push( { "name" : "security", "value" : ajax_nonce, "action" : "send_form" } );
$.ajax({
url : ajax_url,
type : 'post',
data : form_data,
success : function( response ) {
console.log( response );
},
fail : function( err ) {
console.log( "Błąd: " + err );
}
});
return false;
});
</script><?php
And it still does nothing. :/ If i made a mistake please dissuade me of any notion.

Related

Problem with inserting data to custom table using ajax in wordpress plugin

I am trying to insert data in custom table in wordpress while creating plugin using AJAX. But I failed to do.
here is the code of contact.php where I register scripts
add_action('wp_enqueue_scripts', 'setting_up_scripts_contact_form_wp');
function setting_up_scripts_contact_form_wp() {
wp_register_style( 'contact-custom-style',plugins_url('public/css/style.css', __FILE__) );
wp_enqueue_style( 'contact-custom-style');
wp_enqueue_script( 'cfajax-con', plugins_url('includes/submit-form.js', __FILE__),array(),false,true );
// wp_enqueue_script( 'wpforajax_con_test', plugins_url('public/js/test.js', __FILE__) );
// wp_register_script('wpforajax_con_test', plugin_dir_url(__FILE__) . 'test.js', true);
wp_localize_script(
'jsforcon-frontend-js',
'jsforcon_globals',
[
'ajax_url' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'jsforcon_insert_nonce' )
]
);
}
contact form is
<div class="container">
<div class="row display_big justify-content-center">Contact Us</div>
<div class="row justify-content-center">
<div class="col-md-6 ">
<form>
<input type="text" id="conName" class="txt_trans txt_full " name="conName" placeholder="Name" required><br><br>
<input type="text" id="conMail" name="conMail" class="txt_trans txt_full" placeholder="Mail" required><br><br>
<small id="emailHelp" class="form-text text-muted p-0 m-0">We takes your mail id for sending reply to you.</small>
<textarea id="conContant" class="txt_a_trans txt_full " name="conContant"cols="30" rows="10" placeholder="content" required></textarea>
<div class="con_error_msg"></div>
<button type="button" class="btn_submit" id="saveContact" value="load data" >Contact Us</button><br><br><br><br>
</form>
</div> </div></div>
<?php echo "<script type='text/javascript'>var ajaxurl = '".admin_url('admin-ajax.php')."'</script>"; ?>
and the insert.php file is here
<?php
function my_contact_form(){
require( dirname(__FILE__).'/wp-load.php' );
global $wpdb;
$table_name = 'wp_contact_form';
$wpdb->insert(
$table_name,
array(
'con_name' => $your_name,
'con_main' => $your_mail,
'contant' => $your_content,
'con_status' => 'unview',
'con_rep_status' => 'notReplied',
'con_date' => time()
),
array(
'%s',
'%s',
'%s',
'%s',
'%s',
'%s'
)
);
}
?>
javascript code for implementing ajax
var cf_saveContact = document.getElementById("cf_saveContact");
cf_saveContact.addEventListener('click', function() {
var conName = document.getElementById("conName").value;
var conMail = document.getElementById("conMail").value;
var conContant = document.getElementById("conContant").value;
if(conName == "" || conMail == "" || conContant == ""){
document.querySelector(".con_error_msg").innerHTML = "<p style='color:red'>all fields are required</p>";
}else{
var action = "jsforcon-insert";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET",jsforwp_globals.ajax_url+"?action="+action+"&_ajax_nonce="+jsforcon_globals.nonce+"&name="+conName+"&mail="+conMail+"&content="+conContant,true);
xmlhttp.send();
xmlhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
conName = document.getElementById("conName").value = "";
conMail = document.getElementById("conMail").value = "";
conContant = document.getElementById("conContant").value = "";
document.querySelector(".con_error_msg").innerHTML = "<p style='color:green'>Successfully Sent</p>";
} } }
});
I use the ajax code outside wordpress work but in wordpress not works.
I just want to insert data using ajax in wordpress table. If you have any other method than suggest.
You added the wrong handler name to wp_enqueue_script for submit-form.js.
add_action('wp_enqueue_scripts', 'setting_up_scripts_contact_form_wp');
function setting_up_scripts_contact_form_wp() {
wp_register_style( 'contact-custom-style',plugins_url('public/css/style.css', __FILE__) );
wp_enqueue_style( 'contact-custom-style');
wp_enqueue_script( 'jsforcon-frontend-js', plugins_url('includes/submit-form.js', __FILE__),array(),false,true );
// wp_enqueue_script( 'wpforajax_con_test', plugins_url('public/js/test.js', __FILE__) );
// wp_register_script('wpforajax_con_test', plugin_dir_url(__FILE__) . 'test.js', true);
wp_localize_script(
'jsforcon-frontend-js',
'jsforcon_globals',
[
'ajax_url' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'jsforcon_insert_nonce' )
]
);
}
And change jsforwp_globals.ajax_url to jsforcon_globals.ajax_url
var cf_saveContact = document.getElementById("cf_saveContact");
cf_saveContact.addEventListener('click', function() {
var conName = document.getElementById("conName").value;
var conMail = document.getElementById("conMail").value;
var conContant = document.getElementById("conContant").value;
if(conName == "" || conMail == "" || conContant == ""){
document.querySelector(".con_error_msg").innerHTML = "<p style='color:red'>all fields are required</p>";
}else{
var action = "jsforcon-insert";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET",jsforcon_globals.ajax_url+"?action="+action+"&_ajax_nonce="+jsforcon_globals.nonce+"&name="+conName+"&mail="+conMail+"&content="+conContant,true);
xmlhttp.send();
xmlhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
conName = document.getElementById("conName").value = "";
conMail = document.getElementById("conMail").value = "";
conContant = document.getElementById("conContant").value = "";
document.querySelector(".con_error_msg").innerHTML = "<p style='color:green'>Successfully Sent</p>";
}
}
}
});
You say you're doing this in an AJAX call? Are you writing out the response from the AJAX call to be sure that you're not getting errors? Always check the XMLHttpRequest's status and response for errors before proceeding.

WP Login & Password comparisons

How i comparisons password & login via ajax using wp functions ? If user enter wrong password show error msj else ok. I try this code
$username = '';
$password = '';
$auth = wp_authenticate( $username, $password );
if ( is_wp_error( $auth ) ) {
$error_string = $auth->get_error_message();
echo '<div id="message" class="error"><p>' . $error_string . '</p></div>';
}
else {
echo "Ok!";
}
To Create the login page using ajax please follow the below steps :
1) Create form html in any custom template OR from admin side page Pages >> Add New
<div class="top_bar">
<div class="container">
<div class="ajax_login">
<form id="login" action="login" method="post">
<h1><?php esc_attr_e('User login','wordpress') ?></h1>
<p class="status"></p>
<input id="username" type="text" name="username" placeholder="<?php esc_attr_e('Username','wordpress') ?>">
<input id="password" type="password" name="password" placeholder="<?php esc_attr_e('Password','wordpress') ?>">
<div class="forgotten_box">
<a class="lost" href="<?php echo esc_url(wp_lostpassword_url()); ?>"><?php esc_attr_e('Lost your password?','wordpress') ?></a>
</div>
<input class="submit_button" type="submit" value="Login" name="submit">
<?php wp_nonce_field( 'ajax-login-nonce', 'security' ); ?>
</form>
<div class="ajax_login_overlay"></div>
<?php if (is_user_logged_in()):?>
<a class="login_button" href="<?php echo wp_logout_url( home_url() ); ?>"><?php esc_attr_e('Logout','wordpress') ?></a>
<?php else: ?>
<a class="login_button" id="show_login" href=""><?php esc_attr_e('Login','wordpress') ?></a>
<?php endif; ?>
</div>
</div>
</div>
2) Add Below Code in your current active theme functions.php file
For More Help see this link : signon and Ajax Call
/********* AJAX Login ***********/
function yourtheme_ajax_login_init(){
wp_register_script('ajax-login-script', get_template_directory_uri() . '/js/ajax-login-script.js', array('jquery') );
wp_enqueue_script('ajax-login-script');
wp_localize_script( 'ajax-login-script', 'ajax_login_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'redirecturl' => home_url(),
'loadingmessage' => esc_html__('Sending user info, please wait...', 'wordpress')
));
// Enable the user with no privileges to run ajax_login() in AJAX
add_action( 'wp_ajax_nopriv_ajaxlogin', 'ajax_login' );
}
// Execute the action only if the user isn't logged in
if (!is_user_logged_in()) {
add_action('init', 'yourtheme_ajax_login_init');
}
if (!function_exists('ajax_login')) {
function ajax_login(){
// First check the nonce, if it fails the function will break
check_ajax_referer( 'ajax-login-nonce', 'security' );
// Nonce is checked, get the POST data and sign user on
$info = array();
$info['user_login'] = $_POST['username'];
$info['user_password'] = $_POST['password'];
$info['remember'] = true;
$user_signon = wp_signon( $info, false );
if ( is_wp_error($user_signon) ){
echo json_encode(array('loggedin'=>false, 'message'=> esc_html__('Wrong username or password.', 'wordpress'))); //Send Error Message on login Failed.
} else {
echo json_encode(array('loggedin'=>true, 'message'=> esc_html__('Login successful, redirecting...', 'wordpress'))); //Send Message on Login Success .
}
wp_die();
}
}
3) En-queue the custom js file ajax-login-script.js that we placed in the js/ folder, write the below code in functions.php file
jQuery(document).ready(function($) {
"use strict";
// Show the login dialog box on click
$('a#show_login').on('click', function(e){
$('.ajax_login_overlay').fadeIn(500);
$('form#login').fadeIn(500);
e.preventDefault();
});
$('.ajax_login_overlay').on('click', function(e){
$('form#login').fadeOut(500);
$('.ajax_login_overlay').fadeOut(500);
$('form#register_form').hide();
$('.ajax_login .status').html('');
$('#registration-error-message').html('');
$('form#login').hide();
$('form#register_form .field input').val('');
});
// Perform AJAX login on form submit
$('form#login').on('submit', function(e){
$('form#login p.status').show().text(ajax_login_object.loadingmessage);
$.ajax({
type: 'POST',
dataType: 'json',
url: ajax_login_object.ajaxurl,
data: {
'action': 'ajaxlogin', //calls wp_ajax_nopriv_ajaxlogin
'username': $('form#login #username').val(),
'password': $('form#login #password').val(),
'security': $('form#login #security').val() },
success: function(data){
$('form#login p.status').text(data.message);
if (data.loggedin === true){
document.location.href = ajax_login_object.redirecturl;
}
}
});
e.preventDefault();
});
});
I hope it will help you.
Try below code
$user = get_user_by( 'login', $username );
if($user && wp_check_password($pass, $user->data->user_pass, $user->ID)){
echo "That's it";
}
else{
echo "Nope";
}
Ref : https://codex.wordpress.org/Function_Reference/wp_check_password

Upload file and insert data to database with php and jquery/ajax

Hi am trying to upload an image and insert data into items table ( phpmyadmin ) It works if i don't user ajax but when i tried to upload using ajax it didn't work
This is my html5 script
<form id="InsertItemTodatabase" enctype="multipart/form-data" action="requests/newItem.php" method="post" class="add-new-item-form-form">
<div class="form-group">
<input type="text" name="itemName" placeholder="Item name" class="form-control" id="itemNameJs">
</div>
<div class="form-group">
<input type="text" name="itemDesc" placeholder="Item Description" class="form-control" id="itemDescJs">
</div>
<div class="form-group">
<input type="text" name="itemPrice" placeholder="Item Price" class="form-control" id="itemPriceJs">
</div>
<div class="form-group">
<?php $fetch = fetchData( '*', 'category', '' , '', '', $fetch="fetchAll" ); ?>
<select class="form-control" name="category" id="itemCatJs">
<option value="0">Select Category</option>
<?php
foreach ($fetch as $data) {
echo '<option value="' . $data[ 'cat_id' ] . '">' . $data[ 'cat_name' ] . '</option>';
}
?>
</select>
</div>
<div class="form-group">
<input type="text" name="itemAmount" placeholder="Amount" class="form-control" id="itemAmountJs">
</div>
<div class="form-group">
<label for="uploadItemPic" class="btn btn-primary">Upload Item Picture</label>
<input type="file" id="uploadItemPic" name="itemPic" class="form-control">
</div>
<div class="form-group">
<button type="submit" name="submitAddItemForm" id="submitNow">
<i class="ti-plus"></i>
Add Item
</button>
</div>
</form><!-- /.add-new-item-form-form -->
And this is my jQuery/Ajax script for uplaoding data.
$(document).on( 'submit', '#InsertItemTodatabase', function(e){
e.preventDefault();
var file_data = $('#uploadItemPic').prop('files')[0],
name = $( '#itemNameJs' ).val(),
desc = $( '#itemDescJs' ).val(),
price = $( '#itemPriceJs' ).val(),
cat = $( '#itemCatJs option:selected' ).val(),
amount = $( '#itemAmountJs' ).val(),
image = $( '#uploadItemPic' ).val();
var file = new FormData();
file.append('file',$('#uploadItemPic')[0].files[0]);
var ajaxUrl = $(this).attr('action');
alert(file);
$.ajax({
url: ajaxUrl, // point to server-side PHP script
type: 'POST',
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: {
name : name,
desc : desc,
price : price,
cat : cat,
amount : amount,
image : image,
file
},
success: function(php_script_response){
alert(php_script_response); // display response from the PHP script, if any
}
});
});
And this is my newItem.php
<?php
if( $_SERVER[ 'REQUEST_METHOD' ] == 'POST' ){
include "../database\connect.php";
$item_name = $_POST[ 'itemName' ];
$item_desc = $_POST[ 'itemDesc' ];
$item_price = $_POST[ 'itemPrice' ];
$item_amount = $_POST[ 'itemAmount' ];
$item_category = $_POST[ 'category' ];
$formErrors = array();
if( empty( $item_name ) ){
$formErrors[] = 'You should type the item name';
}
if( empty( $item_desc ) ){
$formErrors[] = 'You should add item description';
}
if( empty( $item_price ) ){
$formErrors[] = 'You should add item price';
}
if( empty( $item_amount ) ){
$formErrors[] = 'You should type item amount';
}
if( $item_category == 0 ){
$formErrors[] = 'You should select item category';
}
$item_picture = $_FILES[ 'itemPic' ];
$picture_name = $item_picture[ 'name' ];
$picture_temp = $item_picture[ 'tmp_name' ];
$picture_size = $item_picture[ 'size' ];
$picture_type = $item_picture[ 'type' ];
if( empty( $picture_name ) ){
$formErrors[] = 'You should select item picture';
}
/*
Picture Extension
-------------------
*/
$extensions = array( "png", "jpg", "jpeg", "gif" );
$picture_name_explosion = explode('.', $picture_name);
$extension_name = end( $picture_name_explosion );
$extension = strtolower( $extension_name );
if( !in_array($extension, $extensions) && !empty( $picture_name ) ){
$formErrors[] = 'This extension is not allowed';
}
if($picture_size > 4194304){
$formErrors[] = 'Image Can\'t Be Larger Than 4MB';
}
if( empty( $formErrors ) ){
$item_image = rand( 0, 1000000 ) . '_' . $picture_name;
move_uploaded_file($picture_temp, '../layouts/images/items' . $item_image);
$stmt = $db->prepare( "INSERT INTO Items( item_name, item_description, item_pic, item_price, amount, added_date, cat_id ) VALUES( :zname, :zdesc, :zpic, :zprice, :zamount, :zdate, :zcat ) " );
$stmt->execute( array(
'zname' => $item_name,
'zdesc' => $item_desc,
'zpic' => $item_image,
'zprice' => '$' . $item_price,
'zamount' => $item_amount,
'zdate' => date( 'Y-m-d h:i:s' ),
'zcat' => $item_category
) );
echo date( 'Y-m-d h:i:s' );
}
foreach ($formErrors as $error) {
var_dump( $error );
}
}
When i tried to upload i get an error that $_POST data is not defined in newItem.php
Please help me in that, And thanks in advance!
You don't need to write so much of code, instead
try to give name attribute to your form tab.
<form id="jqdata" enctype="multipart/form-data" method="post" class="add-new-item-form-form" name="jqdata" action="requests/newItem.php">
Now your ajax call:
var ajaxUrl = $(this).attr('action');
$(document).ready(function(){
$('#submitNow').click(function(e){
e.preventDefault();
var form = $("#jqdata");
var formdata = new FormData(form[0]);
$.ajax({
url: ajaxUrl,
data: formdata,
processData: false,
contentType: false,
type: 'POST',
success: function (output) {
alert(output);
$("#jqdata")[0].reset(); //reset all data from form.
}
});
});
});
Try this and do let me know if it works.
Change your variable assignments as mentioned below:
$item_name = $_POST[ 'name' ];
$item_desc = $_POST[ 'desc' ];
$item_price = $_POST[ 'price' ];
$item_amount = $_POST[ 'amount' ];
$item_category = $_POST[ 'cat' ];
The Data posted to newitems file is the one that you have set in your ajax request. So the field names that you are using should be changed to match the ones set in your ajax data.

error on contact form submit via jquery ajax

Based on this question i had to rewrite my contact form script.
The goal is to to have a send button labeled send. After clickick it should show sending till the php script is done. When its done it should show sent.
Thats my simple form:
<form id="contactForm" action="mail.php" method="post">
<input type="text" id="name" name="name" placeholder="Name" required><br />
<input type="text" id="email" name="email" placeholder="Mail" required><br />
<textarea name="message" id="message" placeholder="Nachricht" required></textarea><br />
<button name="submit" type="submit" id="submit">send</button>
</form>
Here is the jquery script for the label changing and the ajax submit.
<script>
$( init );
function init() {
$('#contactForm').submit( submitForm );
}
function submitForm() {
var contactForm = $(this);
if ( !$('#name').val() || !$('#email').val() || !$('#message').val() ) {
$('#submit').html('error');
} else {
$('#submit').html('sending');
$.ajax( {
url: contactForm.attr( 'action' ) + "?ajax=true",
type: contactForm.attr( 'method' ),
data: contactForm.serialize(),
success: submitFinished
} );
}
return false;
}
function submitFinished( response ) {
response = $.trim( response );
if ( response == "success" ) {
$('#submit').HTML = ('sent');
} else {
$('#submit').html('error');
}
}
</script>
the mail.php:
<?php
define( "RECIPIENT_NAME", "John Doe" );
define( "RECIPIENT_EMAIL", "john#doe.com" );
define( "EMAIL_SUBJECT", "Subject" );
$success = false;
$name = isset( $_POST['name'] ) ? preg_replace( "/[^\.\-\' a-zA-Z0-9]/", "", $_POST['name'] ) : "";
$email = isset( $_POST['email'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['email'] ) : "";
$message = isset( $_POST['message'] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_POST['message'] ) : "";
if ( $name && $email && $message ) {
$recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
$headers = "Von: " . $name . " <" . $email . ">";
$success = mail( $recipient, EMAIL_SUBJECT, $message, $headers );
}
if ( isset($_GET["ajax"]) ) {
echo $success ? "success" : "error";
} else {
//add html for javascript off user
}
?>
Its submits correct and i get the mail but i doesnt change the label to sent.Its stuck at sending.
Any idea or suggestions whats wrong with my code?
best regards
dennym
The error is on this line:
$('#submit').HTML = ('sent');
Change that to:
$('#submit').html('sent');
$('#submit').HTML = ('sent');
should be
$('#submit').html('sent');
like you have everywhere else.
You have to change
$('#submit').HTML = ('sent');
to:
$('#submit').html('sent');
in your function submitFinished();

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