PHP get cloned html element values - javascript

So I have code in my HTML page which makes dynamic fields for measurements. By default, I have this html code
<form id="data_form" method="post">
<fieldset class="flex one" id="box_parent">
<h3><span class="label warning"><i class="fas fa-box-open"></i> Parcel:</span></h3>
<label>
Weight (kg):<input style="width: 10%;" name="pl_weight[]" type="number">
Length (cm):<input style="width: 10%;" name="pl_length[]" type="number">
Width (cm):<input style="width: 10%;" name="pl_width[]" type="number">
Height (cm):<input style="width: 10%;" name="pl_height[]" type="number">
</label>
</fieldset>
<fieldset class="flex one" id="box_child"></fieldset>
<input style="font-size: 1.2em; border: 2px solid #595a5a; letter-spacing: 2px" type="submit" id="get_rates" value="Submit">
<form>
<input style="font-size: 1.2em; border: 2px solid #595a5a; letter-spacing: 2px" type="button" id="add_box_measurement" value="Add Package">
Javascript:
$( "#add_box_measurement" ).click(function() {
$( "#box_parent" ).clone().appendTo( "#box_child" );
});
$('#data_form').submit(function(e){
var form_data = $(this).serializeArray();
$.ajax({
url: endpoint,
type: 'post',
data: form_data
}).done((response) => {
});
It works fine in the front-end and I am able to clone the input elements. My issue is whenever I am trying to get the values in PHP it always just returns 1 value. It's not getting the value of the cloned fields even if the name is something like pl_weight[] | $_POST["pl_weight"] the array content is always 1 even for example I cloned the fields 5 times. Not sure if I am doing something wrong here.
I am using AJAX to submit the form.
EDIT:
I think this
var form_data = $(this).serializeArray();
is having issues getting the cloned elements

Related

Form contents are printed outside of the form while using PHP tag

I have created a table for category which fetches category data from database. The table have a column having icon. upon clicking that icon , a form pops up to edit name of that particular category.i used display:none for form id , but only form is being hidden. contents inside form(input,button,etc) are being displayed and when i click icon a complete blank form pops up because contents are already displayed outside of the form before clicking icon.
here's the part of the code:
HTML
<div class="category-table">
<table border="1px">
<thead>
<tr>
<th>Category ID</th>
<th>Category Name</th>
<th>Action</th>
</tr>
</thead>
<?php
require("../PHP/connection.php");
$select="SELECT *from category_details";
$result=mysqli_query($con,$select);
$num_rows= mysqli_num_rows($result);
if($result){
if($num_rows>0){
while($row=$result->fetch_assoc()){
$id = $row["category_id"];
$catname = $row["category_name"];
echo "
<input type='checkbox' id='changecatcb' onclick='changecatfun()'>
<div class='changecat'>
<form id='changecatform' action='../HTML/AdminPanelChange.php' method='POST'>
<label for='changecatcb'><i class='fas fa-times'></i></label>
<p>Enter new name:</p>
<input type='text' value=".$catname.">
<button type='submit' name='changecatbutton'>Save Changes</button>
</form>
</div>
</div>
<tr>
<td>".$id."</td>
<td>".$catname."</td>
<td>
<label for='changecatcb'>
<i class='fa fa-edit' aria-hidden='true' style='color:green'></i>
</label>
</td>
</tr>
";
}
}
else
echo "<p> No Categories in Database </p>";
}
}
else
echo "<p> Can not run query </p>";
?>
</table>
</div>
JS
function changecatfun(){
var form = document.getElementById('changecatform');
var checkbox = document.getElementById('changecatcb');
if(checkbox.checked == true){
form.style.display='block';
}
else{
form.style.display='none';
}
}
CSS
.changecat form{
position: absolute;
background-color: white;
box-shadow: 0 0 10px 5px #555;
height: 5%;
width: 50%;
left: 25%;
display: none;
}
but contents are being printed inside form exactly like i want if i put the same code outside PHP tag like this:
works outside PHP tag
<input type='checkbox' id='changecatcb' onclick='changecatfun()'>
<div class='changecat'>
<form id='changecatform' action='../HTML/AdminPanelChange.php' method='POST'>
<label for='changecatcb'><i class='fas fa-times'></i></label>
<p>Enter new name:</p>
<input type='text' value='.$catname.'>
<button type='submit' name='changecatbutton'>Save Changes</button>
</form>
</div>
and yes, when i use PHP tag and inspect code in browser the form tag ends before form-contents like this:
<div class="changecat">
<form id="changecatform" action="../HTML/AdminPanelChange.php"method="POST" style="display: block;"></form>
<label for="changecatcb"><i class="fas fa-times"></i></label>
<p>Enter new name:</p>
<input type="text" value="Clothing">
<button type="submit" name="changecatbutton">Save Changes</button>
</div>
I am a beginner and this is the first time i am asking question in here. any help would be appreciated. Thank you!
This has nothing to do with PHP.
You are trying to make input and div elements children of a table element, which is not allowed.
Using a markup validator would have highlighted this error.
If you want those element inside a table then they must be inside a td or th element that is, in turn, inside a tr element.

.php file won't display form data

I'm trying to change my "Submit" button style when a user clicks on it upon submitting the form.
The action attribute calls PHP file, but the actual data doesn't display until I remove onSubmit attribute from my form. Then I can't use sendBtn() function to change the style of the button.
Pseudo-class option is not good, because it would change the style even if the form is empty.
Any ideas?
PS. I'm on local server with MAMP and using Dreamweaver for editing.
<form class="customform" method="post" action="emailOnServer.php" method="post" onSubmit="return sendBtn();" autocomplete="on" >
<div class="s-12" onClick="formFocus()"><input id="imie" name="imie1" placeholder="Twoje imię" type="text" required </input></div>
<div class="s-12" onClick="formFocus()"><input id="email" name="email1" placeholder="Twój e-mail" type="email" required </input></div>
<div class="s-12" onClick="formFocus()"><textarea placeholder="Wiadomość" id="pole" rows="5" style="resize:none;" required></textarea </input></div>
<div class="custom2" style="width: 34%; float: right;" ><input id="se" type="submit" value="Wyślij" style="background-color:#92c500; color: white; border-color:#6C0;" ></input> </div>
<div class="custom1" style="width: 65%;" ><button id="resetButton" onclick="cleanBtn()" type="reset" style="background-color: #808080; color: white; border-color:#066; border-radius:2px;">Wyczyść </button></div>
<img id="tick123" src="img2/green-tick-icon-0.png" style="display: none; float:right; position:absolute; right:1%; top:86%; padding:0; margin:0; width: 28px; height: 28px;"/>
<img id="tick1234" src="img2/green-tick-icon-0.png" style="display: none; position:absolute; left:58%; top:86%; padding:0; margin:0; width: 28px; height: 28px;"/>
</form>
<!-- more code to change form style on focus -->
function sendBtn() {
if ( document.getElementById('email').value.indexOf("#")> 0 &&
document.getElementById('email').value.indexOf(".")> 2 &&
document.getElementById('imie').value != 0 &&
document.getElementById('email').value != 0 &&
document.getElementById('pole').value != 0){
document.getElementById('se').style.backgroundColor = "#00283A";
document.getElementById("tick123").style.display="block";
document.getElementById('se').value="Wysłano";
document.getElementById('email').disabled=true;
document.getElementById('imie').disabled=true;
document.getElementById('pole').disabled=true;
return true;}}
It's from a free template and I know I should've used css stylesheets to make it more readable
This is emailOnServer.php file:
<body>
Hello User
<?php $name = $_POST['imie1'];
echo $name; ?>
</body>
First, your HTML have some errors, e.g.:
<input id="imie" .... type="text" required </input>
// look here ^
// the tag is not closed correctly
should be
<input id="imie" name="imie1" placeholder="Twoje imię" type="text" required />
Anyway, if you need to remove the onsubmit attribute, you can do something like this
<form name="myform" ...>
...
</form>
then, the js
var form = document.forms.myform;
form.onsubmit = function(){
// do stuff
document.getElementById('se').style.backgroundColor = "#00283A";
// ...
}
This jsfiddle has an example code for your requirements. The form elements was simplified.

How to get my form submitted via jQuery/ajax?

I'm trying to submit a form via jquery so that the whole page won't reloads. I'm following the instruction on jQuery.post() guide but so far it's not working. Here's what I'm looking for to complete this task.
Submit the form to a ColdFusion proxy page and from their it will send the data as json via CFHTTP.
During the process of submitting the form, show a progress gif or status.
Somehow, hide or remove the form off of the page.
Show a success or thank you message on the page where the form used to be.
So far the form I have did not even find the values from the input. The error says that "TypeError: $form.find(...).value is not a function". Below is my JavaScript code thus far:
$(function(){
$("##frmComment##").submit(function(event){
event.preventDefault();
$("##submitResponse").append('<img src="http://st2.india.com/wp-content/uploads/2014/07/ajax-loader.gif" class="progressGif">');
// Cache $form, we'll use that selector more than once
var $form=$(this);
var data = $form.serialize(); //get all the data of form
//post it
$.post(
"/customcf/knowledgeOwl/proxyPost-KB.cfm",
data,
//console.log(response),
function(response){
// Success callback. Remove your progress gif, eg:
//$('body').removeClass('in-progress');
console.log(response);
// Remove the spining gif from the div
$("##submitResponse img:last-child").remove();
//Remove the feedback form
$("##frmComment").remove();
$form.fadeOut('slow', function(){
//Add response text to the div
$("##submitResponse").append("<h6>Thank you for your feedback.</h6>");
$("##submitResponse").html(response).fadeIn('slow');
});
});
});
})
Here's the project I've setup in JSFiddle. And here's the form.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<form data-abide id="frmComment">
<div class="row">
<div class="large-12 medium-12 columns">
<div class="row" data-equalizer>
<div class="large-4 medium-4 columns">
<div class="row">
<div class="large-12 columns">
<label>
<input type="text" placeholder="Name" name="name" required>
</label>
<small class="error">Name is required and must be a string.</small>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<label>
<input type="text" placeholder="Email" name="mailfrom" required pattern='.*#.*\..{3}|.*#.*\..{2}'>
</label>
<small class="error">An email address is required.</small>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<div class="g-recaptcha" data-sitekey="6LfjNwITABCDPbDHdC5wx6HXRmXtqO3pgUItl-E"></div>
<noscript>
<div style="width: auto; height: 462px;">
<div style="width: auto; height: 422px; position: relative;">
<div style="width: auto; height: 422px; position: absolute;">
<iframe src="https://www.google.com/recaptcha/api/fallback?k=6LfjNwITABCDPbDHdC5wx6HXRmXtqO3pgUItl-E" frameborder="0" scrolling="no" >
</iframe>
</div>
</div>
<div style="border-style: none; bottom: 12px; left: 25px; margin: 0px; padding: 0px; right: 25px; background: ##f9f9f9; border: 1px solid ##c1c1c1; border-radius: 3px; height: 100px; width: 300px;">
<textarea id="g-recaptcha-response" name="g-recaptcha-response" class="g-recaptcha-response" style="width: 280px; height: 80px; border: 1px solid ##c1c1c1; margin: 10px; padding: 0px; resize: none;"></textarea>
</div>
</div>
<br /><br />
</noscript>
</div>
</div>
</div>
<div class="large-8 medium-8 columns">
<div class="row">
<div class="large-12 columns">
<textarea id="message" name="message" placeholder="Leave a comment...we love feedback!" rows="5" required></textarea>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<button type="submit" class="tiny right button">Submit</button>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<div id="submitResponse"></div>
Okay, with some help, I managed to get the jQuery post to send the data to my proxyPost-KB.cfm page but it error out (505) when it hits that page. This is what I have in my proxyPost-KB.cfm page. None of the logs I setup in this CFM page is even get executed either.
<!---
Make the proxy HTTP request using. When we do this, try to pass along all of the CGI information that was made by the original AJAX request.
--->
<cflog text="CGI: #cgi#" type="Information" file="CGIparameters">
<cfhttp url="https://app.kb.com/api/head/comment.json" method="post" timeout="15" throwonerror="true">
<!---<cfhttpparam type="body" name="data"value="#serializeJSON(jsonString)#" />--->
<cfhttpparam type="url" name="_authbykey" value="56ec1f1232131c78636142d6">
<cfhttpparam type="url" name="project_id" value="55c4ffd123131c527e294fe6">
<!---<cfhttpparam type="url" name="article_id" value="#artID#">
<cfhttpparam type="url" name="content" value="#form.message#"/>
<cfhttpparam type="url" name="public_name" value="#form.name#"/>
<cfhttpparam type="url" name="public_email" value="#form.mailfrom#"/>--->
<cfhttpparam type="url" name="status" value="pending"/>
<!--- Pass along any URL values. --->
<cfloop item="strKey" collection="#URL#">
<!---<cfhttpparam type="url" name="public_name" value="#URL[strKey]#" />
<cfhttpparam type="url" name="public_email" value="#URL[strKey]#" />--->
<cflog text="URL: #URL[strKey]#" type="Information" file="CGIparameters">
</cfloop>
</cfhttp>
<!---
Get the content as a byte array (by converting it to binary,
we can echo back the appropriate length as well as use it in
the binary response stream.
--->
<cfset binResponse = ToBinary(ToBase64( objRequest.FileContent )) />
<!--- Echo back the response code. --->
<cfheader statuscode="#Val( objRequest.StatusCode )#" statustext="#ListRest( objRequest.StatusCode, ' ' )#" />
<!--- Echo back response legnth. --->
<cfheader name="content-length" value="#ArrayLen( binResponse )#" />
<!--- Echo back all response heaers. --->
<!---<cfloop item="strKey" collection="#objRequest.ResponseHeader#">
<!--- Check to see if this header is a simple value. --->
<cfif IsSimpleValue( objRequest.ResponseHeader[ strKey ] )>
<!--- Echo back header value. The cfheader tag generate the error "Complex object types cannot be converted to simple values"--->
<cfheader name="#strKey#" value="#objRequest.ResponseHeader[ strKey ]#" />
<cflog text="IsSimpleValue: #strKey#" type="Information" file="debugCFLoop">
</cfif>
</cfloop>--->--->
<!---
Echo back content with the appropriate mime type. By using
the Variable attribute, we will make sure that the content
stream is reset and ONLY the given response will be returned.
--->
<cfcontent type="#objRequest.MimeType#" variable="#binResponse#" />
Here's an example to do what you describe:
$("#frmComment").submit(function(event) {
event.preventDefault();
// Form has been submitted - now show your progress gif, eg:
// $('body').addClass('in-progress');
// or maybe:
// $('.spinner').show();
// etc - CSS can be whatever you want
// Cache $form, we'll use that selector more than once
var $form=$(this);
// Serialize all input from the form
var data=$form.serialize();
// Post it
$.post(
"your-proxy-url",
data,
function(response) {
// Success callback. Remove your progress gif, eg:
// $('body').removeClass('in-progress');
console.log(response); // show the proxy response on your console
// Now hide the form
$form.fadeOut('slow', function() {
// And show a result once it's gone
$(".result").html(response).fadeIn('slow');
});
}
);
});
I think you could use this code inside the $( "#frmComment" ).submit(function( event ) { function:
event.preventDefault();
var data = $('#frmComment').serialize(); //get all the data of form
var url = "yourUrl.php";
$.ajax({
type: "POST",
url: url,
data: data,
dataType: "json",
success: function(data) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handing here');
}
});
The PHP 'yourUrl' will recive the form inputs (you could use var_dump($_POST); to see the structure.

Getting updated values in ng-repeat Angular JS

I am using ng-repeat, which is getting values from my db and putting it. Now i insert these values into input text which i update. Now i have a save button, which saves the updated values. I am not getting the updated values when i press the save button. Please guide me through this.
<div ng-controller="education" ng-init="getEducationDetails();">
<div class="col-md-12">
<div class="row" ng-repeat="values in education"
style="margin-left: 20px; margin-right: 20px; margin-top: 10px;">
<div class="col-md-6">
<h4>
<small>Degree</small>
</h4>
<input type="text" id="educationDegree" name="educationDegree"
value="{{values.education_degree}}" style="width: 90%;" />
</div>
<div class="col-md-6">
<h4>
<small>Year</small>
</h4>
<input type="text" id="educationYear" name="educationYear"
value="{{values.education_year}}" style="width: 100%;" />
</div>
<div class="col-md-12" style="margin-top: 10px;">
<h4>
<small>University</small>
</h4>
<input type="text" id="educationUniversity"
name="educationUniversity"
value="{{values.education_university}}" style="width: 100%;" />
</div>
</div>
</div>
<div class="col-md-12" style="margin: 20px;">
<button ng-click="educationSave();" class="btn btn-default">Save</button>
</div>
</div>
on educationSave() i save the values. But when i get the education array in the educationSave() method, i get the old array. How can i get the updated array, after i adjust some of the input types
Here is how i get the values:
$scope.getEducationDetails = function()
{
$http({
method : 'GET',
url : '/getEducationDetails'
}).success(function(data, status, headers, config) {
$scope.education = data.resultSet;
alert($scope.education);
}).error(function(data, status, headers, config) {
});
};
Here is my controller method:
$scope.educationSave = function() {
var educationArray = JSON.stringify($scope.education);
//I then save this educationArray
};
The problem is that you are not using ng-model to bind your actual input value to controller. From documentation:
HTML input element control. When used together with ngModel, it provides data-binding, input state control, and validation.
Try something like this in your markup for each input:
<input type="text" id="educationDegree" name="educationDegree"
ng-model="values.education_degree" style="width: 90%;" />
See little Demo

Sending parameters to web page using javascript/jQuery without HTML Form Submit?

I have two web pages A.html and B.html(Thrid party provided so i dont have access for its code). Where A.html has form and onClick of submit the data is sent to B.html with method="post" and target="chat".
As soon as B.html receives A.html request a pop up for Chat window starts. But now i dont want the user to fill form every time and submit to start support of chat and i want to accomplish this using javascript/jquery only without asking user to fill in the HTML form.
Below is my form code in html:
<label for="sample" style="display: none;">sample</label>
<form name="sample" id="sample" method="post" target="chat" >
<div class="form_elem">
Name : <input type="text" id="vName" name="vName" value=""> <div class="error">*</div>
Mobile Number : <input type="text" id="mobile" name="21512" value=""> <div class="error">*</div>
Connection Type : <select name="21524" id="state">
<option value="0" selected="selected">Select</option>
<option value="24">PF</option>
<option value="25">PD</option>
</select> <label> </label>
<input type="button" style="border-width: 0px; margin-right: 10px; cursor: pointer;" onclick="javascript:return Submit_Data();" value="Submit" name="btnSubmit" class="submit">
<input type="button" style="border-width: 0px; margin-right: 10px; cursor: pointer;" onclick="javascript:return Clear_Click('old')" value="Clear" name="btnclear" class="reset">
</div>
</form>
function Submit_Data()
{
window.open("Live Chat", "chat", "height=" + ChatWindow_Height + ", width = " + ChatWindow_Width);
var url = "B.Html";
var form = document.getElementById("sample");
form.action = url;
form.submit();
}
Assuming data necessary to be sent is hard coded now like. var name='pawan',mobile='9930667xxx',state='24'. How to write javascript/jQuery that doesnot involve any html form and submits data directly to B.html ?
Thanks.
try this
$.ajax({
async:true,
type: "POST",
dataType: "json",
contentType: "application/x-www-form-urlencoded",
url: "pageB",
data:"para="+variable,
beforeSend: function,
success:function,
timeout:10000,
error:function
});
para=variable para is the post in the server $_POST['para']
http://api.jquery.com/jquery.ajax/

Categories

Resources