Putting a javascript code into a MySQL database - javascript

I'm editing a web program in MySQL; unfortunately, I got stuck with the following:
A smarty markup, used to display a form, has the following value:
{php}
$format = $this->get_template_vars("phone_number_format");
$values = explode("|", $this->get_template_vars("VALUE"));
$name = $this->get_template_vars("NAME");
$pieces = preg_split("/(x+)/", $format, 0, PREG_SPLIT_DELIM_CAPTURE);
$counter = 1;
foreach ($pieces as $piece)
{
if (strlen($piece) == 0)
continue;
if ($piece[0] == "x") {
$size = strlen($piece);
$value = (isset($values[$counter-1])) ? $values[$counter-1] : "";
$value = htmlspecialchars($value);
echo "<input type=\"text\" name=\"{$name}_$counter\" value=\"$value\"
size=\"$size\" maxlength=\"$size\" class=\"VOLGENDE\"/>";
$counter++;
} else {
echo $piece;
}
}
{/php}
{if $comments}
<div class="cf_field_comments">{$comments}</div>
{/if}
I need to add some javascript to this, but I cannot manage to get it working. This is the javascript that needs to be added:
$(".VOLGENDE").keyup(function () {
if (this.value.length == this.maxLength) {
$(this).next('.VOLGENDE').focus();
}
});
With this script, I am trying to make sure that the focus will be put on the next field once the maximum amount of characters in a given field is reached.
I am looking for a way to include this javascript into the MySQL database field where the PHP code mentioned above is found. If there is anybody who could help me out with this, then that would be great :)
Thanks in advance!

Related

I'm trying to use some data i pulled from a php database as information in a clickable SVG picture (javascript)

<?php
require_once('dbconn.php');
$arm = "SELECT problem, description, reason, reg_date FROM body_arm";
$result = $conn->query($arm);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo " " . $row["problem"].
" - " . $row["description"].
" - reason: " . $row["reason"].
" - TIMESTAMP:" . $row["reg_date"].
"<br/>";
}
} else {
echo "0 results";
}
$conn->close();
?>
<!--
Here I have some code for the SVG
-->
<script>
window.onload = function () {
const pieces = document.getElementsByTagName('svg');
for (var i = 0; pieces.length; i++) {
let _piece = pieces[i];
_piece.onclick = function(t) {
if (t.target.getAttribute('data-position') != null)
document.getElementById('data').innerHTML = t.target.getAttribute('data-position');
if (t.target.parentElement.getAttribute('data-position') != null)
document.getElementById('data').innerHTML = t.target.parentElement.getAttribute('data-position');
}
}
}
</script>
I have tried to use the function ob_get_contents, couldn't really get it working.
I have tried to echo the php variable to javascript like: var val = "";
As I'm starting to understand I can't really find the php variable in javascript and need to find a way around that or maybe use something like node.js to open a connection to the server with something closer to javascript? I'm a beginner by the way!
For me the solution I found was json_encode!
$example_array_variable = json_encode($example);
//Doing this in the PHP.
//Then later in the JavaScript decode it.
echo json_encode($example_array_variable);
Eureka!!

Php and ajax not returning any data from database, no errors

I have created a search using ajax and php, however when I click the search button nothing happens. There are no errors, however when I look at the network in the console it doesn't seem to be reaching searching.php as this file doesn't show up in the network. I want to be able to put the returned data from the search into seperate divs, although at the minute it isn't returning any data at all and I have no idea why.
This is my php
require_once('config1.php');
$output = '';
if(isset($_POST['search']) === true && empty($_POST['search']) === false){
$query = "SELECT a.attraction_name, a.lat, a.long, a.cost, a.image FROM zz_attractions a INNER JOIN zz_city c ON a.city_id = c.city_id WHERE c.city_name = '" . mysqli_real_escape_string(trim($_POST['search'])) . "' ";
$result = mysqli_query($conn, $query);
$count = mysqli_num_rows($result);
if ($count == 0) {
$output = 'there was no search results';
} else {
while ($row = mysqli_fetch_array($result)) {
$attraction_name = $row['attraction_name'];
$lat = $row['lat'];
$long = $row['long'];
$cost = $row['cost'];
$image = "<img src='{$row['image']}' height='100' width='100'>";
$output .= '<div>'.$attraction_name.' '.$lat.' '.$long.' '.$cost.' '.$image.'</div>';
}
}
}
This is my ajax
$('#submit').on('click', function() {
var search = $('#search').val();
if ($.trim(search) != '') { //if search is not equal to nothing - using trim allows users to type in blank space and it won't return anything
$.post('searching.php', {search: search}, function(data) {
$('#return').text(data);
});
}
});
Within the html the div id is #return. If someone could help me find out why no data is returning that would be great.

