Multiple Ajax Forms using Wordpress Loop - javascript

I am trying to make multiple Ajax forms work in a Wordpress loop. I have given the form and fields in each form a unique ID. I'm trying to reference each form within the javascript in order to submit the AJAX form but instead the page refreshes as if it's trying to submit the form using php. I am no expert and can't figure out how this works. The script works for an individual form as I can reference the actual form_id directly within the javascript. I want to be able to submit the form on each post within the loop without having to refresh the page. Thanks in advance for your help.
Javascript in the template that contains the loop.
<script>
var form_id = $(this).closest("form").attr('id');
form_id.validate({
highlight: function(element, errorClass, validClass) {
$(element).parent('label').addClass('errors');
},
unhighlight: function(element, errorClass, validClass) {
$(element).parent('label').removeClass('errors');
},
submitHandler: function(form) {
$.ajax({
type: "POST",
url: '<?php echo admin_url(); ?>admin-ajax.php',
data: form_id.serialize(),
beforeSend: function() {
$("input[name=submit],button", form).attr('disabled', 'disabled');
$("div.loading", form).show();
$("div.status", form).hide();
},
success: function(result) {
if (result == 1 || result == '1') {
$("div.loading", form).hide();
$("div.thanks").slideDown();
document.forms["leadForm"].reset();
} else {
$("div.loading", form).hide();
$("input[name=submit],button", form).removeAttr('disabled');
$("div.status", form).html(result).show();
}
}
});
}
});
</script>
The form within the loop.
<?php $pid = get_the_ID(); ?>
<form name="leadForm" method="post" id="leadForm-<?php echo $pid; ?>" action="#">
<div class="grid-x grid-padding-x">
<div class="medium-12 cell">
<textarea tabindex="2" rows="6" cols="30" maxlength="350" title="Please enter a message" name="message" id="message-<?php echo $pid; ?>" placeholder="Your message" ></textarea>
</div>
<div class="medium-6 cell">
<label>Full Name
<input type="text" placeholder="Full Name" class="required" autocomplete="off" name="fullname" id="fullname-<?php echo $pid; ?>" >
</label>
</div>
<div class="medium-6 cell">
<label>Email Address
<input type="email" placeholder="Email Address" class="required" autocomplete="off" name="email" id="email-<?php echo $pid; ?>" >
</label>
</div>
<div class="medium-12 cell">
<label>Phone Number
<input type="tel" placeholder="Phone Number" class="required" autocomplete="off" name="phone" id="phone-<?php echo $pid; ?>" >
</label>
</div>
<div class="medium-12 cell">
<button class="button submit radius expanded" type="submit" >Send</button>
<div class="loading" style="display:none;" >
<img src="<?php echo get_template_directory_uri(); ?>/images/progress.gif" alt="Loading..." />
</div>
<div class="status callout radius alert small" style="display:none; text-align:center;">There was an error sending your message.
</div>
<div class="thanks callout radius success small" style="display:none; text-align:center;">Thank you.
</div>
<input type="hidden" name="current_url" value="<?php echo the_permalink(); ?>" class="button" />
<input type="hidden" name="current_title" value="<?php echo the_title(); ?>" class="button" />
</div>
</div>
</form>
The php script within the Wordpress - functions.php
<?php
add_action('wp_ajax_nopriv_leadForm', 'core_leadForm');
add_action('wp_ajax_leadForm', 'core_leadForm');
function core_leadForm()
{
if (!((isset($_POST['fullname']) && !empty($_POST['fullname'])) && (isset($_POST['email']) && !empty($_POST['email'])) && (isset($_POST['phone']) && !empty($_POST['phone'])) && (isset($_POST['message']) && !empty($_POST['message'])) ))
{
echo 'Enter all fields';
}
else if (!is_email($_POST['email']))
{
echo 'Email is not valid';
}
else
{
if (function_exists('ot_get_option'))
{
//$to = ot_get_option('cont_email');
$to = 'email#website.com';
}
else
{
$to = '';
}
}
}
ob_start();
?>
<br>
<table>
<tr>
<td><b><u>CONTACT DETAILS</u></b><br>
<br></td>
<td> </td>
</tr>
<tr>
<td><b>Full Name:</b></td>
<td><?php echo $_POST['fullname'] ?></td>
</tr>
<tr>
<td><b>Phone Number:</b></td>
<td><?php echo $_POST['phone'] ?></td>
</tr>
<tr>
<td><b>Email Address:</b></td>
<td><?php echo $_POST['email'] ?></td>
</tr>
<tr>
<td><b>Link:</b></td>
<td><?php echo $_POST['current_title'] ?></td>
</tr>
<tr>
<td><b>Message:</b></td>
<td><?php echo $_POST['message'] ?></td>
</tr>
</table>
<?php
$message = ob_get_contents();
ob_end_clean();
$subject = 'NEW MESSAGE';
$headers[] = 'From: ' . $_POST["fullname"] . ' <' . $_POST["email"] . '>';
add_filter('wp_mail_content_type', 'core_html_content_type');
function core_html_content_type()
{
return 'text/html';
}
if (wp_mail($to, $subject, $message, $headers))
{
// echo "test";
echo 1;
}
else
{
echo 'Your message failed to send. Please try again.';
}
die();
?>

