how to insert correctly in javascript and php - javascript

Hello. I have a function to add row. I just added a second input but I don't know how to insert it correctly.
My JS code:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var counter = 0;
$(function(){
$('p#add_field').click(function(){
counter += 1;
$('#container').append(
'<strong> No. ' + counter + '</strong>'
+
'<strong> ........................ Client ' + counter + '</strong><br />'
+
'<input id="field_' + counter + '" name="dynfields[]' + '" type="text" />'
+
'<input id="field_' + counter + '" name="dynfieldstest[]' + '" type="text" /><br />'
);
});
});
</script>
How I insert:
if (isset($_POST['submit_val'])) {
if ($_POST['dynfields']) {
// HERE WHERE IT'S DOEST WORK //
foreach (array_combine( $_POST['dynfields,dynfieldstest'] as $key=>$value, $key=>$value1 )) {
$values = mysql_real_escape_string($value);
$values1 = mysql_real_escape_string($value1);
$query = mysql_query("INSERT INTO recherche (hobbies,client) VALUES ('$values', '$values1')", $connection );
}
}
echo "<i><h2><strong>" . count($_POST['dynfields']) . "</strong> Info Added</h2></i>";
mysql_close();
}
Thanks for help!

I'm guessing that you're looking for a solution that will scale as more and more inputs are added to the form. Here's a simpler way. It assumes that for each dynfields there will be a corresponding dynfieldstest, and we can count the number of dynfields in order to control the loop.
if (isset($_POST['submit_val'])) {
if ($_POST['dynfields']) {
$post_count = count($_POST['dynfields']);
for ($i=0;$i<$post_count;$i++) {
$values = mysql_real_escape_string($_POST['dynfields'][$i]);
$values1 = mysql_real_escape_string($_POST['dynfieldstest'][$i]);
$query = mysql_query("INSERT INTO recherche (hobbies,client) VALUES ('$values', '$values1')", $connection );
}
}
echo "<i><h2><strong>" . count($_POST['dynfields']) . "</strong> Info Added</h2></i>";
mysql_close();
}
Also, it's time to stop using the deprecated mysql functions. Switch to mysqli for MySQL only, or if you switch to PDO you can interface with MySQL and lots of other database types (MSSQL, Oracle, PostgreSQL, SQLite, etc...).

You should insert all new rows at once.
And use mysqli or PDO in the future, not the old mysql_* functions.
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var counter = 0;
$(function(){
$('p#add_field').click(function(){
counter += 1;
$('#container').append(
'<strong> No. ' + counter + '</strong>'
+
'<strong> ........................ Client ' + counter + '</strong><br />'
+
'<input id="field_' + counter + '" name="dynfields[]' + '" type="text" />'
+
'<input id="field_' + counter + '" name="dynfields[]' + '" type="text" /><br />'
);
});
});
</script>
PHP:
if (isset($_POST['submit_val'])) {
if (is_array($_POST['dynfields'])) {
foreach($_POST['dynfields'] as $key=>$value)
{
$hobbies = mysql_real_escape_string($value);
$client = mysql_real_escape_string($key);
$queryStr[] = "('$hobbies', '$client')";
}
$query = mysql_query("INSERT INTO recherche (hobbies,client) VALUES ".implode(',',$queryStr), $connection );
}
echo "<i><h2><strong>" . count($_POST['dynfields']) . "</strong> Info Added</h2></i>";
mysql_close();
}
To add new input simply add
+
'<input id="field_' + counter + '" name="dynfields[]' + '" type="text" /><br />'
to the js

Related

Select2 Not active

<script>
$(document).ready(function(){
$("#btn-tambah-form").click(function(){
var jumlah = parseInt($("#jumlah-form").val());
var nextform = jumlah + 1;
$("#insert-form").append(
"<div class='row mb-10 p-10'>" +
" <div class='input-group col-md-2'>" +
" <?php $result = mysqli_query($conn, 'SELECT * FROM produk');?>" +
" <?php $jsArray = 'var idproduk = new Array();\n';?>" +
" <select class='form-control select2' id=\'idproduk"+nextform+"\' name=\'idproduk[]\' onchange=\'changeProduk"+nextform+"(this.value),sum();\' required>" +
" <option></option>" +
" <?php while ($row = mysqli_fetch_array($result)) {?>" +
" <?php echo '<option value=\'' . $row['idproduk'] . '\'>' . $row['produk_nama'] . '</option>';?>" +
" <?php$jsArray .= 'idproduk[\'' . $row['idproduk'] . '\'] = {harga_beli:\'' . addslashes($row['harga_beli']) . '\',produk_satuan:\'' . addslashes($row['produk_satuan']) . '\'};\n';?>" +
" <?php }?>" +
" </select>" +
" </div>" +
"</div>");
$("#jumlah-form").val(nextform);
});
$("#btn-reset-form").click(function(){
$("#insert-form").html("");
$("#jumlah-form").val("1");
});
});
</script>
can someone help me. why my select2 not active when i put them on javascript.
when i put them outside java they can run correct.
please help me how to solve this code.
There is problem with backslashed quotes, remove them. It should be all.
<select class='form-control select2' id='idproduk"+nextform+"' name='idproduk[]' onchange='changeProduk"+nextform+"(this.value),sum();' required>" +

