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']))
Related
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 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.
Implemented in PHP using Codeigniter, I am using Twitter Bootstrap Modal for my project. The goal is that when I click the modal, an entry form for the name will appear. Fortunately, the modal gets the data I need (i.e. the name of the community). However, when I load the modals one by one, it is only in the first modal that my code here works:
Here are my codes inside my view page together with the codes linked above:
//..code here
<?php foreach ($name_list as $list) { ?>
modal trigger
<img class="pointer" title="Edit" src="pic.png" data-toggle="modal" data-target="<?php echo "#" . $list->name?>"/> <?php echo $list->name?>
modal
<div class="modal fade bs-example-modal-sm" id="<?php echo $list->name ?>" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
<div class="modal-dialog modal-sm">
<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">Edit <?php echo $list->name?></h4>
</div>
<form action="<?php echo base_url();?>edit" method="post">
<div class="modal-body">
<b><p id="warning"></p></b>
<input name="edit-name" id="edit-name" type="text" placeholder="Name" value="<?php echo $list->name?>"/>
<input name="edit-id" type="text" value="<?php echo $list->id?>" class="hidden"/>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" id="edit-btn" disabled="true" class="btn btn-primary" value="Save changes" />
</div>
</form>
</div>
</div>
</div>
What is wrong with my code? Why does my JS code work only once?
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