Hard to replicate all the issues that WP might have with your code. But it would be one of these:
this when used outside of an reference to an html object refers to window. .closest travels up the dom tree, not down, so it will not find forms within the window object. The same effect of what you want to achieve can be achieved by $('form').attr('id'), i.e. return the id of the 1st form found.
You need to ensure $ is defined before using, this is a WP quirk of using the shipped version of jquery, you substitute the word jQuery for $
I see no evidence that jQuery is loaded by the time you use it, you are also using another library, .validate, make use of $(document).ready();
Also on a side note, learn how to use the console (e.g. in chrome), you can output js here to test variables, any errors in your code will output here too.

Related

div #id in foreach loop only selects last variable when trying to show/hide in function

I am navigating through a simple foreach loop to get "blog posts". It shows basic blog information, a reply and delete button. When I select the 'reply' button, a small form beneath the reply button appears to fill out. The problem is, the function I am passing the variable to, only gets the last id for the form. How do I change my function or div element to be unique for each instance?
I have tried setting up PHP #echo variable's on the "id" and function, I have checked all my opening and closing brackets 10-fold. I have tried using different GetElementBy ... methods. I started looking into Jquery but I wanted to get this finished with PHP/Javascript only.
<?php foreach ($mainentries as $entry) :
$subentryID = $entry['SubEntryID'];
if ($subentryID == "0")
{ ?>
<div><tr><td><?php echo ('#'.$entry['EntryID'].' - ')?></td>
<td><?php echo $entry['Body']; ?></td>
<br />
<?php foreach($subentries as $subentry) : ?>
<?php if ($subentry['SubEntryID'] == $entry['EntryID'])
{ ?>
<div id="subposts">
<td><td><td>#<?php echo $subentry['EntryID'];?></td><br>
<td>
<?php echo $subentry['Body']; ?>
</td></td></td>
</div>
<?php } endforeach; ?>
<br />
<td>
<button onclick="cookiechecksub()">Reply</button>
<?php echo $entry['EntryID'];
$subform = $entry['EntryID']; ?>
<div id="<?php echo $subform?>" style="display:none">
<form action="Add_subentry.php" method="post" id="Add_subentry">
<label>Title:</label><br />
<input type = "text" name="Title" class="Title"/> <br />
<label>Body</label><br />
<div class="area">
<input type = "textarea" name="Body" class="Body"/><br />
</div>
<input type="hidden" readonly="true" name="EntryID" value="<?php echo $entry['EntryID']; ?>" />
<input type=submit id="btnReply" value="Submit Reply"/>
</form>
</div></td>
<td>
<form action="Delete_entry.php" method="post" id="Delete_entry">
<input type="hidden" readonly="true" name="EntryID" value="<?php echo $entry['EntryID']; ?>" />
<?php if ($userid == 1)
{ ?>
<input type="submit" id="btnDelete" value="Delete Post"/>
<?php } ?>
<br /><br />
</form>
</td>
</tr>
</div>
<?php
} endforeach; ?>
<Script>
function cookiechecksub() {
if (!userid) {
if (confirm("Please log in first")) {
window.location.replace("http://localhost/alexdes/login-logout.php");
}
}
else {
TryAddSubPost();
}
}
function TryAddSubPost()
{
var x = document.getElementById("<?php echo $subform?>");
if (x.style.display === "none")
{
x.style.display="block";
}
else
{
x.style.display="none";
}
}
</Script>
this is because you used php echo in the js function especially in TryAddSubPost
change it to be like this:
<script>
function cookiechecksub(id) {
if (!userid) {
if (confirm("Please log in first")) {
window.location.replace("http://localhost/alexdes/login-logout.php");
}
}
else {
TryAddSubPost(id);
}
}
function TryAddSubPost(id)
{
var x = document.getElementById(id);
if (x.style.display === "none")
{
x.style.display="block";
}
else
{
x.style.display="none";
}
}
</script>
and use the id from php only when calling the function, like this:
<button onclick="cookiechecksub('<?php echo $entry['EntryID']?>')">Reply</button>
Give cookiechecksub an argument, and pass it to TryAddSubPost
<button onclick="cookiechecksub('<?=$entry['EntryID']?>')">

