I have a website, where I can select an Excel file. After selecting I print the filedata in a html table under the fileselect (for checking and editing). Below the table are some buttons and one of them is to upload the table data to a database. For that I'm going through the button click to a JS function, where I store the table data in a multidimensional array. To upload the data I post the array to my php-file. After successful upload I want to show a modal. And thats what my problem is: the modal doesn't appear.
Here is my shorten code:
home.php (html of the website with fileselect)
<!doctype html>
<html lang="de">
<head>
<script src="../js/bootstrap/jquery.slim.min.js"></script>
<script src="../js/bootstrap/popper.min.js"></script>
<script src="../js/bootstrap/bootstrap.min.js"></script>
<script src="web.js"></script>
</head>
<body>
<div class="container">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<div class="input-group">
<label class="input-group-btn">
<span class="btn btn-primary">
Datei auswählen… <input type="file" name="file" style="display: none;">
</span>
</label>
<input type="text" class="form-control" readonly>
</div>
</br>
<button id="excelBtn" type="submit" class="btn btn-success btn-block">Excel-Datei anzeigen</button>
</form>
<?php
if(isset($_FILES['file'])){ //executed after fileselect
include "upload.php"; //show file as table on website, works fine
}
if(isset($_POST['data'])){ //is executed when returning from JS
//upload all array data
//after successful upload do:
include "modal_success.php"; //this php works, will not show extra
}
?>
</div>
</body>
</html>
EDIT: modal_success.php
<div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="false">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Speichern</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Die Daten des Mitarbeiters wurden erfolgreich in die Datenbank geschrieben.
</div>
<div class="modal-footer">
<button type="button" class="btn btn-warning" onClick="geheZuHome()">Zurück zur Startseite</button>
<button type="button" class="btn btn-warning" onClick="window.location.href=window.location.href">Weitere Datei hochladen</button>
</div>
</div>
</div>
</div>
<script>
$("#modal").modal("show");
</script>
upload.php
<!-- print data as table -->
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
<button id="exBtnEnable" type="button" class="btn btn-info btn-block" disabled=false onclick="editTable(<?php echo $taID ?>)">Bearbeiten aktivieren</button>
<button id="exBtnHoch" name="exBtnHoch" onclick="saveInArray()" type="button" class="btn btn-success btn-block">Excel-Datei hochladen</button>
<button id="exBtnAbbr" type="button" onClick="window.location.href=window.location.href" class="btn btn-secondary btn-block">Abbrechen</button>
</form>
My web.js:
function saveInArray(){
//save data in array
var arrString = JSON.stringify(tableData);
var request = new XMLHttpRequest();
request.open('post', 'home.php', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
request.send('data=' + arrString);
}
First I had a save.php where I did the upload to database, but for the modal it was the wrong location. So I took all the code to home.php. Now the location is right but it won't show again.
I thought there could be a problem with multiple file bindings in home.php(bootstrap javascript). Can you confirm it? Or how can I solve it?
It's a project which I took over, so most structure was already there.
In your home.php change
$_POST['data']
to
$_POST['daten']
or in your web.js change
request.send('daten=' + arrString);
to
request.send('data=' + arrString);
and the modal should work.
EDIT:
I see the problem(s) now.
Where do you load your web.js?
Even if saveInArray is called, you don't do anything whit the response.
Possible (but dirty) solution:
Change your web.js
function saveInArray() {
// save data in array
var arrString = JSON.stringify(tableData);
$.post('home.php', {data: arrString}).done(function(response)
{
$('body').html($(response).find('body').html());
});
}
This does a AJAX call with jQuery's post function and replaces the whole body.
Related
Im making a timeline app in php that allows to add, edit and delete events. I wanted to use a modal to ask for confirmation and to test this function from boostrap, but then my problem happened, as i cant make it send a variable through a form.
this calls the modal for each event:
<button type="button" class="eliminarEventoModal" data-id="<?php echo $evento['id'] ?>" data-bs-toggle="modal" data-bs-target="#eliminarEvento">
this gets the $evento['id'] from before into #idEvento, i got from other post on this page related to modals, and i know it works
<script>
$(document).ready(function() {
$(".eliminarEventoModal").click(function() {
$("#idEvento").text($(this).attr('data-id'));
$("#eliminarEvento").modal("show");
});
});
</script>
this is the modal code. it ask if you are sure to delete or not. if not, the modal close and nothing happens, if yes, then push a form to editEvento.php (a diferent file where i use the modal) where the event is deleted.
<!-- Modal -->
<div class="modal fade" id="eliminarEvento" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="eliminarEventoLabel">Delete event</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p>Confirm delete event.</p>
<?php $idEvento='<span id="idEvento"/>'; echo "a".$idEvento."a";?> //<--- line to test if getting the right id only
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-bs-dismiss="modal">Cancelar</button>
<form class="col-md-auto needs-validation" method="POST" action="/editarEvento.php" >
<input type="hidden" name="borrar" value="borrar">
<input type="hidden" name="id" value="<?php echo $idEvento;?>"> //<--- line where it dont work
<button type="submit" class="btn btn-danger">Eliminar</button>
</form>
</div>
</div>
</div>
</div>
The form works with the borrar variable, but not with the id, but why? i need the id to delete the event, so i cant delete any. i have tried some other posts from this page, but i didnt get to work. i have no experience with javascript, im thinking my problem may be related misunderstading some part related to it.
--Edit: modal from page source
<div class="modal fade" id="eliminarEvento" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="eliminarEventoLabel">Eliminar evento</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p>Confirmar eliminar evento.</p>
a<span id="idEvento"/>a </div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-bs-dismiss="modal">Cancelar</button>
<form class="col-md-auto needs-validation" method="POST" action="/Aeberion/editarEvento.php" >
<input type="hidden" name="borrar" value="borrar">
<input type="hidden" name="id" value="<span id="idEvento"/>">
<button type="submit" class="btn btn-danger">Eliminar</button>
</form>
</div>
</div>
</div>
</div>
This is invalid HTML:
<input type="hidden" name="id" value="<span id="idEvento"/>">
The <> brackets in the value attribute are breaking the overall parsing. If you really want the value to be an entire HTML element, you need to HTML-encode the output:
<input type="hidden" name="id" value="<?php echo htmlentities($idEvento);?>">
Though it's not clear why you want the value to be an HTML element, because the information it contains is essentially meaningless and already known to you. But if that's the value you want it needs to be encoded so the HTML parser doesn't think it's part of the <input> element.
What it really looks like though is that this is the value you want:
$evento['id']
Which you assign to a <span> here:
$("#idEvento").text($(this).attr('data-id'));
However:
A <span> is not posted to the server as part of a form
You want the value, not an empty copy of a <span> element.
You already know how to find an element by its id and set a property on it:
$("#idEvento").text($(this).attr('data-id'));
So give your target element an id so you can set its value:
<input type="hidden" name="id" id="eventoModalId">
and:
$("#eventoModalId").val($(this).attr('data-id'));
I have a webform that allows people to post a status as part of my website. It works fine when posting from my locally hosted site however now I have the code on my live site it doesn't work.
Here is my form, file path is root/profile.php -
<div class="modal fade" id="post_form" tabindex="-1" role="dialog" aria-
labelledby="postModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Post Something!</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>This will appear on the user's profile page and also their newsfeed for your
friends to see!</p>
<form class="profile_post" action="" method="POST">
<div class="form-group">
<textarea class="form-control" name="post_body"></textarea>
<input type="hidden" name="user_from" value="<?php echo $userLoggedIn; ?>">
<input type="hidden" name="user_to" value="<?php echo $username; ?>">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" name="post_button"
id="submit_profile_post">Post</button>
</div>
</div>
</div>
</div>
The JS listener to process the post, file path is root/social/assets/js/listen.js -
$(document).ready(function() {
//Button for profile post
$('#submit_profile_post').off('click').on('click', function() {
$.ajax({
type: "POST",
async: false,
url: "social/includes/handlers/ajax_submit_profile_post.php",
data: $('form.profile_post').serialize(),
success: function(msg) {
$('#post_form').modal('hide');
location.reload();
},
error: function () {
alert("Failed to post!");
}
});
});
});
The content of the file the JS/AJAX calls, file path is root/social/includes/handlers/ajax_submit_profile_post.php-
require '../../config/config.php'; //getting $con var
include("../classes/User.php"); //Call in the USER CLASS
include("../classes/Post.php"); //Call in the Post CLASS
include("../classes/Notification.php"); //Call in the Post CLASS
if (isset($_POST['post_body'])) {
$post = new Post($con, $_POST['user_from']);
$post->submitPost($_POST['post_body'], $_POST['user_to'], "");
}
config.php contains the db connection and Post.php is the sql insert and works from a different form on the site. Can anyone see any issues with the code itself as to why it wouldn't work in a different environment? Both localhost and server are PHP 7.4.
When trying to post I get the error message 'Failed to Post!' as per the AJAX function.
I have tried changing the file paths as I thought this may be the issue but have so far been unable to find what might be the correct one.
Try this instead.
Makes more sense. No need to reload the page, then what is the point of using Ajax
$(function() {
$('#profile_post').on('submit', function(e) {
e.preventDefault()
$.ajax({
type: "POST",
url: "social/includes/handlers/ajax_submit_profile_post.php",
data: $(this).serialize(),
success: function(msg) {
$('#post_form').modal('hide');
},
error: function() {
alert("Failed to post!");
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="modal fade" id="post_form" tabindex="-1" role="dialog" aria- labelledby="postModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Post Something!</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>This will appear on the user's profile page and also their newsfeed for your friends to see!</p>
<form class="profile_post" id="profile_post" action="" method="POST">
<div class="form-group">
<textarea class="form-control" name="post_body"></textarea>
<input type="hidden" name="user_from" value="<?php echo $userLoggedIn; ?>">
<input type="hidden" name="user_to" value="<?php echo $username; ?>">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button class="btn btn-primary" name="post_button">Post</button>
</div>
</form>
</div>
</div>
</div>
</div>
I create form, the popup window (in the same file with the form) and the script that creates the post request when the user clicks the button, but when I click the button the page relaoded automatically and the popup window never appears
*I want to pass a parameter from the form to popup window in order to identify the product that the user selected.
My code is below:
*The form is inside of a loop in order to create many items
index.php
while($row = mysqli_fetch_assoc($select_all_products)) {
$product_id = $row['id'];
$product_name = $row['name'];
$product_price1 = $row['price1'];
$product_price2 = $row['price2'];
$product_price3 = $row['price3'];
$product_image= $row['photo'];
?>
<div class="col-lg-6 col-md-6 item-entry mb-4">
<form method="post" >
<a href="#" class="product-item md-height bg-gray d-block">
<?php echo "<img width='300px' height='300px' src='images/$product_image' alt='Image' class='img-fluid'>"; ?>
</a>
<h2 class="item-title"><?php echo $product_name; ?></h2>
<input id="id" type="hidden" name="id" value="<?php echo $product_id; ?>">
<label>shop1: </label>
<strong class="item-price"><?php echo $product_price1 ."\xE2\x82\xAc".str_repeat(' ', 5) ; ?></strong>
<label>shop2 </label>
<strong class="item-price"><?php echo $product_price2 ."\xE2\x82\xAc".str_repeat(' ', 5) ; ?></strong>
<label>shop3 </label>
<strong class="item-price"><?php echo $product_price3 ."\xE2\x82\xAc" .str_repeat(' ', 3) ; ?></strong>
<button type="submit" onclick="loadData(this.getAttribute('data-id'));" data-id="<?php echo $product_id; ?>" class="btn btn-primary btn-sm rounded" data-toggle="modal" data-target="#myModal">Change Price<i class="fas fa-tags"></i></button>
</form>
</div>
<?php
}
?>
popup window :
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
script :
<script type="application/javascript">
function loadData(id) {
id.preventDefault();
$.ajax({
url: "price.php",
method: "POST",
data: {get_data: 1, id: id},
success: function (response) {
console.log(response);
}
});
}
</script>
From the console log I found that the post request send it but with reload page and for this reason the the popup window never appears. 1
What I can do in order the page not reloaded ,the pop up appeared get the post request?
Thank you
To prevent the form from being submitted and hence the page refresh, you should call preventDefault on the form's onsubmit event, like this: <form method="post" onsubmit="event.preventDefault()">. It also works returning false like this: <form method="post" onsubmit="return false">.
I've made an example with the php part removed so you can see. Hope this helps.
I want to make a form appear on a popup window when I click "Add" button. So I am using a modal to show a PHP form but when I tried to save the data inserted into the form into database, it does not work. When I clicked save, a weird URL came out as so :
.../pembelitkatakutest.php?image=025pikachu_xy_anime_3.png&save=
I am not sure, but I think the URL should not have the "image=025pikachu_xy_anime_3.png&" part.
My code is as below:
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">Add Tongue Twister</button><br><br><br>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">Add Tongue Twister</h4>
</div>
<div class="modal-body">
<form method = "POST">
<div class="form-group">
<label for="usr">Please Choose a Picture:</label>
<input type="file" name="image">
<script type="text/javascript">
$(document).ready(function() {
$(window).keydown(function(event){
if(event.keyCode == 13) {
event.preventDefault();
return false;
}
});
});
</script>
</div>
<div class="form-group">
<label for="pwd">Please write the tongue twister:</label>
<input type="text" rows = "3" class="form-control">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" name="save">Save changes</button>
<?php if(isset($_POST['save']))
{
//target folder to keep the media
$target = "images/".basename($_FILES['image']['name']);
//get all submitted data from form
$image = $_FILES['image']['name'];
$text = $_POST['text'];
if(!empty($_FILES['image']['name']))
{
$sql = "INSERT INTO pembelitkataku(image, text) VALUES ('$image','$text')";
mysqli_query($db, $sql);
}
else
{
$message = "Sila pilih semua fail";
echo "<script type='text/javascript'>alert('$message');</script>";
}
move_uploaded_file($_FILES['image']['tmp_name'], $target);
}
?>
</div>
</form>
</div>
May I know what went wrong in my code and what can I do to fix it ?
If it is possible, I want to avoid using Javascript as it is very confusing to understand.
Thank you.
Use <form method="POST" enctype="multipart/form-data">
Because by default your code is making GET request but your PHP code want to receive a POST request. You can see it in this line of code :
if(isset($_POST['save']))
im new to php and still learning. i tried to customized bootstrap template and tried to connect a form to a database.
insert.php
$con=mysqli_connect("localhost","root","","finalproject");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO stokbarang (Merek, Tipe, Harga)
VALUES
('$_POST[merek]','$_POST[tipe]','$_POST[harga]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
header("Location: stock.php");
and a page where the form is stock.php, the form is below :
<form name="sentMessage" class="well" id="contactForm" novalidate action = "insert.php" method = "post">
<legend>Masukkan Data</legend>
<div class="control-group">
<div class="controls">
<label>Merek Mobil</label>
<input type="text" class="form-control" placeholder="Merek mobil" id="merek" required
data-validation-required-message="Masukkan Merek mobil" name = "merek"/>
<p class="help-block"></p>
</div>
</div>
<div class="control-group">
<div class="controls">
<label>Tipe Mobil</label>
<input type="text" class="form-control" placeholder="Tipe Mobil" id="email" required
data-validation-required-message="Masukkan tipe mobil" name = "tipe"/>
</div>
</div>
<div class="control-group">
<div class="controls">
<label>Harga</label>
<input type="number" class="form-control" placeholder="Harga"
id="email" required
data-validation-required-message="Masukkan harga mobil" name = "harga"/>
</div>
<br>
<div id="success"> </span></div> <!-- For success/fail messages -->
<br>
<button type="submit" class="btn btn-primary pull-right">Insert</button><br/><br>
</form>
the form is work and i can insert the data by clicking Insert button to database.
Now i want to add a modal as alert after the form is submitted to database in stock.php
i modified the Insert button as following
<button type="submit" class="btn btn-primary pull-right" data-toggle="modal" data-target="#myModal">Insert</button><br/><br>
here is the modal :
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">SUCCESS</h4>
</div>
<div class="modal-body">
<p>Data Inserted!!</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
but it seems like the button only trigger the modal to appear without submit the form to database. Any suggestion to make the modal appear after successful inserting data to database (after redirecting to stock.php)? or maybe there is better way to make alert after redirect? thank you for your time and help :)
change the header location on insert.php as below :
header("Location: stock.php?sucsess=true");
then stock.php on the head :
<script type="text/javascript">
<?php
if ($_GET['sucsess'] =='true'){
echo '$(function() {
$( "#myModal" ).dialog();
});'
}
?>
</script>
here is a demo only for the alert demo