dynamic form fields with javascript an php: It doesn't work

I have a small javascript which add form-fields dynamically.
My javascript snippet without any php codes works fine.
<script type="text/javascript">
var counter = 0;
$(function(){
$('p#add_field').click(function(){
counter += 1;
$('#container').append(
'<strong>Artikel ' + counter + '</strong><br />'
+ '<input id="field_' + counter + '" name="dynfields[]' + '" type="text" class="login-username" /><br />'
+ '<input id="field2_' + counter + '" name="dynfields2[]' + '" type="text" class="login-username" /><br />' );
});
});
</script>
But in this script i need an array that read entries from a database for a select option field (dropdown).
I do it like this:
<script type="text/javascript">
var counter = 0;
$(function(){
$('p#add_field').click(function(){
counter += 1;
$('#container').append(
'<strong>Artikel ' + counter + '</strong><br />'
+ '<input id="field1_' + counter + '" name="dynfields[]' + '" type="text" class="login-username" /><br />'
+ '<input id="field2_' + counter + '" name="dynfields2[]' + '" type="text" class="login-username" /><br />'
+ '<select name="dynfields3[]' + '">
<?php
$abfrage = "SELECT * FROM artikel";
mysql_query("SET NAMES SET 'utf8'");
$ergebnis = mysql_query($abfrage);
while($row = mysql_fetch_object($ergebnis))
{
$id = $row->id;
$name = $row->name;
$beschreibung = $row->beschreibung;
$preis = $row->preis;
echo " <option value='$row->id'>$row->name;</option> ";
}
?>
</select><br />'
);
});
});
</script>
It doesn't work. I get the following error
Uncaught SyntaxError: Unexpected token ILLEGAL
What's wrong? Iam very glad for any help.
Regards,
Stefan
You can try this :
<script type="text/javascript">
var counter = 0;
$(function(){
$('p#add_field').click(function(){
counter += 1;
$('#container').append(
'<strong>Artikel ' + counter + '</strong><br />'
+ '<input id="field1_' + counter + '" name="dynfields[]' + '" type="text" class="login-username" /><br />'
+ '<input id="field2_' + counter + '" name="dynfields2[]' + '" type="text" class="login-username" /><br />'
+ '<select name="dynfields3[]">' +
+ '<?php $abfrage = "SELECT * FROM artikel"; mysql_query("SET NAMES SET 'utf8'"); $ergebnis = mysql_query($abfrage); while($row = mysql_fetch_object($ergebnis)){?>'
+ '<option value="' + '<?php echo $row->id ?>' + '">' + '<?php echo $row->name ?>' + '</option>'
+ '<?php }?></select></br>'
);
});
});
</script>
I think the error is here
+ '<select name="dynfields3[]' + '">
maybe you intend
+ '<select name="dynfields3[]" >' +
<?php
$abfrage = "SELECT * FROM artikel";
mysql_query("SET NAMES SET 'utf8'");
$ergebnis = mysql_query($abfrage);
while($row = mysql_fetch_object($ergebnis))
{
$id = $row->id;
$name = $row->name;
$beschreibung = $row->beschreibung;
$preis = $row->preis;
echo " <option value='$row->id'>$row->name;</option> ";
}
?>
+ '</select><br />';

Ajax Webpage Not Displaying Most Update to Date Content After Redirect