Combining two or more submit buttons into one

I have submit buttons for different section of the webpage. The submit button is used to update the forms and database with the text value in the form fields. Currently, each submit button updates the forms (tied to their respective PKEY id, "consideration_no") only in their own sections. I want to update all the sections forms with one button click.
As you can see from the code below, there are 2 submit buttons. I have tried to link two together through IDs but it did not work for me.
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$question = $answer = "";
$question_err = $answer_err = "";
if(isset($_POST["dg_no"]) && !empty($_POST["dg_no"])){
//counter for array
$counter = 0;
// Get hidden input value
$dg_no = $_POST['dg_no'];
$consideration_no = $_REQUEST['consideration_no'];
$answer = $_POST['answer'];
// Check input errors before inserting in database
if(empty($answer_err)){
// Validate address address
$input_answer = trim($_POST["answer"]);
if(empty($input_answer)){
$answer_err = "Please enter an answer.";
} else{
$answer = $input_answer;
$answer1[$counter] = $input_answer;
}
// Prepare an Submit statement
$sql = 'Update "PDPC".consideration SET answer=:answer WHERE consideration_no = :consideration_no';
if($stmt = $pdo->prepare($sql)){
$stmt->bindParam(":answer", $param_answer);
$stmt->bindParam(":consideration_no", $param_consideration_no);
//$stmt->bindParam(":dg_no", $param_dg_no);
//Set Parameter in while loop, hence new set of parameter for every new form is created and executed.
//Could change the counter loop to a dynamic loop with foreach array.
while ($counter<15){
$param_answer = $answer[$counter];
$param_consideration_no = $consideration_no[$counter];
$stmt->execute();
//$param_dg_no = $dg_no;
// Attempt to execute the prepared statement
//debugggggg
/* $message = $consideration_no[$counter];
$message1 = $answer[$counter];
$message2 = 'lol';
echo "<script type='text/javascript'>alert('$message, $message1, $message2 ');</script>"; */
$counter++;
//apparently redirecting can be placed in the loop, and fields will still get changed.
//header("location: home1.php?dm_no=".$_GET["dm_no"]);
header("location: home1.php?dm_no=".$_GET["dm_no"]);
}
}
if($stmt->execute()){
//Records Submitd successfully. Redirect to landing page
header("location: home1.php?dm_no=".$_GET["dm_no"]);
exit();
} else{
echo "Something went wrong. Please try again later.";
}
// Close statement
unset($stmt);
}
// Close connection
unset($pdo);
} else{
/* --- DISPLAY/READ TABLE, SEE SECTIONS AND ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */
// Check existence of dg_no parameter before processing further
if(isset($_GET["dg_no"]) && !empty(trim($_GET["dg_no"]))){
// Get URL parameter
$dg_no = trim($_GET["dg_no"]);
// Prepare a select statement
$sql = 'SELECT * FROM "PDPC".consideration WHERE (dg_fkey = :dg_no AND code_no = 1) ORDER BY consideration_no';
if($stmt = $pdo->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bindParam(":dg_no", $param_no);
// Set parameters
//$param_no = $dg_no;
$param_no = trim($_GET["dg_no"]);
// Attempt to execute the prepared statement
if($stmt->execute()){
if($stmt->rowCount() > 0){
SubSection($subsection1_1); //Consent Collection Subsection
while($row = $stmt->fetch()){
// Retrieve individual field value
$consideration_no = $row["consideration_no"];
$question = $row["question"];
$answer = $row["answer"];
$dg_no = $_GET['dg_no'];
//...time to show the questions and answers with the while loop...
?>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<div class="form-group <?php echo (!empty($answer_err)) ? 'has-error' : ''; ?>">
<label><?php echo $question; ?></label>
<input type="text" name="answer[]" class="form-control" value="<?php echo $answer; ?>">
<span class="help-block"><?php echo $answer_err;?></span>
<input type="hidden" name="consideration_no[]" value="<?php echo $consideration_no; ?>"/>
<input type="hidden" name="dg_no" value="<?php echo $dg_no; ?>"/>
</div>
<?php
}
//...after the loop, show the Submit and Cancel button, coz we only need 1 set each section.
?>
<input type="Submit" name = "$consideration_no[]" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
<?php
}
}
else{
echo "Oops! Something went wrong. Please try again later.";
}
}
Section($section2); //Collection section
// Prepare a select statement
$sql = 'SELECT * FROM "PDPC".consideration WHERE (dg_fkey = :dg_no AND code_no = 2) ORDER BY consideration_no';
if($stmt = $pdo->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bindParam(":dg_no", $param_no);
// Set parameters
//$param_no = $dg_no;
$param_no = trim($_GET["dg_no"]);
// Attempt to execute the prepared statement
if($stmt->execute()){
if($stmt->rowCount() > 0){
SubSection($subsection2); //Consent Collection Subsection
while($row = $stmt->fetch()){
// Retrieve individual field value
$consideration_no = $row["consideration_no"];
$question = $row["question"];
$answer = $row["answer"];
$dg_no = $_GET['dg_no'];
//...time to show the questions and answers with the while loop...
?>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<div class="form-group <?php echo (!empty($answer_err)) ? 'has-error' : ''; ?>">
<label><?php echo $question; ?></label>
<input type="text" name="answer[]" class="form-control" value="<?php echo $answer; ?>">
<span class="help-block"><?php echo $answer_err;?></span>
<input type="hidden" name="consideration_no[]" value="<?php echo $consideration_no; ?>"/>
<input type="hidden" name="dg_no" value="<?php echo $dg_no; ?>"/>
</div>
<?php
}
//...after the loop, show the Submit and Cancel button, coz we only need 1 set each section.
?>
<input type="Submit" name = "$consideration_no[]" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
<?php
}
}
else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
unset($stmt);
// Close connection
unset($pdo);
}
else{
// URL doesn't contain dg_no parameter. Redirect to error page
header("location: error.php");
exit();
}
}
I want it to update all the fields, in different sections, with one submit button
your code was bit difficult to read, but from what i understood you are trying to combine two or more form submissions into one. It's quiet simple
<form method="POST" action="save.php">
<input type=text name=name[] />
<input type=text name=name[] />
</form>
by using the [] to identify the input element you can have multiple values with the same name where you can access them from the PHP script as an array.
For example the above example will produce an array as follows
<?php
print_r($_POST['name']); //("name" => Array....
is this clear enough for you? if not drop a comment, i will explain more. As a side note i do recommend you look into using template engine, and also a framework in your coding project.
Here's what I see when i separate the html into a new file. I tried to remove the excess forms but when I open the last collapsible section, it instantly executes a submit action and brings me back to the home page.
<button class="collapsible"><?php echo $section ?></button>
<div class="content">
<button class="collapsible"><?php echo $subsection ?></button>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<?php
//while loop start
?>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<div class="form-group <?php echo (!empty($answer_err)) ? 'has-error' : ''; ?>">
<label><?php echo $question; ?></label>
<input type="text" name="answer[]" class="form-control" value="<?php echo $answer; ?>">
<span class="help-block"><?php echo $answer_err;?></span>
<input type="hidden" name="consideration_no[]" value="<?php echo $consideration_no; ?>"/>
<input type="hidden" name="dg_no" value="<?php echo $dg_no; ?>"/>
</div>
<?php
//while loop ends
?>
<input type="Submit" name = "$consideration_no[]" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
<?php
//while loop start
?>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<div class="form-group <?php echo (!empty($answer_err)) ? 'has-error' : ''; ?>">
<label><?php echo $question; ?></label>
<input type="text" name="answer[]" class="form-control" value="<?php echo $answer; ?>">
<span class="help-block"><?php echo $answer_err;?></span>
<input type="hidden" name="consideration_no[]" value="<?php echo $consideration_no; ?>"/>
<input type="hidden" name="dg_no" value="<?php echo $dg_no; ?>"/>
</div>
<?php
//while loop ends
?>
<input type="Submit" name = "$consideration_no[]" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
<?php

Email input is not taking email address as valid input in newsletter subscribe box

I have newsletter subscribe input in opencart website and when i input email and press subscribe it says "Email is not valid!: even thou it is.
So i cant use it since it doesnt take emails.
I used this theme and didnt change anything in the subscribe module,
you can scroll down to the footer and check how it behaves here: http://demopavothemes.com/pav_woosa/demo2/
Cant figure out what is the problem.
Heres the code of the module:
<div class="<?php echo $prefix; ?> newsletter-v1" id="newsletter_<?php echo $position.$module;?>">
<form id="formNewLestter" method="post" action="<?php echo $action; ?>" class="formNewLestter">
<div class="panel panel-v1">
<div class="panel-heading">
<h4 class="panel-title"><?php echo $objlang->get("entry_newsletter");?></h4>
</div>
<div class="panel-body">
<div class="input-group">
<input type="text" placeholder="Email Here ..." class="form-control email" <?php if(!isset($customer_email)): ?> <?php endif; ?> size="18" name="email">
<div class="input-group-btn pull-left">
<button type="submit" name="submitNewsletter" class="btn btn-primary icon-mail radius-6x"><?php echo $objlang->get("button_subscribe");?></button>
</div>
</div>
<input type="hidden" value="1" name="action">
<div class="valid space-top-10"></div>
</div>
<?php if (!empty($social)): ?>
<?php echo html_entity_decode( $social );?>
<?php endif ?>
</div>
</form>
</div>
<script type="text/javascript"><!--
$( document ).ready(function() {
var id = 'newsletter_<?php echo $position.$module;?>';
$('#'+id+' .box-heading').bind('click', function(){
$('#'+id).toggleClass('active');
});
$('#formNewLestter').on('submit', function() {
var email = $('.inputNew').val();
$(".success_inline, .warning_inline, .error").remove();
if(!isValidEmailAddress(email)) {
$('.valid').html("<div class=\"error alert alert-danger\"><?php echo $objlang->get('valid_email'); ?><button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button></div></div>");
$('.inputNew').focus();
return false;
}
var url = "<?php echo $action; ?>";
$.ajax({
type: "post",
url: url,
data: $("#formNewLestter").serialize(),
dataType: 'json',
success: function(json)
{
$(".success_inline, .warning_inline, .error").remove();
if (json['error']) {
$('.valid').html("<div class=\"warning_inline alert alert-danger\">"+json['error']+"<button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button></div>");
}
if (json['success']) {
$('.valid').html("<div class=\"success_inline alert alert-success\">"+json['success']+"<button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button></div>");
}
}
});
return false;
});
});
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}
--></script>
This line:
$('.inputNew')
is looking for a class named inputNew. Your HTML doesn't have an element with that name. Your element it looks like has a class of email.
<input type="text" placeholder="Email Here ..." class="form-control email" <?php if(!isset($customer_email)): ?> <?php endif; ?> size="18" name="email">
^^^^^
You also could use the form-control but that doesn't sound unique. An id would be better or you could use the name attribute like this:
$('input[name="email"]')
so change the JS line to:
var email = $('.email').val();
or
var email = $('input[name="email"]').val();
You can read more about these here, https://api.jquery.com/category/selectors/.