Creating a unique variable for data

Hi guys so i have created a simple comment box for my site now. It works perfectly, however the problem i am having is that i have different pages which are going to require different comment box. I cant seem to figure out how to get the comment box to be unique for every page. So right now my database holds this :
Called comments:
id
comment
comment1
comment_date
Now my idea is that everything was stored into comment, so i added comment1 for other page to store the info. However i have no clue how to edit the php file to get it to work with comment1. Any help on this would be great.
HTML:
<div class="comment_container">
<div class="comments">
<?php
include_once("comments.php");
?>
</div>
<div class="comments_form">
<table>
<tr><td><textarea id="comment_text"></textarea></td>
<td><input type="button" id="comment_process" value="Post Comment"/></td></tr>
</table>
</div>
</div>
JS:
$(document).ready(function() {
$('#comment_process').click(function() {
if ($('#comment_text').val() != "") {
$.post("comments.php?action=post", {
comment: $('#comment_text').val()
}, function(data) {
$('.comments').html(data);
$('#comment_text').val("");
});
}
});
});
PHP:
include_once("connect.php");
function convert ($date) {
$converteddate = date("F j, Y g:ia", strtotime($date." +1day"));
return $converteddate;
}
function getComments(){
$comments = "";
$sql = mysql_query("SELECT * FROM comments") or die(mysql_error());
if(mysql_num_rows($sql) == 0){
$comments = "<div class='each_comment'>There are no comments</div>";
} else {
while($row = mysql_fetch_assoc($sql)){
$comments .= "<div class='each_comment'><small><em>".convert($row['comment_date'])."</em></small><br />".$row['comment']."</div>";
}
}
return $comments;
}
function postComments($comment){
$comment = mysql_real_escape_string(strip_tags($comment));
$sql = mysql_query("INSERT INTO comments (comment, comment_date ) VALUES ('".$comment."', now())");
return true;
}
if((isset($_GET['action'])) && ($_GET['action']== "post")){
postComments($_POST['comment']);
}
echo getComments();
Thanks again for the help
DISCLAIMER
For future visitors:
Don't copy this code, as it has several issues that go beyond answering the question.
What you need to add is an identifyer for the type of comment. (Type could be replaced with something more suitable to your case like 'product', 'user', ... whatever the difference is/what they are related to)
So in your database add that new column:
comments
--------
id
comment
type
comment_date
Now you need to pass around that type through all your calls, and it shall be specified in your 'HTML'-Page (which actually is php...).
<div class="comment_container">
<div class="comments">
<?php
// specify the type needed on that page
$type = 1;
include_once("comments.php");
echo getComments($type);
?>
</div>
<div class="comments_form">
<table>
<tr><td><textarea id="comment_text"></textarea></td>
<td><input type="button" id="comment_process" value="Post Comment"/></td></tr>
</table>
</div>
</div>
<script>
// specify the type in javascript
var type=1;
$(document).ready(function() {
$('#comment_process').click(function() {
if ($('#comment_text').val() != "") {
// add the type here:
$.post("comments.php", {
comment: $('#comment_text').val(),
type: type,
action: 'post'
}, function(data) {
$('.comments').html(data);
$('#comment_text').val("");
});
}
});
});
</script>
and in comments.php:
//....some code left out here
function getComments($type){
$comments = "";
$sql = mysql_query("SELECT * FROM comments where type=$type") or die(mysql_error());
if(mysql_num_rows($sql) == 0){
$comments = "<div class='each_comment'>There are no comments</div>";
} else {
while($row = mysql_fetch_assoc($sql)){
$comments .= "<div class='each_comment'><small><em>".convert($row['comment_date'])."</em></small><br />".$row['comment']."</div>";
}
}
return $comments;
}
function postComments($comment, $type){
$comment = mysql_real_escape_string(strip_tags($comment));
$sql = mysql_query("INSERT INTO comments (comment, comment_date, type ) VALUES ('".$comment."', now(), ".$type.")");
return true;
}
if((isset($_POST['action'])) && ($_POST['action']== "post")){
postComments($_POST['comment'], $_POST['type']);
// send all the comments back to client
echo getComments($_POST['type']);
}
// moved to html-file: echo getComments($type);
NOTE
There are several issues with that code.
First don't use mysql functions. For real. Unsecure and deprecated/deleted as of php7. Use mysqli or pdo. Furthermore your sql can be hacked with sql injection. Read about prepared statements.
The general structure of that code is not very good.
Try to seperate output and formating from getting data.
For example it would be much better if a function called 'getComments' only would get the comments from the database, then let others decide what to do with that data. The less one function does the better.
Please read about coding styles, maybe start learning object oriented programming.
I hope this still helps you to get a clue of where to go!

