How to add javascript data to mysql? - javascript

I have problem how to add this javascript data to mysql database?
<script type="text/javascript">
var count = 0;
function countClicks() {
count = count +1 ;
document.getElementById("likes").innerHTML = count;
}
</script>
<input type="button" value="Like "onclick="javascript:countClicks();" alt="alt text"/>
<div id="likes">0</div>

You need to use mysql-real-escape-string while inserting your js code to mysql db. Assign your code string to a variable and use mysql-real-escape-string while inserting db. Example usage;
HTML:
<form action="save_code.php" method="POST">
<table>
<tr>
<td>Code</td>
<td><textarea name="code"></textarea></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Save" value="Save"/></td>
</tr>
</table>
</form>
PHP: save_code.php
// Comment out this for real test
//$jsCode = $_POST['code'];
//Assign js code string to variable
$jsCode = '<script type="text/javascript">
var count = 0;
function countClicks() {
count = count +1 ;
document.getElementById("likes").innerHTML = count;
}
</script>
<input type="button" value="Like "onclick="javascript:countClicks();" alt="alt text"/>
<div id="likes">0</div>';
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
or die(mysql_error());
$query = "INSERT INTO your_table(id, code) VALUES('', mysql_real_escape_string($jsCode))";
mysql_query($query);

You have 2 ways to do:
1- AJAX
You must make a SaveData.php for example and make a ajax Post to this page and then insert in database.
2- JS to PHP
In the same page you do this
Insert into TABLE (count) VALUES (".<script> write(count); </script>.");

Related

Submiting Javascript variable to PHP via HTML Form