Hide/Show toggle echo results in php

I am trying to toggle results i have echo'd out of table but i am having no luck.
I have tried the same code in HTML and it works perfectly.
Ive been working on this for a while now, and was wondering if someone could point me in the right direction.
What I've tired
Adding the javascript inside the php echo.
Adding a counter to the id, to make it unique on loop
Placing each line of the echo results in echo(""); tags.
adding a counter, to make the id unique on loop.
PHP
$i = 1;
while ($output = $fc_sel->fetch_assoc()) {
$fc_run .= $output['Food_Cat_name'] . $output['Food_Cat_Desc'] . '<br>';
$_SESSION['Food_Cat_name'] = $output['Food_Cat_name']; //echo out product name
$_SESSION['Food_Cat_Desc'] = $output['Food_Cat_Desc']; //echo out product desc
echo"
<div id='first_product'>
<button onclick='toggle_visibility('tog')'>Toggle</button>
<div id='tog'>
<div id='red_head'>
<p id='menu_title' class ='hidden' onclick='toggle_visibility('tog')'> Add your first menu item</p>
</div>
<h3 id='menu'>Menu Section</h3>
<form name='first_prod' id='first_prod' enctype='multipart/form-data' action='testing.php' method='POST' accept-charset='utf-8' >
<label id='cat_label' name='cat_label'>Name</label>
<input type='text' id='cat_name' name='cat_name' value=''>
<label id='desc_label' name='desc_label'>Description</label>
<input type='text' id='cat_desc' name='cat_desc' value=''>
</form>
</div>
</div>
";
}
}
JAVASCRIPT
<script>
//turn entire div into toggle
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.display == 'block' || e.style.display == '')
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>
The single quotes in onclick='toggle_visibility('tog')' are conflicting with the outer single quotes. So either escape them or use double quotes in either the outer pair or the inner pair.
Then in PHP, remove the <?php echo. Just put the HTML in PHP. The echo only complicates things. If you need dynamic data in your HTML, just inject it at that place with <?php ... ?>. But so far I haven't seen any of that in your HTML: it is static.
Here is a working snippet, after having made that change in two places:
//turn entire div into toggle
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.display == 'block' || e.style.display == '')
e.style.display = 'none';
else
e.style.display = 'block';
}
<div id='first_product'>
<button onclick="toggle_visibility('tog')">Toggle</button>
<div id='tog'>
<div id='red_head'>
<p id='menu_title' class ='hidden' onclick="toggle_visibility('tog')"> Add your first menu item</p>
</div>
<h3 id='menu'>Menu Section</h3>
<form name='first_prod' id='first_prod' enctype='multipart/form-data' action='testing.php' method='POST' accept-charset='utf-8' >
<label id='cat_label' name='cat_label'>Name</label>
<input type='text' id='cat_name' name='cat_name' value=''>
<label id='desc_label' name='desc_label'>Description</label>
<input type='text' id='cat_desc' name='cat_desc' value=''>
</form>
</div>
</div>
Edit after modification of the question
The code in the question was extended so the HTML is produced in a loop now.
You should now take care to produce unique id values only. So you'll probably want to add <?=$i?> at several places, like this:
<?php
session_start();
// ....
$i = 1;
while ($output = $fc_sel->fetch_assoc()) {
$fc_run .= $output['Food_Cat_name'] . $output['Food_Cat_Desc'] . '<br>';
$_SESSION['Food_Cat_name'] = $output['Food_Cat_name'];
$_SESSION['Food_Cat_Desc'] = $output['Food_Cat_Desc'];
?>
<div id='first_product<?=$i>'>
<button onclick="toggle_visibility('tog<?=$i>')">Toggle</button>
<div id='tog<?=$i>'>
<div id='red_head<?=$i>'>
...etc. Note that the PHP was closed before the HTML output started. Do this, instead of a large echo. Then at the end of it, open PHP tag again to end the loop:
<?php
}
?>
please modify your code
echo "
<div id='first_product'>
<button onclick='toggle_visibility(\"tog\")'>Toggle</button>
<div id='tog'>
<div id='red_head'>
<p id='menu_title' class ='hidden' onclick='toggle_visibility(\"tog\")'> Add your first menu item</p>
</div>
<h3 id='menu'>Menu Section</h3>
<form name='first_prod' id='first_prod' enctype='multipart/form-data' action='testing.php' method='POST' accept-charset='utf-8' >
<label id='cat_label' name='cat_label'>Name</label>
<input type='text' id='cat_name' name='cat_name' value=''>
<label id='desc_label' name='desc_label'>Description</label>
<input type='text' id='cat_desc' name='cat_desc' value=''>
</form>
</div>
</div>
"
<button value='tog' onclick='toggle_visibility(this)'>Toggle</button>
Just use "this" and assign value to button its working
Try this ;)
<?php
$i = 1;
while($output = $fc_sel->fetch_assoc()){
$fc_run .= $output['Food_Cat_name'] . $output['Food_Cat_Desc'] . '<br>';
$_SESSION['Food_Cat_name'] = $output['Food_Cat_name']; //echo out product name
$_SESSION['Food_Cat_Desc'] = $output['Food_Cat_Desc']; //echo out product desc
?>
<div id="first_product<?php echo $i; ?>">
<button onclick="javascript:toggle_visibility('tog<?php echo $i; ?>')">Toggle</button>
<div id="tog<?php echo $i; ?>">
<div id="red_head<?php echo $i; ?>">
<p id="menu_title<?php echo $i; ?>" class ="hidden" onclick="toggle_visibility('tog<?php echo $i; ?>')"> Add your first menu item</p>
</div>
<h3 id="menu<?php echo $i; ?>">Menu Section</h3>
<form name="first_prod" id="first_prod<?php echo $i; ?>" enctype="multipart/form-data" action="testing.php" method="POST" accept-charset="utf-8">
<label id="cat_label<?php echo $i; ?>" name="cat_label">Name</label>
<input type="text" id="cat_name<?php echo $i; ?>" name="cat_name" value="">
<label id="desc_label<?php echo $i; ?>" name="desc_label">Description</label>
<input type="text" id="cat_desc<?php echo $i; ?>" name="cat_desc" value="">
</form>
</div>
</div>
<?php
$i++;
}
?>