PHP echo is printing JavaScript alert code on page

I was making a form for inserting products for admin in an e-commerce project. During validation of the form data, I tried to check if the form data is empty or not.
Thus I introduced an if statement and checked the values of all the parameters passed from the form and in the if block wrote an echo statement.
Here is my code:
<? php
//text variables
if(isset($_POST['insert_product'])){
$product_title = $_POST['product_title'];
$product_cat = $_POST['product_cat'];
$product_brand = $_POST['product_brand'];
$product_price = $_POST['product_price'];
$product_desc = $_POST['product_desc'];
$product_status = 'on';
$product_keywords = $_POST['product_keywords'];
//images variables
$product_img1 = $FILES['product_img1']['name'];
$product_img2 = $FILES['product_img2']['name'];
$product_img3 = $FILES['product_img3']['name'];
//temp names
$temp_name1 = $FILES['product_img1']['tmp_name'];
$temp_name2 = $FILES['product_img2']['tmp_name'];
$temp_name3 = $FILES['product_img3']['tmp_name'];
//validation and insertion query
if($product_title == '' OR $product_cat == '' OR $product_brand == '' OR $product_keywords == '' OR $product_img1 == '' OR $product_price == ''){
echo"<script>alert('you have not entered all the values')</script>";
exit();
}
}
?>
It is producing an output like
(...alert('you have not entered all the values');"; exit();} } ....)
Please help me to solve this problem.
I am using Sublime text and checked the same in Notepad++ but it’s giving the same error.
This works fine for me. Try iterating through $_POST in a loop, checking values that way. It'll condense your code and make things easier to read in the future:
<?php
if (isset($_POST)) {
foreach ($_POST as $key => $value) {
if (!isset($_POST[$key]) || $value == "") {
echo "<script> alert('you have not entered all the values'); </script>";
exit;
}
}
}
That said, you should try to preserve $_POST and use a cleaned string if you're using data provided by the user:
<?php
if (isset($_POST)) {
// Clean a string, making it safe for using with a database.
function clean_string($string) {
global $mysqli;
$string = $mysqli->real_escape_string($string);
stripslashes($string);
return $string;
}
foreach ($_POST as $key => $value) {
if (!isset($_POST) || $value == "") {
echo "<script> alert('you have not entered all the values'); </script>";
exit;
}
// If you're going to be using this $_POST data with a database you should also
// clean the strings before using them in any way.
$Data = new stdClass();
foreach ($_POST as $key => $value) {
if (isset($_POST[$key]) && $_POST[$key] !== "") {
$Data->$key = clean_string($value);
}
}
}
// All of the $_POSTed items are set and cleaned for use. Do what you will with them below.
}
try the following, *note semicolon
echo "<script language='javascript'>alert('thanks!');</script>";
echo"<script>alert('you have not entered all the values');</script>";
use this .....u r forgetting semicon after )