I have these below codes which give user option to reserve a seat according to their choice. These 3 mentioned below are difficulties that I am facing I need help.
To send the total value of a variable named total from Javascript to PHP
To send the total number of selected seats which are being hold by a variable called results from Javascript to PHP
How to make a Reserve Now button inactive if a user did not select any seat from checkbox.
These below are my codes.
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Seat(s)</title>
</head>
<body>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (isset($_POST['submit'])) { //Seat Reserve
require 'action_page.php';
}
elseif (isset($_POST[''])) { //Cancel
require 'mypage.php';
}
}
//
$parameter = "this is a php variable";
echo "var myval = foo(" . parameter . ");";
?>
?>
<h2>Please choose a seat to book</h2>
<form action="index.php" method="post">
<input type="checkbox" name="vehicle" id="A1" value="100">$100<br>
<input type="checkbox" name="vehicle" id="A2" value="65"> $65<br>
<input type="checkbox" name="vehicle" id="A3" value="55"> $55<br>
<input type="checkbox" name="vehicle" id="A4" value="50"> $50<br>
<p id="demo">
Selected Seat(s)
<br>
<span id="selected-seats"></span> <!-- container for selected seats -->
<br>
Total: <span id="total-container"></span> USD
<button type="submit" class="btn btn-primary" name="submit">Reserve Now</button>
</p>
</form>
<script>
const selections = {};
const inputElems = document.getElementsByTagName("input");
const totalElem = document.getElementById("total-container");
const seatsElem = document.getElementById("selected-seats");
for (let i = 0; i < inputElems.length; i++) {
if (inputElems[i].type === "checkbox") {
inputElems[i].addEventListener("click", displayCheck);
}
}
function displayCheck(e) {
if (e.target.checked) {
selections[e.target.id] = {
id: e.target.id,
value: e.target.value
};
}
else {
delete selections[e.target.id];
}
const result = [];
let total = 0;
for (const key in selections) {
result.push(selections[key].id);
total += parseInt(selections[key].value);
}
totalElem.innerText = total;
seatsElem.innerHTML = result.join(",");
//window.alert(result); //Hold Number of Seats Selected.
//window.alert(total); //Hold Total Cost of Selected Seats.
}
var myval = foo("this is a php variable"); // I tried to take this value and output it but it didn't work out.
$.ajax({
type: 'POST',
url: 'action_page.php',
data: {'variable': total},
});
</script>
</body>
</html>
action_page.php
<html>
<head>
<title>Seats Feedback</title>
</head>
<body>
<?php
echo "<br>";
$myval = $_POST['variable'];
print_r($myval);
?>
Looking forward to hear from you guys.
When you're not doing AJAX, posting data to a PHP script the old fashioned way is a matter of:
setting the action attribute on a <form> element to point to the destination PHP script URL
ensuring your form's <input> elements contain all of the data you want to post
adding a submit button to the form
For step 1, currently, your form says to send the post request to itself. This is totally fine (you can use a <?php block ?> like you're doing to determine whether to show a success confirmation or a blank form depending on the contents of $_POST, but I'm guessing your intention is to ultimately send the data over to action_page.php. I made that the action target and removed all of the PHP from your index.
As for step 2, your total isn't currently in an <input> element and won't be posted. I created an invisible total element for this purpose: <input type="hidden" name="total" id="hidden-total" value="0"> and added a couple lines to the script to retrieve this element and set its value whenever your total is recalculated. You could combine the two total elements and style one to look and be non-editable (exercise for the reader).
Another problem relating to step 2 is that you have four different elements with the name vehicle. Only one of these name/value pairs will be posted, so I updated these elements to use unique names so they'll all be sent.
Step 3, making sure you have a submit button, you've already done successfully.
To verify it's working, you can var_dump($_POST) on the receiving PHP script to see the results of the post request or retrieve a specific value by name with e.g. $_POST['total']. At this point, your PHP script can go ahead and parse/validate/sanitize the post data, render proper response output, do a redirect, and/or do whatever else needs to be done, such as writing to a database.
Here's the full code:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Seat(s)</title>
</head>
<body>
<h2>Please choose a seat to book</h2>
<form action="action_page.php" method="post">
<input type="checkbox" name="vehicle-a1" id="A1" value="100">$100<br>
<input type="checkbox" name="vehicle-a2" id="A2" value="65"> $65<br>
<input type="checkbox" name="vehicle-a3" id="A3" value="55"> $55<br>
<input type="checkbox" name="vehicle-a4" id="A4" value="50"> $50<br>
<input type="hidden" name="total" id="hidden-total" value="0">
<p id="demo">
Selected Seat(s)
<br>
<span id="selected-seats"></span> <!-- container for selected seats -->
<br>
Total: <span id="total-container"></span> USD
<button type="submit" class="btn btn-primary" name="submit">Reserve Now</button>
</p>
</form>
<script>
const selections = {};
const inputElems = document.getElementsByTagName("input");
const totalElem = document.getElementById("total-container");
const hiddenTotalElem = document.getElementById("hidden-total");
const seatsElem = document.getElementById("selected-seats");
for (let i = 0; i < inputElems.length; i++) {
if (inputElems[i].type === "checkbox") {
inputElems[i].addEventListener("click", displayCheck);
}
}
function displayCheck(e) {
if (e.target.checked) {
selections[e.target.id] = {
id: e.target.id,
value: e.target.value
};
}
else {
delete selections[e.target.id];
}
const result = [];
let total = 0;
for (const key in selections) {
result.push(selections[key].id);
total += parseInt(selections[key].value);
}
totalElem.innerText = total;
hiddenTotalElem.value = total;
seatsElem.innerHTML = result.join(",");
}
</script>
</body>
</html>
action_page.php
<!DCOTYPE html>
<html lang="en">
<head>
<title>Seats Feedback</title>
</head>
<body>
<?php
echo "<pre style='font-size: 1.5em;'>"; // format debug post dump
var_dump($_POST);
?>
</body>
</html>
Sample output
array(5) {
["vehicle-a1"]=>
string(3) "100"
["vehicle-a3"]=>
string(2) "55"
["vehicle-a4"]=>
string(2) "50"
["total"]=>
string(3) "205"
["submit"]=>
string(0) ""
}
As before, this isn't an industrial strength example and there is plenty of room for improvement, but hopefully it does communicate the basic idea.

Dynamic Fields js/php to MySql need to submit dynamically to the database

I can not get the values from the javascript add row to go dynamically as a row into MySql only the form values show up as the form below as one row. I made it as an array, but no such luck, I have tried this code around a multitude of ways. I don't know what I am doing wrong, kindly write out the correct way.
My code for example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Dynamic Fields js/php to MySql need to submit dynamically to the database</title>
<?php
require ('database.php');
?>
<script type="text/javascript">
var counter = 1;
var collector = "";
function addfields(indx)
{
var tbl = document.getElementById('table_id');
var newtr = document.createElement('tr');
counter = counter + indx;
newtr.setAttribute('id','tr'+counter);
newtr.innerHTML = '<td><input type="checkbox" name="checkb'+counter+'" id="checkb'+counter+'" value="'+counter+'" onclick="checkme('+counter+')"></td><td><input type="text" name="text1[]"></td><td><textarea name="textarea1[]"></textarea></td>';
tbl.appendChild(newtr);
}
function checkme(dx)
{
collector += dx+",";
}
function deletetherow(indx)
{
var col = collector.split(",");
for (var i = 0; i < col.length; i++)
{
var remvelem = document.getElementById('tr'+col[i]);
var chckbx = document.getElementById("checkb"+col[i]);
if(remvelem && chckbx.checked)
{
var tbl = document.getElementById('table_id');
tbl.removeChild(remvelem);
}
}
}
</script>
</head>
<body>
<form enctype="multipart/form-data" id="1" style="background-color:#ffffff;" action="<?php echo $_SERVER['PHP_SELF']; ?>"></form>
<table id="table_id" >
<tr id="tr1" class="trmain">
<td>
</td>
<td>
<input type="text" name="text1[]">
</td>
<td>
<textarea name="textarea1[]"></textarea>
</td>
</tr>
</table>
<input type="button" value="Add" onClick="addfields(1);" />
<input type="button" value="Delete" onClick="deletetherow()" />
<input type="submit" value="Send" id="submit" name="submit"/>
<?php
if(isset($_POST['submit'])) {
for ($i=0; $i < count($_POST['text1']); $i++ )
{
$ced = stripslashes($_POST['text1'][$i]);
$erg = stripslashes($_POST['textarea1'][$i]);
$bnt = mysql_query("INSERT INTO tablename (first, second) VALUES ('$ced', '$erg')")or
die ('Error: '. mysql_error() );
}
}
?>
</body>
</html>
Here is a perma link for anyone: Dynamic Fields js/php to MySql need to submit dynamically to the database
If you are seeking answer to this subject, then Sean was right, it actually never overwrote the other as just first inputs submitted to MySQL as others ignored as wasn't part of loop. His innerhtml dynamic with loop is working.
If you want the code, its' above-edited or take from perma. There are not a whole lot of these working examples on the web, now you can go further with jQuery with this and getting more popular.

Issue passing value between javascript and php - Popup PHP Javascript HTML

I am trying to incorporate a popup into my project. It works up until I try and pass a value from javascript to the php script. I have included a link to the example I used and link to the original script. There were slight changes made to the original script. The area I am having an issue with is marked with a ---->
full script can be found here:
http://www.webdeveloper.com/forum/showthread.php?279111-Contact-form-popup-window
working example can be found here:
http://ilolo.ru/wd/contact_form/
I have the following in hello.html
<form id='form1' style='width: 1100px'>
<table>
<th>Email</th>
<th>Options</th>
<tr>
<td>
<input type='text' id='email1' size='25' value='bob#mail.com'>
</td>
<td><a id='1' href='#null' class='contactus'><img src= 'images/emailbutton.jpg' title='Email' border='0' height='24' width='24'></img></a>
</tr>
</table>
</form>
The following js is in a .js that I reference in my html.
I use the following since I have more than one form. Just showed one form in my example.
The alert below works....shows the correct email address when I click on the image link in the html.
function findCenter(obj) {
var deltaX = parseInt(obj.css('padding-left')),
deltaY = parseInt(obj.css('padding-top'));
obj.css('left', $(window).width() / 2 - obj.width() / 2 - deltaX + 'px').css('top', $(window).height() / 2 - obj.height() / 2 - deltaY + 'px');
}
$(document).ready(function () {
$('.contactus').click(function () {
var element = $(this);
var J = element.attr('id');
var email = document.getElementById('email'+J).value;
alert(email);
$('#result').html('<h3>Loading</h3>').css('display', 'block');
findCenter($('#result'));
$.get('email.php', function (data) {
$('#result').html(data);
findCenter($('#result'));
$('#snd').click(function () {
var subject = document.getElementById('subject').value;
var addy = document.getElementById('addy').value;
var comments = document.getElementById('comments').value;
$('#result').append('<br /><br /><div><i>Sending...</i></div>');
$.post('lbi_email.php',{mode: 'snd', subject: subject, addy: addy, comments: comments},function(data){
$('#result').html(data);
findCenter($('#result'));
});
});
});
});
});
email.php
This value below is not getting sent by the javascript and the input value=$email is not written correctly (I think)
<?php
include( 'connection.php');
function showForm(){
$email=$_POST[ 'email'];
echo '<form name="mf" id="mf" action="" method="post">
<h2>Send Email To Customer</h2><br />
<p><label>Address :</label><input type="text" size="35" name="addy" id="addy" value="'.$email.'"/></p>
<p><label>Subject : </label><input type="text" size="35" name="subject" id="subject" value=""/></p>
<label>Message:</label><textarea style="width: 100%;" cols="20" rows="10" id="comments" name="comments"></textarea>
<p><img src="submitbutton.jpg" title="Submit Email" border="0" height="25" width="75"></img></p></form>';
}
function sndForm(){
/* here goes checking data and so on... then sending if everything 's good and sending done show message to the user*/
echo '<h3>Everything\'s cool.
<br />
<br />Viva Cuba!</h3>
<script type="text/javascript">
setTimeout(\'$("#result").fadeOut("fast")\',3000);
</script>';
}
/*---------------------------------------------------------------------*/
$mode=(!empty($_GET['mode']))?$_GET['mode']:$_POST['mode'];
switch($mode)
{
case 'snd':sndForm();break;
default: showForm();break;
}
?>
In your javascript you are sending literal email instead of your email value -
$.post('email.php',{mode: 'snd', email: 'email'},function(data){
Change this to -
$.post('email.php',{mode: 'snd', email: email},function(data){
In your php code you have a variable scope issue - $email is outside the scope of your function
$email=$_POST[ 'email'];
function showForm(){
echo $email;
Try setting it inside
function showForm(){
$email=$_POST[ 'email'];
echo $email;
Finally, you have $email inside single quotes-
echo '<form name="mf" id="mf" action="" method="post">
<h2>Send Email To Customer</h2><br />
<input type='text ' value='$email '/>
...
Need to update to
echo '<form name="mf" id="mf" action="" method="post">
<h2>Send Email To Customer</h2><br />
<input type="text" value="'.$email.'"/>
...
Additionally, it looks like when you are submitting the for you are not sending the comments textarea, so you probably need to add that as well.
$('#snd').click(function () {
$('#result').append('<br /><br /><div><i>Sending...</i></div>');
var comments = document.getElementById('comments').value;
$.post('email.php',{mode: 'snd', email: email, comments: comments},function(data){
$('#result').html(data);
findCenter($('#result'));
});
});
Edit
You need to add the email value to your $.get() -
$.get('email.php', email: email, function (data) {
and then change it to $_GET['email'] in your php -
function showForm(){
$email=$_GET[ 'email'];

accessing selected radio button value inside iframe [duplicate]

This question already has answers here:
Accessing Elements Inside iframe and body Tags with JavaScript
(2 answers)
Closed 10 years ago.
I write the code. Where I am trying to write a form which is having a long list of radio button content inside 'iframe' like below:
<form name="iframeform" method="POST" action="http://localhost/cgi-bin/run">
<tr>
<td><iframe id="macList" src="http://localhost/macinfo" style="width:1000px;height:160px">
</iframe></td>
</tr>
<tr>
<input type="hidden" name="macaddr" value="">
<td><input type="submit" name="macselect" value="Continue" id="stdbtn" onclick="getIframeContent()"></td>
</tr>
</form>
'iframe' is pointing to macinfo page is having code like below:
<html>
<body>
<table>
<tr>
<td><input type=radio name=mac value=E8:B7:48:7B:C0:4A>abc.example.com</td>
</tr>
<tr>
<td><input type=radio name=mac value=00:17:08:5A:81:CF>xyz.cisco.com</td>
</tr>
....
</table>
</body>
</html>
How can I write "getIframeContent()" function to fetch the value of selected radio button? please help..
Long story short. To access iframe document use .contentWindow.document, i.e.:
document.getElementById('macList').contentWindow.document
And an example code:
<html>
<head>
<script type="text/javascript">
function getIframeContent(){
var myIFrame = document.getElementById('macList');
var myIFDoc = myIFrame.contentWindow.document;
var myRadios = myIFDoc.getElementsByName("mac");
var checkedItemValue = "";
for(var i=0; i<myRadios.length; i++) {
if (myRadios[i].checked) {
checkedItemValue = myRadios[i].value;
}
}
if (checkedItemValue) {
alert(checkedItemValue);
} else {alert('Select address');}
}
</script>
</head>
<body>
<iframe id="macList" src="..."
style="width:600px;height:160px">
</iframe>
<input type="submit" onclick="getIframeContent();">
</body>
</html>
You will have to get the array of mac using document.getElementsByName and loop over them:
var allRadios = document.getElementsByName("mac");
var checkedItem;
for(var i=0; i<allRadios.length; i++) {
if (allRadios[i].checked) {
checkedItem = allRadios[i];
alert('Found checked radio button');
}
}
You could then pass checkedItem to your getIframeContent function.
Edit
You could share the checkedItem variable across two pages by using window
window.checkedItem = allRadios[i];

equivalent for request.getParameterValues() in javascript

For example in form, I've 2 or more element that have the same name like in the below code:
<form name="form1" method="post" action="saveToDb.jsp">
<span id="feedBackList">
<table>
<thead>
<tr>
<td>column1</td>
<td>column2</td>
</tr>
</thead>
<tbody>
<tr>
<td><input type=text id=field1 name=field value="firstvalueTosavetoDb"></td>
<td><input type text id="field2 name=field value="secondvalueTosavetoDb"></td>
</tr>
</tbody>
</table>
</span>
</form>
Value for this two field I want to capture and save it to database. This can be done by submit the form, and in my saveToDb.jsp file I just need to get the value by using
String[] value = request.getParameterValues("field");
loop through the array and save it to database. the problem is I don't want to submit the form because the page will be refresh. what I'm trying to achieved is, I want to use jQuery.get method and pass the value and view back the value without refresh the page and put it in my <span> tag like below code
var $p = jQuery.noConflict(){
function submitAndView(){
//here is where i should get the value
var span = document.getElementById("feedBackList");
$p.get("saveToDb",{pass the value here}, function(data){
span.innerHTML = data
});
}
the question is what is the equivalent to request.getParameterValues in JavaScipt or jQuery. p/s: the number of <input> elements is not fixed.
Could you add a name and onsubmit attribute to your form, calling a validation JS function which loops through all of the fields with the same name and constructs some type of string or array for you to easily add info to your db? e.g.:
<form name=form1 action='#' method=post onsubmit='return validateForm()'>
<fieldset>
<input type=text name='field[]' value='firstValue'>
</fieldset>
</form>
function validateForm(){
count = 0;
str = '';
for(x=0; x<document.form1.elements["field[]"].length; x++){
str += document.form1.elements["field[]"][x].value + ','
count++;
}
//submit form data

Categories