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.
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 was inspired by the following source code:
https://github.com/felixivance/Bootstrap-Modal-with-Dynamic-MySQL-Data-using-Ajax-PHP
based on bootstrap 3.3.7 & jquery 3.2.1
My goal is to be able to use it with BTS 4.5 / jquery 3.5.1
Here is my code on the index page
<!-- get list -->
<tr>
<td><?php echo $row['beatid']." ".$row['beatname']; ?></td>
<td>
<button data-toggle="modal" data-target="#showBeat" data-id="<?php echo $row['beatid']; ?>" id="getBeat" class="btn btn-sm btn-info"><i class="glyphicon glyphicon-eye-open"></i> View</button>
</td>
</tr>
Here is the Modal code :
<!-- Modal -->
<div id="showBeat" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Your Listening</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div id="modal-loader" style="display: none; text-align: center;">
<img src="ajax-loader.gif">
</div>
<!-- content will be load here -->
<div id="dynamic-content"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" datadismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- Modal -->
My JS/jquery code :
<script>
$(document).ready(function(){
$(document).on('click', '#getBeat', function(e){
var uid = $(this).data('id'); // it will get id of clicked row
$('#dynamic-content').html(''); // leave it blank before ajax call
$('#modal-loader').show(); // load ajax loader
$.ajax({
url: 'getData.php',
type: 'GET',
data: 'id='+uid,
dataType: 'html',
success: function(data){
$('#dynamic-content').html('');
$('#dynamic-content').html(data); // load response
$('#modal-loader').hide();
},
error: function(){
$('#dynamic-content').html('Something went wrong, Please try again...');
$('#modal-loader').hide();
}
})
});
});
</script>
And my PHP code dealing with the $ .ajax request :
if (isset($_GET['id'])) {
$id = intval($_GET['id']);
$connect = new PDO ("mysql:host=$servername;dbname=$dataname;charset=utf8", $user, $mdp);
$connect -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$getBeat = $connect -> prepare ("SELECT * FROM databasename WHERE dataid=$id");
$getBeat -> execute();
$rows=$getBeat->fetch();
?>
<div class="row">
<div class="col-xl-12"><img src="<?php echo $rows['data']; ?>" class="rounded mx-auto d-block"></div>
</div>
<div class="row">
<div class="col-xl-3" style="margin:5px;text-align: center;">
<audio src="../file/<?php echo $rows['data']; ?>" controls></audio>
</div>
</div>
<?php } ?>
When I click on my link the modal opens well, but it gets stuck on the loader image
But it does not display the data coming from the database!
I tried to adapt the base code with whatever information I found, but nothing helped.
Could you tell me where my error (s) is, thank you in advance
I have a modal containing a combobox,this combobox is populated from database, i want the combobox filled when the modal is opened not on page load,how can this be done?
div class="modal fade" id="modal-DeleteFrm">
<div class="modal-dialog modal-sm" style="width:300px;">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">Delete Farmer</h3>
</div>
<div class="modal-body">
<div class="well" style="margin-bottom: 0px;padding: 10px;">
<div>
<label class="Modallabel">Farmer Name:</label>
</div>
<div>
<select style="width:100%;background-color: #101d49;color:#ffffff;padding-bottom: 5px;" name="FarmerName" id="FarmerName">
<option value="">Select Farmer Name</option>
<!--populate value using php-->
<?php
$stmt ="SELECT * FROM Farmers";
foreach ($conn->query($stmt) as $row) {
$FarmerName = $row['first_name_'].' '.$row['last_name_'];
?>
<option value="<?php echo $row['Farmer_ID'];?>"><?php echo $FarmerName;?></option>
<?php
}
?>
</select>
</div>
</div>
</div>
<div class="modal-footer">
<button id="submitbtn" name="submitbtn" type="button" class="btn btn-success btn-md" style="text-align:center;margin:0;width: 75px;" onclick="DeleteEntry('DeletedFarmer')">Delete</button>
<button type="button" class="btn btn-secondary btn-md" data-dismiss="modal" onclick="CancelModal()" style="text-align:center;font-weight: bold;">Cancel</button>
</div>
</div>
</div>
You need to set a callback to your modal opening event as this code. Then populate your select into it:
$('#modal-DeleteFrm').on('shown.bs.modal', function () {
// write your codes here...
})
You should probably be doing an ajax request when the modal button is clicked. i.e.
$('.modal-DeleteFrm.').on('click', function(){
$.ajax([
url: YOUR-POST-URL
dataType: json,
method: POST,
success: function() {
// Do your appending here
}
])
})
Which would send a POST request and return the data back as JSON.
You could then append this to your modal form using javaScript .append()
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']))
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?