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>
Related
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.
My form contains two select elements. Submission should occur via AJAX only when the onclick event handler bound to button#assignrole is triggered.
But currently, the AJAX call is fired as soon as I select an option from the "User" dropdown:
I have tried to disable all other scripts in my footer, header etc and only kept jQuery v3.4.1
<!-- Assign Role To User -->
<div class="modal fade" id="assignrole" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Assign Role To User</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="selectuser">Select User</label>
<select class="form-control" id="selectuser">
<?php foreach ($users as $user): ?>
<option value="<?= $user['id'] ?>">
<?= $user['username'] ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label for="selectrole">Select Role</label>
<select class="form-control" id="selectrole" data-live-search="false">
<?php foreach ($roles as $role): ?>
<option value="<?= $role['id'] ?>">
<?= $role['role_name'] ?>
</option>
<?php endforeach; ?>
</select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" id="assignrole" class="btn btn-primary">Save changes</button>
</div>
</form>
</div>
</div>
</div>
$(document).ready(function() {
var base_url = "http://127.0.0.1/ci3/";
$("#assignrole").on('click', function() {
var user_id = $('#selectuser option:selected').attr('value');
var role_id = $('#selectrole option:selected').attr('value');
$.ajax({
url: base_url + "backend/assign_role",
method: 'POST',
data: {
"user_id": user_id,
"role_id": role_id
},
dataType: 'json',
success: function(data) {
if (data.status == 1) {
alert("Data Send Success");
}
},
error: function(data) {
alert("maybe your login session timed out, try to login again!");
}
});
});
});
no errors show up
It seems that you have duplicate ID's.
Here:
<div class="modal fade" id="assignrole" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
And here:
<button type="submit" id="assignrole" class="btn btn-primary">Save changes</button>
So that means that when you add the click event it will be set on the first hit of that ID. Which in your case is the modal element.
$("#assignrole") // <div class="modal fade" id="assignrole" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
Changing the ID's of one of the two elements will fix the click issue.
It's because you selector ("#assignrole") is not appropriate.
you have 2 html element with same ids:
<button type="submit" id="assignrole" class="btn btn-primary">Save changes</button>
<div class="modal fade" id="assignrole" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"></div>
remove the modal id.
I cant insert a into my database using bootstrap modal and some ajax. Can someone help me. I recieved an error of Uncaught SyntaxError: Invalid shorthand property initializer. I've been looking for some similar problems with this but I cant find it. Im new to AJAX by the way so im sorry. Does anyone know how to fix this. TIA
Modal
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalCenterTitle">Supplier</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p style="font-weight: bold;">Name </p>
<input style="text-transform:uppercase" type="text" class="form-control" id="supplier"/>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="add_supplier">Add</button>
</div>
</div>
</div>
</div>
Ajax
<script type="text/javascript">
$(document).ready(function(){
$('#add_supplier').click(function(e){
e.preventDefault();
var input = $('#supplier').val();
$.ajaxSetup({
headers:{
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{ url('/supplier') }}",
method: 'post',
data: {
name = input
},
success: function (res){
console.log(res);
window.location.href = '{{route("supplier.index")}}';
}
});
});
});
</script>
Controller
public function store(Request $request)
{
$data = $request->all();
$data['name'] = ($data['name']);
Supplier::create($data);
return response()->json($data);
}
route
Route::resource('supplier', 'SupplierController');
Your data must be sent as a javascript object, so the correct syntax would be
data: {name: input}
I added a Bootstrap modal to my page. Here is the code of modal div:
<div class="modal fade" id="myModal<?php echo $kategori['C_ID'];?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel<?php echo $kategori['C_ID'];?>">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel<?php echo $kategori['C_ID'];?>">Perditeso</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="id">ID</label>
<input type="text" class="form-control" id="id<?php echo $kategori['C_ID'];?>" value="<?php echo $kategori['C_ID'];?>">
</div>
<div class="form-group">
<label for="newname">Kategoria</label>
<input type="text" class="form-control" id="newname<?php echo $kategori['C_ID'];?>" value="<?php echo $kategori['C_Name'];?>">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Mbyll</button>
<button type="button" onclick="catupdate('<?php echo $kategori['C_ID'];?>')" class="btn btn-primary">Ruaj ndryshimet</button>
</div>
</div>
</div>
</div>
and the catupdate function:
function catupdate(id){
var dataString="fshij=" + id;
$.ajax({
type:"post",
url:"../functions/query.php",
data:dataString,
cache:false,
success: function(html){
$('#del').html(html);
}
});
return false;
}
The function runs correctly and completes the action but it doesn't close Modal automatically. In this case i'm tryint to edit datas there. PHP codes are okay.
You should close the modal programmatically after the click using :
$('[id^="myModal"]').modal('hide');
//OR
$('.modal').modal('hide');
Inside success function or in the beginning of your function catupdate to, e.g :
success: function(html){
$('.modal').modal('hide');
$('#del').html(html);
}
Hope this helps.
Use the following syntax to hide a modal:
$('#modalID').modal('hide');
So, in your code:
function catupdate(id){
var dataString="fshij=" + id;
$.ajax({
type:"post",
url:"../functions/query.php",
data:dataString,
cache:false,
success: function(html){
$('#del').html(html);
$('.modal:visible').modal('hide');
}
});
return false;
}
I never used jquery before and tried hard to find a solution for my case.
On the cockpit.php page I use a form to get some content from a mysql database. Meanwhile I am able to show this content in a div on the cockpit.php page.
The plan is to show the content in a modal. There the user has 10 seconds to confirm it (in this case it should be stored to the database).
The problem: I tried it for hours and days to get the content into the modal. No chance... Any idea on how to solve this? Btw: At the moment I reload the window after the countdown reaches zero. Here it would also be an idea to just close to modal via jquery.
So I would really appreciate some hints. Thx.
Final Solution:
modal.js
$(function(){
$("#pricing").submit(function() {
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
success: function(data)
{
$('#myModal').find('#a').text(data.a);
$('#myModal').find('#b').text(data.b);
$('#myModal').find('#c').text(data.c);
$('#myModal').find('#d').text(data.d);
$('#myModal').find('#e').text(data.e);
$('#myModal').find('#f').text(data.f);
$('#a2').val($(this).data('a'));
$('#myModal').modal('show');
}
});
return false;
});
});
$("#confirm").click(function(){
var data = {
a: $('#a').text(),
b: $('#b').text(),
c: $('#c').text()
};
$.ajax({
url: 'confirm.php',
type: "POST",
data: data,
dataType: 'json',
success: function(confirm) {
window.location.reload();
}
});
});
relevant HTML-part of the Modal for click-function:
<div class="alert hidden" role="alert" id="modalAlert"></div>
<input type="hidden" id="confirmmodal" name="confirmmodal" value="" />
</div>
<div class="modal-footer">
<button type="button" class="btn btn-ar btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-ar btn-primary" id="confirm">Confirm</button>
</div>
confirm.php
<?php
$a = $_POST['a'];
// do what you want
$confirm = array('message' => $a);
echo json_encode($confirm);
So the functionality works fine...
I made a full example for you, I use it on my website. This is a html file with a link and a modal, the required JQuery and a simple php code to simulate the server response. It shows you, how you can pass data to the modal, how to show the modal and display the server response.
Just copy the files into the same directory and test it, it works for me.
index.html
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="/script.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModal" aria-hidden="true">
<div class="modal-dialog ">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalTitle"></h4>
</div>
<div class="modal-body">
<div class="alert hidden" role="alert" id="modalAlert"></div>
<input type="hidden" id="myModalID" name="myModalID" value="" />
<p>Modal example.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-danger" id="myModalButton">Submit</button>
</div>
</div>
</div>
</div>
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
<a class="openModalLink" href="/" data-id="1234" data-name="Stackoverflow answer">
<span> Click me to open modal</span>
</a>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
</body>
</html>
script.js
$(function(){
$(".openModalLink").click(function(e) {
e.preventDefault();
$("#myModalTitle").html('Hello, my name is '+$(this).data('name')+'!');
$("#myModalID").val($(this).data('id'));
$('#myModal').modal('show');
});
$("#myModalButton").click(function(){
$.ajax({
url: '/function.php',
data: {
id: $("#myModalID").val()
},
dataType: 'json',
success: function(data)
{
$('#myModal').find('#modalAlert').addClass('alert-success');
$('#myModal').find('#modalAlert').html(data.message).show;
$('#myModal').find('#modalAlert').removeClass('hidden');
}
});
});
});
function.php
<?php
echo json_encode(array('message' => 'You submitted this id: ' . $_GET['id']));
hope this helps, feel free to ask me
UPDATE BASED ON YOUR COMMENT
I created another version that will take data from the form on the html page, pass it to php and then display the results from php on the modal window. It uses a different javascript, because now we are "post"-ing the form data to php. Here are the files:
index.html
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="/script.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModal" aria-hidden="true">
<div class="modal-dialog ">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalTitle"></h4>
</div>
<div class="modal-body">
<div class="alert hidden" role="alert" id="modalAlert"></div>
<input type="hidden" id="myModalID" name="myModalID" value="" />
<p>Modal example.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-danger" id="myModalButton">Submit</button>
</div>
</div>
</div>
</div>
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
<div class="row">
<div class="col-md-8 col-md-offset-0">
<form class="form-inline" id="myForm" action="/function.php" method="post">
<div class="form-group">
<label for="myInput">Input data</label>
<input type="text" class="form-control" id="myInput" name="myInput" placeholder="Enter data here">
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
</body>
</html>
script.js
$(function(){
$("#myForm").submit(function(event) {
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
success: function(data)
{
//display data...
$('#myModal').find('#modalAlert').addClass('alert-success');
$('#myModal').find('#modalAlert').html(data.message).show;
$('#myModal').find('#modalAlert').removeClass('hidden');
$('#myModal').modal('show');
}
});
return false;
});
});
function.php
<?php
echo json_encode(array('message' => 'You submitted this data: ' . $_POST['myInput']));