PHP validation to check if record exists

I'm trying to create a validation for a form. When a user fills out the form, it is supposed to run a set of queries. The first is to check if a records already exists in the table. If it does exist, then it doesn't need to run the the next 2 queries, which are to INSERT and UPDATE.
I'm not sure what I am doing wrong, but the table already has an existing record. After checking the table, it still runs the INSERT and UPDATE queries. They should not fire. It should not do anything.
Here is my code: * I'm starting my code from the for loop, which is just taking an array of BOL numbers and CONTAINER numbers that the user manually selected. I exploded the array, but I will not show that code as I do not think it is necessary to show in this case *
<?php
for($i = 0; $i < $count; $i++)
{
$bolService = $bolArray[$i];
$conService = $conArray[$i];
$checkService = "SELECT * FROM import_service WHERE bol = '" . $bolService . "' AND container = '" . $conService . "'";
$checkSerRes = mysql_query($checkService);
$checkSerNum = mysql_num_rows($checkSerRes);
if($checkSerNum > 0)
{
$successService = false;
}
elseif($checkSerNum = 0)
{
$sql_query_string = mysql_query
("INSERT INTO import_service (bol, container) VALUES ('$bolService','$conService')");
$updateService = mysql_query ("UPDATE import_dispatch_details SET SERVICE = 'Y'
WHERE BOL_NUMBER = '$bolService' AND CONTAINER = '$conService')");
$successService = true;
}
}
// javascript fires an ALERT message in this next set of code
if($successService = true)
{
echo ("<script language='javascript'>
window.alert('Record has been saved')
window.location.href=''
</script>");
}
// if checkSerNum > 0, then it should skip the INSERT and UPDATE and fire the code below
elseif($successService = false)
{
echo ("<script language='javascript'>
window.alert('There was an error saving the record')
window.location.href=''
</script>");
}
?>
I'm not sure why this is not working correctly. I need this validation to work. I'm sure there is an alternative method, but this is what I got.
Please help me make this work.
Thank you in advance.
This elseif($checkSerNum = 0) needs to be elseif($checkSerNum == 0)
You're presently doing an assignment instead of a comparison.
Including if($successService = true) and elseif($successService = false) so add another = sign.
Add error reporting to the top of your file(s) which will help during production testing.
error_reporting(E_ALL);
ini_set('display_errors', 1);
http://www.php.net/manual/en/function.mysql-error.php
Footnotes:
mysql_* functions deprecation notice:
http://www.php.net/manual/en/intro.mysql.php
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
These functions allow you to access MySQL database servers. More information about MySQL can be found at » http://www.mysql.com/.
Documentation for MySQL can be found at » http://dev.mysql.com/doc/.
This isn't quite efficient (you are selecting * from your table, which you aren't using - waste of memory?). Why don't you do something like this:
for ($i = 0; $i < $count; $i++)
{
$bolService = $bolArray[$i];
$conService = $conArray[$i];
$recordExists = false;
$result = mysql_query("SELECT COUNT(*) AS recordCount FROM import_service WHERE bol = '" . $bolService . "' AND container = '" . $conService . "'");
if ($result) {
$row = mysql_fetch_assoc($result);
$recordExists = ($row['recordCount'] >= 1);
}
if ($recordExists)
{
$successService = false;
}
else
{
$sql_query_string = mysql_query
("INSERT INTO import_service (bol, container) VALUES ('$bolService','$conService')");
$updateService = mysql_query
("UPDATE import_dispatch_details SET SERVICE = 'Y'
WHERE BOL_NUMBER = '$bolService' AND CONTAINER = '$conService')");
$successService = true;
}
}
P.S. mysql_* is officially deprecated. Please use PDO or MySQLi. Also, your code is potentially open to SQL Injection.

Categories