I have page that displays images from different directories and can change the file names of files in a folder, based on their order in a jQuery sortable list.
So far everything is working except that after I Save the new file names and the Save page redirects to the Edit page I have to do a "Empty Cache and Hard Reload" in order for the new file order to be displayed.
Edit Page
<!DOCTYPE html>
<?php
session_start();
if (!$_SESSION['username']) {
echo "<script>window.location = './index.php'</script>";
}
?>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Cache-control" content="no-cache">
<meta http-equiv="Expires" content="-1">
<link rel="stylesheet" href="../js/jquery/jquery-ui-1.11.4/jquery-ui.css">
<script src="../js/jquery/jquery-2.1.4.min.js"></script>
<script src="../js/jquery/jquery-ui-1.11.4/jquery-ui.js"></script>
<script>
$(window).load(function() {
$(document).ready(function() {
$("#btnRefresh").click(function() {
window.location.reload(true);
});
$.ajax({
url: 'getPics.php',
success: function(resultOfAjaxCall) {
xmlDoc = $.parseXML(resultOfAjaxCall);
$xml = $(xmlDoc);
html = "";
$xml.find('Folder').each(function(index) {
//console.log($(this).attr('Name'));
city = $(this).attr('Name');
html += "<h3 class='accordion-header'>" + city + "</h3>";
html += "<div class='accordion-section'>";
html += "<button id='" + city + "_Save'>Save " + city + "</button>";
html += " ";
//Upload Form
html += '<form enctype="multipart/form-data" action="uploader.php" method="POST">';
html += '<input type="hidden" name="MAX_FILE_SIZE" value="100000" />';
html += '<input type="hidden" name="City_Folder" value="' + city + '" />';
html += 'Choose a file to upload: <input name="userfile" type="file" /><br />';
html += '<input type="submit" value="Upload File" />';
html += '</form>';
//Save Form
html += '<form enctype="multipart/form-data" action="save.php" method="POST" id="' + city + '_Save_Form">';
html += '<input type="hidden" name="City_Folder" value="' + city + '" />';
html += '</form>';
html += "<ul class='" + city + "-sortable-list'>";
$(this).find('File').each(function(index) {
//console.log($(this).text()
fileName = $(this).find('File_Name').text();
filePath = $(this).find('File_Path').text();
fileRealPath = $(this).find('File_Real_Path').text();
//console.log(fileName);
//console.log(filePath);
html += '<form enctype="multipart/form-data" action="delete.php" method="POST" id="' + fileName + '_Delete_Form">';
html += '<input type="hidden" name="Delete_Path" value="' + filePath + '" />';
html += '</form>'
html += "<li id='" + fileName + "' class='ui-state-default' value='" + fileRealPath + "'>" + fileName + " ";
html += "<button id='" + fileName + "_Delete'>Delete</button>";
html += "<br>"
html += "<img src='" + filePath + "' style='width:150px;'/>";
html += "<br></li>";
})
html += "</ul>";
html += "</div>";
//window.location.reload(true);
});
$("#accordion").append(html);
var $accordion = $("#accordion").accordion({
collapsible: true,
heightStyle: "content",
active: false
});
$("[class$=-sortable-list]").sortable({
update: function(event, ui) {
console.log(ui);
var order = [];
$("[class$=-sortable-list] li").each(function(e) {
order.push($(this).attr("id") + "=" + ($(this).index() + 1));
});
var positions = order.join();
// alert(positions);
},
stop: function(event, ui) {
console.log("an item was moved");
$accordion.find("#tmp").remove();
},
start: function(event, ui) {
$accordion.append("<ul id='tmp'></ul>");
$accordion.find("#tmp").append(ui.item);
}
}).disableSelection();
//Save Click
$("[id$=_Save_Form]").submit(function(event) {
folder = event.target.id.replace("_Save_Form", "");
$("." + folder + "-sortable-list li").each(function(e) {
//alert(folder);
//alert($(this).index());
//alert($(this).attr("value"));
$("<input />").attr("type", "hidden")
.attr("name", "path[" + $(this).index() + "]")
.attr("value", $(this).attr("value"))
.appendTo("#" + event.target.id);
});
});
$("[id$=_Save]").click(function(event) {
$("#" + event.target.id + "_Form").submit();
});
}
});
});
});
</script>
<title>Edit Slider</title>
</head>
<body>
<?php ?>
<p>You are logged in as <?= $_SESSION['username'] ?> (Logout)</p>
<p><button id="btnRefresh">Refresh</button></p>
<div id="accordion">
</div>
</body>
</html>
Save Page
<?php
$root = filter_input(INPUT_SERVER, "DOCUMENT_ROOT", FILTER_SANITIZE_STRING, FILTER_SANITIZE_MAGIC_QUOTES);
require $root . '/CC_Library/CC_Folder.php';
require $root . '/CC_Library/CC_String.php';
$folder = filter_input(INPUT_POST, "City_Folder", FILTER_SANITIZE_STRING, FILTER_SANITIZE_MAGIC_QUOTES);
$dir = "";
$i = 0;
$s = new CC_String;
$tmp = $s->generate_rand(5);
foreach ($_POST['path'] as $value) {
$CC = new CC_File($value);
$dir = $CC->get_File_Dir();
echo "Changing " . $CC->get_Full_File_Name() . " to " . $tmp . str_pad($i, 10, '0', STR_PAD_LEFT) . "." . $CC->get_File_Extension() . "<br>";
$CC->Rename($tmp . str_pad($i, 10, '0', STR_PAD_LEFT) . "." . $CC->get_File_Extension());
$i++;
}
$j = 0;
//echo $dir;
$F = new CC_Folder($dir);
$Files = $F->get_Folder_Files();
foreach ($Files as $value) {
echo "Changing " . $value->get_Full_File_Name() . " to " . $folder . "-" . str_pad($j, 8, '0', STR_PAD_LEFT) . "." . $value->get_File_Extension() . "<br>";
$value->Rename($folder . "-" . str_pad($j, 8, '0', STR_PAD_LEFT) . "." . $value->get_File_Extension());
$j++;
}
echo "<script>window.location.replace('Edit_Slider.php')</script>";
I dont want to read all of that notorious code. Your problem is client sided, not server sided so your code is irreverent.
Your webbrowser is caching and not updating your images. A fix for this would be to extend the current image source with a timestamp like so:
<img src="image.jpg?lastmod=12345678"
//javascript
function(img_src){
var timestamp = (new Date()).getTime();
img_src += "lastmod?" + timestamp;
}
how to clear or replace a cached image
The reason this works is because the source URL is different each time because of the timestamp will always be different & web browsers remember content relative to the URL.