php echo codeigniter into javascript array

I have this bit of code in my codeigniter view:
<script>
var content = [];
content[<?php echo $storageItem["id"]; ?>] = "<?php echo form_open("/account/edititem", array("class" => "form-inline"), array("id" => $storageItem["id"], "item_loc" => "inventory", "acctid" => $acct_data->account_id)); ?>
<div class="panel-body">
<div class="row">
<div class="col-xs-2">
<strong>Refine level:</strong> <input type="number" name="refine" class="form-control" value="<?php echo $storageItem["refine"]; ?>" <?php if ($storageItem["type"] != 4 && $storageItem["type"] != 5) { echo "readonly"; } ?> />
</div>
<div class="col-xs-2">
<strong>Broken?:</strong> <input type="checkbox" name="attribute" class="form-control" value="1" <?php if ($storageItem["attribute"] == 1) { echo "checked"; } if ($storageItem["type"] != 4 && $storageItem["type"] != 5) { echo "disabled"; } ?> />
</div>
<div class="col-xs-2">
<strong>Bound?:</strong> <input type="checkbox" name="bound" class="form-control" value="1" <?php if ($storageItem["bound"] == 1) { echo "checked"; } ?> />
</div>
</div>
<br />
<div class="row">
<div class="col-xs-2">
<strong>Card 1:</strong> <input type="number" name="card0" class="form-control" value="<?php echo $storageItem["card0"]; ?>" <?php if ($storageItem["type"] != 4 && $storageItem["type"] != 5) { echo "readonly"; } ?> /></br>
</div>
<div class="col-xs-2">
<strong>Card 2:</strong> <input type="number" name="card1" class="form-control" value="<?php echo $storageItem["card1"]; ?>" <?php if ($storageItem["type"] != 4 && $storageItem["type"] != 5) { echo "readonly"; } ?> /></br>
</div>
<div class="col-xs-2">
<strong>Card 3:</strong> <input type="number" name="card2" class="form-control" value="<?php echo $storageItem["card2"]; ?>" <?php if ($storageItem["type"] != 4 && $storageItem["type"] != 5) { echo "readonly"; } ?> /></br>
</div>
<div class="col-xs-2">
<strong>Card 4:</strong> <input type="number" name="card3" class="form-control" value="<?php echo $storageItem["card3"]; ?>" <?php if ($storageItem["type"] != 4 && $storageItem["type"] != 5) { echo "readonly"; } ?> /></br>
</div>
</div>
<?php echo form_close(); ?>
</div>";
</script>
I create array named 'content' in javascript and then need to stuff almost an entire form into it to be able to create a child row in DataTables.
( for more information regarding what I've been trying to do and where these variables come from, see Datatables child row with PHP data from Codeigniter )
I've tried escaping single and double quotes (PHP complains about this), json_encode (PHP also complains about this as I still need the quotes and PHP interprets the quotes as the end of the json_encode), I've tried surrounding the entire value of the javascript array with '"' and "'", I've tried surrounding every line with ' '+ without success as well. How do I get this entire string into a form where javascript and PHP will parse it correctly and neither of them freak out?
Look at what you're doing:
<script>
var content = [];
content[<?php [..snip..] ?>] = "<?php [..snip..] ?>
^---start of javascript string
<div class="panel-body">
^---end of javascript string
^---start of another string
That means you have essentially:
variable = "some string stuff"variable-variable"more string stuff"
which is outright illegal JS.
The specific fix is to ESCAPE all of the strings in that html:
<script>
yadayada
<div class=\"panel-body\"> yada yadayada
^-----------^
But that doesn't fix the fact that this is incredibly bad code. You shouldn't be dumping loads of html into a JS string, and you should never be directly echoing text from PHP into a JS context.
If nothing else, why not generate all the content in PHP, then dump it all out as json?
<?php
$data = "blah blah blah blah";
?>
<script>
var content = <?php echo json_encode($data); ?>;

Categories

Resources