Counting outputted results and send to database

I am wanting output of data from my database to display in a numbered list. Say I have four names in the database. John, suzy, Tom, Linda. I then do a shuffle mix of those names and display them. They appear on my page like this...
undefined John
undefined Suzy
undefined Tom
undefined Linda
I want them to appear as
1 John
2 Suzy
3 Tom
4 Linda
I then want those numbers to send to my database in the order they were in and affiliated with the name they were next to. Right now when they send to my database, each record shows 4, so it is only counting the outputted rows.
I modified my existing script to enable my page to count as a list. However, the count output is not displaying on the page. It shows as undefined, but it is sending as the number 4 to my database.
Why is this not working?
I modified this JS
//'<div class="shuffle_results">' + data[i].firstname + ' ' + data[i].lastname + '</div>' +
To
'<div class="shuffle_results">' + data[i].drafted_order + ' '+ data[i].firstname + ' ' + data[i].lastname + '</div>' +
'<input type="hidden" name="count[]" value="' + data[i].drafted_order + '">' +
Full Code
$count = 0;
foreach ($array as $result) :
$count++;
$shuffle_count = $count;
$shuffle_firstname = htmlentities($result['firstname']);
$shuffle_lastname = htmlentities($result['lastname']);
$shuffle_id = htmlentities($result['id']);
$shuffle_username = htmlentities($result['username']);
$shuffle_email = htmlentities($result['email']);
?>
<input type="hidden" name="count[]" value="<?php echo $shuffle_count; ?>">
<input type="hidden" name="firstname[]" value="<?php echo $shuffle_firstname; ?>">
<input type="hidden" name="lastname[]" value="<?php echo $shuffle_lastname; ?>">
<input type="hidden" name="id[]" value="<?php echo $shuffle_id; ?>">
<input type="hidden" name="username[]" value="<?php echo $shuffle_username; ?>">
<input type="hidden" name="email[]" value="<?php echo $shuffle_email; ?>">
<?php
endforeach;
// only show this button if we have done a shuffle
if ( isset($_POST['shuffle'] ) ) :
echo '<input type="submit" value="Finalize Draft Order" name="insert">';
endif;
?>
</form>
<?php
if (isset($_POST['insert'])) {
$con = mysqli_connect("localhost", "", "", "");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$draft_stmt2 = $con->prepare("INSERT INTO drafted_players (user_id, drafted_order, firstname, lastname, username, email) VALUES (?, ?, ?, ?, ?, ?)");
if ( false===$draft_stmt1|| false===$draft_stmt2 ) {
// Check Errors for prepare
die('Add to user players prepare() failed: ' . htmlspecialchars($con->error));
}
$draft_stmt2->bind_param('iissss', $shuffle_id, $shuffle_count, $shuffle_firstname, $shuffle_lastname, $shuffle_username, $shuffle_email);
foreach ($_POST['id'] as $i => $shuffle_id) {
$shuffle_firstname = $_POST['firstname'][$i];
$shuffle_lastname = $_POST['lastname'][$i];
$shuffle_username = $_POST['username'][$i];
$shuffle_email = $_POST['email'][$i];
$draft_stmt2->execute() or
die('Add to user players execute() failed: ' . htmlspecialchars($draft_stmt2->error));
}
JS
var interval = setInterval(function(){
if( i <= data.length){
console.log( data[i] );
$('#results').append('<div class="result">' +
//'<div class="shuffle_results">' + data[i].firstname + ' ' + data[i].lastname + '</div>' +
'<div class="shuffle_results">' + data[i].drafted_order + ' '+ data[i].firstname + ' ' + data[i].lastname + '</div>' +
'<input type="hidden" name="count[]" value="' + data[i].drafted_order + '">' +
'<input type="hidden" name="firstname[]" value="' + data[i].firstname + '">' +
'<input type="hidden" name="lastname[]" value="' + data[i].lastname + '">' +
'<input type="hidden" name="id[]" value="' + data[i].id + '">' +
'<input type="hidden" name="username[]" value="' + data[i].username + '">' +
'<input type="hidden" name="email[]" value="' + data[i].email + '">' +
'</div>');
var $this = $('.shuffle_results:last');
$this.show().animate({
'left': 0 + 'px',
'bottom': + '0px'
//$(document).height() - (lineheight * data.length)
}, {
duration: time
});
i++;
} else {
clearInterval(interval);
}
}, 3000);
};
$(function(){
$('form[name="form"]').on('submit', function(e){
e.preventDefault();
$.post('shuffle_results.php', function(data){
var o = $.parseJSON(data);
displayResults(o);
});
});
});
//End test shuffle
$(document).ready(function () {

Outputted results from query outputting, but not allowing some of the results to be selected

I have the following code that is supposed to shuffle results from my database if a user is in group 3, 4 or 5. The query is outputting the results fine, but when I click the button to shuffle the results, the only results that display then are from group 3. I believe the issue in my JS, but I'm not sure where or why it is only shuffling the group 3 results when my query is selecting all users from group 3,4 and 5 and the output shows that.
Lets say:
Bob is group 3
Joe is group 4.
Bill is group 5
The way my page looks is like this.
Users that need shuffled...
-Bob
-Joe
-Bill
Button - Shuffle
When I click on the Shuffle Button. Only Bob shows up.
What is wrong in my code that would do this?
$query = mysqli_query($con, "SELECT * FROM users WHERE `group` IN (3, 4 ,5)");
echo 'Users to be given draft order: <br>';
$array = array();
while ($row = mysqli_fetch_assoc($query)) {
$array[] = $row;
echo $row['firstname'] . ' ' . $row['lastname'] . '<br>';
}
?>
<form method="POST" name="form">
<input type="submit" value="Create Draft Order" name="shuffle">
</form>
Shuffled results: <br>
<div class="main-bag">
<div class="shuffle_results" id="results"></div>
</div>
<form method="post">
<input type="submit" value="Finalize Draft Order" name="insert">
var displayResults = function(data){
var i = 0;
var lineheight = 24;
var time = 3000;
var interval = setInterval(function(){
if( i <= data.length){
console.log( data[i] );
$('#results').append('<div class="result">' +
//'<div class="shuffle_results">' + data[i].firstname + ' ' + data[i].lastname + '</div>' +
'<div class="shuffle_results">' + data[i].drafted_order + ' '+ data[i].firstname + ' ' + data[i].lastname + '</div>' +
'<input type="hidden" name="count[]" value="' + data[i].drafted_order + '">' +
'<input type="hidden" name="firstname[]" value="' + data[i].firstname + '">' +
'<input type="hidden" name="lastname[]" value="' + data[i].lastname + '">' +
'<input type="hidden" name="id[]" value="' + data[i].id + '">' +
'<input type="hidden" name="username[]" value="' + data[i].username + '">' +
'<input type="hidden" name="email[]" value="' + data[i].email + '">' +
'</div>');
var $this = $('.shuffle_results:last');
$this.show().animate({
'left': 0 + 'px',
'bottom': + '0px'
//$(document).height() - (lineheight * data.length)
}, {
duration: time
});
i++;
} else {
clearInterval(interval);
}
}, 3000);
};

Categories

Resources