Ajax reload even without changes - javascript

To edit an event on Fullcalendar I click on an event, a modal apparead and is connected to a PHP file and has an AJAX call in JS.
The problem is: when I open the modal and close it, even if I have made no changes it reload the page. Can someone please explain what's the problems in these code, I cant seems to find a solution and it's pretty annoying that reload without making changes.
JS call:
$('#editNewEvent').modal('show').one('hidden.bs.modal', function (e) {
if(event.nomeUtente == $("#nomeUtente").data('value')){
event.title = $('#editEname').val();
event.start = $('#editStarts').val();
event.end = $('#editEnds').val();
$.ajax({
url: 'eventi/updateEvent.php',
type: 'POST',
data: {start: event.start, _id: event.idAssenza, end: event.end, title: event.title},
success: function(data) {
window.location.reload(true);
}
});
$('#calendar').fullCalendar('updateEvent', event._id);
}
});
PHP editEvents:
require_once "../config.php";
session_start();
$id = $_POST['_id'];
$ename = $_POST['title'];
$starts = $_POST['start'];
$ends = $_POST['end'];
$nomeUtente = $_SESSION['nomeUtente'];
// update the records
$sql = "UPDATE assenze SET ename = '$ename', starts = '$starts', ends = '$ends' WHERE idAssenza = $id AND nomeUtente = '$nomeUtente'"; //
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
MODAL:
<div class="modal fade" id="editNewEvent" aria-hidden="true" aria-labelledby="editNewEvent" role="dialog" tabindex="-1" data-show="false" data-toggle="modal">
<div class="modal-dialog modal-simple">
<form class="modal-content form-horizontal" role="form">
<div class="modal-header">
<button type="button" class="close" aria-hidden="true" data-dismiss="modal">×</button>
<h4 class="modal-title">Modifica Assenza di <input type="text" name="editNomeUtente" id="editNomeUtente" value="editNomeUtente" disabled></h4>
</div>
<div class="modal-body">
<div class="form-group row">
<label class="form-control-label col-md-2" for="editEname">Tipo:</label>
<input list="assenza" name="editEname" id="editEname" style="margin-left: 15px;" />
<datalist id="assenza">
<option value="Normali">
<option value="Straordinarie">
<option value="Ferie">
<option value="Malattia">
<option value="Permesso">
<option value="Smart Working">
<option value="Trasferta">
<option value="Assenza non retribuita">
<option value="Altro">
</datalist>
<input type="hidden" name="editNomeUtente" id="editNomeUtente" value="<?php echo $_SESSION["nomeUtente"]; ?>">
</div>
<div class="form-group row">
<label class="col-md-2 form-control-label" for="editStarts">Inizio:</label>
<div class="col-md-10">
<div class="input-group">
<input type="datetime-local" class="form-control" id="editStarts" name="editStarts" data-container="#editNewEvent">
</div>
</div>
</div>
<div class="form-group row">
<label class="col-md-2 form-control-label" for="editEnds">Fine:</label>
<div class="col-md-10">
<div class="input-group">
<input type="datetime-local" class="form-control" id="editEnds" name="editEnds"data-container="#editNewEvent">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<div class="form-actions">
<button class="btn btn-primary" data-dismiss="modal" type="button" id="salva">Salva modifiche</button>
<button class="btn btn-sm btn-white btn-pure" id="annulla" href="">Annulla</button>
</div>
</div>
</form>
</div>
</div>

Because you trigger event it (hidden.bs.modal), event this will be call when you close modal -> call to -> eventi/updateEvent.php.
I suggest you should be call event update when only you click to button Salva modifiche

Related

How to use AJAX to get value form controller into a popup

I want to get data from a controller and display it in a html pop-up when a button is clicked.
At this point the POPUP is showing when the button is clicked but the data isn't loaded
At this point I need that onclick the values get loaded and show them in the popup.
index.blade.php
<button data-toggle="modal" data-target="#edit" id ="uid" name="uid" value="<?php echo $user->id ?>">
</button>
<div class="modal fade" id="edit" tabindex="-1" role="">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="card card-signup card-plain">
<div class="modal-header">
<div class="card-header card-header-primary text-center">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
<i class="material-icons">clear</i>
</button>
<h4 class="card-title">Editar</h4>
</div>
</div>
<div class="modal-body">
<form class="form" method="POST" action = "{{ route('/alteruser') }}" name = 'user'>
#csrf
<div class="card-body">
<div class="form-group bmd-form-group">
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="material-icons"></i>
</div>
</div>
<input name = 'name' type="text" class="form-control" placeholder="<?php echo $seluser->id ?? ''?>" id='id' disabled>
<input name = 'name' type="text" class="form-control" "<?php echo $seluser->name ?? ''?>" id='name'>
<input type="text" class="form-control" placeholder="<?php echo $seluser->email ?? ''?>" id = 'email'>
<input type="password" placeholder="<?php echo $seluser->password ?? ''?>" class="form-control" id = 'password'>
<input type="text" placeholder="<?php echo $seluser->nif ?? ''?>" class="form-control" id = 'nif'>
<input type="text" placeholder="<?php echo $seluser->contacto ?? ''?>" class="form-control" id = 'contact'>
<input type="text" placeholder="Grupo" class="form-control" id = 'grupo'>
</div>
</div>
<button type="submit" class="btn btn-primary btn-link btn-wd btn-lg" name = 'uid'>Confirmar</a>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
UserController#GetUser:
public function getUser() {
$id = $_POST['uid'];
$seluser = DB::table('users') -> where('id', $id) -> first();
$view = view('/users/index',compact('seluser'))->render();
return response(['status'=> 1, 'data' => $view]);
}
Ajax code in index.blade.php:
$(document).ready(function(){
$("#uid").click(function (e){
e.preventDefault();
$.ajax({
type: 'POST',
url: baseUrl+"/getUser",
data:{uid: $("#uid").val()},
dataType: 'json',
success: function(data) {
$('#edit').html(data.html);
}
});
});
});
I'm new at AJAX so i assume the error is in it
Here is an example for what you're trying to do :
Controller for GET request :
$users = \App\User::all();
return view('users', ['users' => $users]);
View users :
<div class="container">
#foreach ($users as $user)
<button class="btn btn-primary" data-toggle="modal" data-target="#edit" id ="uid" data-id="{{$user->id}}">
click here
</button>
#endforeach
#csrf
<div class="modal fade" id="edit" tabindex="-1" role="">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="card card-signup card-plain">
<div class="modal-header">
<div class="card-header card-header-primary text-center">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
<i class="material-icons">clear</i>
</button>
<h4 class="card-title">Editar</h4>
</div>
</div>
<div class="modal-body">
<div id="user">
<h1 id="name"></h1>
<p id="email"></p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
JS code :
<script>
/* eslint disabled */
$(
() => {
$('#uid').click(
(e) => {
var uid = $(event.target).data('id');
$.ajax({
type: 'POST',
url: 'users/' + uid,
data: {'_token': $("input[name='_token']").val()},
success: function(data){
// or use : $('#user').html(data);
$('#user #name').text(data.name);
$('#user #email').text(data.email);
}
});
}
);
}
);
</script>
Controller (Route) POST request :
Route::post('users/{id}', function ($id) {
$data = \DB::table('users')->where('id', $id)->first();
return response()->json($data, 200);
});
This code allow to the client , for each user in db there're modal button to open popup , and after clicking on user's button i get a pop up with mail and name for this user

Cant get data from form sent to mysql database

Can someone help, I cant seem to get the data colleted from the form to be sent to the mysql database.
I am very new to coding and I cant seem to figure out why the form data is not being sent to the mysql database table.
Please any help would be muchly appricated.
once I press submit the page closes than refreshs without any errors, but the data has not been sent to the database table.
Please see code below.
<?php include'inc/header.php'; ?>
<div class="container">
<center>
<h2 style="color: #odc16f">Shipped</h2>
<hr>
</center>
<center>
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#addEmpModal">
Add Order
</button>
</center>
<!-- Modal -->
<div class="modal fade" id="addEmpModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form action="" method="post">
<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">Add New Order</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label>Enter Name</label>
<input class="form-control" type="text" name="customer" id="customer" placeholder="Enter Name">
<label id="lbcustomer" style="color:red"></label>
</div>
<div class="form-group">
<label>Enter Date</label>
<input class="form-control" type="date" name="date" id="date" placeholder="Enter Date">
<label id="lbdate" style="color:red"></label>
</div>
<div class="form-group">
<label>Enter Invoice</label>
<input class="form-control" type="number" name="invoice" id="invoice" placeholder="Enter Invoice">
<label id="lbinvoice" style="color:red"></label>
</div>
<div class="form-group">
<label>Enter eBay</label>
<input class="form-control" type="number" name="ebay" id="ebay" placeholder="Enter eBay">
<label id="lbebay" style="color:red"></label>
</div>
<div class="form-group">
<label>Enter Shipped</label>
<input class="form-control" type="text" name="shipper" id="shipper" placeholder="Enter Shipped">
<label id="lbshipper" style="color:red"></label>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="save">Save changes</button>
</div>
</form>
</div>
</div>
</div>
</div><!-- /.container ends here -->
<?php
include'inc/footer.php';
?>
<script>
$(document).ready(function() {
$(document).on('click', '#save', function() {
var customer = $("#customer").val();
var date = $("#date").val();
var invoice = $("#invoice").val();
var ebay = $("#ebay").val();
var shipper = $("#shipper").val();
if (customer == "") {
$("#lbcustomer").html("Enter Name");
} else if (date == "") {
$("#lbdate").html("Enter Date");
} else if (invoice == "") {
$("#lbinvoice").html("Enter Invoice");
} else if (ebay == "") {
$("#lbebay").html("Enter eBay");
} else if (shipper == "") {
$("#lbshipper").html("Enter Shipper");
} else {
$.ajax({
url: "save_data.php",
type: "post",
data: {
customer: customer,
date: date,
invoice: invoice,
ebay: ebay,
shipper: shipper
},
success: function(data) {
alert("Order Has Been Successful");
$("#addEmpModal").modal('hide');
location.reload();
}
});
}
});
});
</script>
Please see below the save_data.php code
<$php
include 'config/config.php';
global $con;
$customer = $_POST['customer'];
$date = $_POST['date'];
$invoice = $_POST['invoice'];
$ebay = $_POST['ebay'];
$shipper = $_POST['shipper'];
$save_data = "INSERT INTO orders(customer, date, invoice, ebay, shipper)VALUES('$customer','$date','$invoice','$ebay','$shipper')";
$result = mysqli_query($con, $save_data);
and below is the config.php code.
<?php
$con = mysqli_connect("localhost","root","Password","shippedorders");
if (!$con) {
echo "Failed to connect to MySQL: ".mysqli_connect_error($con);
}
you are missing
action in :
<form action="save_data.php" method="post">
or are you running your php in same page as html ? or you

Modal window not getting opened Coding - jquery and php got some issue

My modal window is not getting opened. It seems there is an issue with my php.action action - or within ajax call.
Please can someone have a look?
My javascript - alert shows the record id.
$(document).ready(function(){
// Fetch single data
$(document).on("click","#editId",function(e){
e.preventDefault();
//alert("you click edit button");
var action ='FetchSingle';
var editId = $(this).attr('data-editId');
alert("you click edit button:" + editId);
$('#edit').modal('show'); //This works but not wihtin success:function(data)
$.ajax({
url:"action.php",
method:"POST",
data:{action:action,editId:editId},
dataType:"json",
error: function(xhr, status, error) {
var err = JSON.parse(xhr.responseText);
alert(err.Message);
},
success:function(data){
$('#name').val(data.name);
$("#designation").val(data.designation);
$("#sex").val(data.sex);
$('#edit').modal('show');
}
});
});
});});
Here is my action.php
if (isset($_POST['action'])) {
if ($_POST['action'] =='FetchSingle') {
$editId = $_POST['editId'];
$output = '';
$sql = "SELECT * FROM tbl_employee_info WHERE id='".$editId."'";
$data = $DBObj->select($sql);
foreach ($data as $value) {
$output['image'] = $value['image'];
$output['name'] = $value['name'];
$output['designation'] = $value['designation'];
$output['sex'] = $value['sex'];
$output['uploaded_hidden_image'] = '<img width="70px" height="70px" src="upload/'.$value['image'].'">';
}
echo json_encode($output);
} //end of isset post action
} //end of if isset post
my Modal window
<!-- Modal -->
<div class="modal fade" id="edit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<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">Edit Details</h4>
</div>
<div class="modal-body">
<div class="form-group pmd-textfield pmd-textfield-floating-label">
<label for="name" class="control-label">Name</label>
<input type="text" class="form-control" name="name" id="name">
</div>
<div class="form-group pmd-textfield pmd-textfield-floating-label">
<label for="Designation" class="control-label">Designation</label>
<input type="text" class="form-control" name="designation" id="designation">
</div>
<div class="form-group pmd-textfield pmd-textfield-floating-label">
<label for="sex" class="control-label">Select a sex</label>
<input type="text" class="form-control" name="sex" id="sex">
<select class="select-simple form-control pmd-select2" name="sex" id="sex">
<option></option>
<option value="1">Male</option>
<option value="2">Fmale</option>
<option value="3">Others</option>
</select>
<!-- end of display data here -->
</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>
<!-- /.Modal -->
Any suggestions or a way to debug the issue would be highly appreciated. The problems seems to be in my action.php script.

Make a dynamic JSON based on the select option

I have this modal view :
<div class="modal fade" id ="myModal" tabindex="-1" role="dialog">
<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">Delta Rom insert missed entries</h4>
</div>
<div class="modal-body">
<form class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label">Event:</label>
<div class="col-sm-10">
<select id="eventData" name="type" data-placeholder="Select"
class="form-control chosen-select">
<option value="Harvest">
Harvest Product Machine
</option>
<option value="Tara">
Tara Machine
</option>
</select>
</div>
</div>
<div id ="producttab" class="form-group">
<label class="col-sm-2 control-label">Product:</label>
<div class="col-sm-10">
<select name="harvest" id ="harvestData" data-placeholder="Select"
class="form-control chosen-select">
<?php
foreach ($this->datamodal['products'] as $value) {
echo '<option value = "' . $value->name . '">' . $value->name . '</option>';
}
?>
</select>
</div>
</div>
<div id ="tabmachines" class="form-group">
<label class="col-sm-2 control-label">Machine:</label>
<div class="col-sm-10">
<select name="machine" id ="machineData" data-placeholder="Select"
class="form-control chosen-select">
<?php
foreach ($this->datamodal['machines'] as $value) {
echo '<option value = "' . $value->name . '">' . $value->name . '</option>';
}
?>
</select>
</div>
</div>
<div id="impuritytab" class="form-group">
<label class="col-sm-2 control-label">Impurity:</label>
<div class="col-sm-10">
<input name="impurities" type="text" class="form-control" id="inputimpuritiesData"
placeholder="Impurities">
</div>
</div>
<div id ="humiditytab" class="form-group">
<label class="col-sm-2 control-label">Humidity:</label>
<div class="col-sm-10">
<input name="humidity" type="text" class="form-control" id="humidityAData"
placeholder="Humidity">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="saveModal" type="button" value="submit" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
And I got 2 types of events with value Harvest or Tara, depending on the event selected I show some particular div's like this:
$('#eventData').change(function() {
opt = $(this).val();
if (opt=="Tara") {
$("#producttab").hide();
$("#impuritytab").hide();
$("#humiditytab").hide();
}else if (opt == "Harvest") {
$("#producttab").show();
$("#impuritytab").show();
$("#humiditytab").show();
}
});
I have a ajax that will submit that form:
function onAddMissedEntryInfoClicked(entryId) {
var currentEntryId = entryId;
$('#myModal').modal('show'); //this load modal view
$("#saveModal").unbind( "click");
$('#saveModal').bind('click', function(){
var event = $('#eventData').val();
var product = $('#harvestData').val();
var machine = $('#machineData').val();
var impurities = $("#inputimpuritiesData").val();
var humidity = $("#humidityData").val();
var dataJson = {
"eventid":currentEntryId,
"event": event,
"product": product,
"machine": machine,
"impurities": impurities,
"humidity":humidity
};
$.ajax({
type: 'POST',
url: "Monitor/thisUpdate",
data: dataJson,
success: function (data) {
console.log(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
$('#myModal').modal('hide');
});
}
My problem is that when I'm on the Machine option, I will see only the tabmachines id field (that is good) but when I submit I will send all form values including the fields that I was hiding in my jQuery. I want to only send the forms on the select option, in my case only send machine values. How I can make my ajax data in a dynamic way? Thank you!
You can add an if clause in your onAddMissedEntryInfoClicked and create a different json object according to the event data.
if (event==="Harvest") {
var dataJson = {
"eventid":currentEntryId,
"event": event,
"machine": machine
};
}
else if (event==="Tara") {
var dataJson = {
"eventid":currentEntryId,
"event": event,
"product": product
"impurities": impurities,
"humidity":humidity
};
}

Bootstrap Modal content issue after refreshing content

I have this modal
<!-- Modal -->
<div id="normale" class="modal fade" role="dialog">
<div class="modal-dialog" style="background-color:white">
<!-- Modal content-->
<div class="modal-content" style="background-color:white">
<div class="modal-header" style="background-color:white">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Aggiungi al carrello</h4>
</div>
<div class="modal-body" id="mod_carrello" style="background-color:white">
<div class="hidden">
<input type="text" id="id_tariffa" name="id_tariffa" value="id_tariffa" readonly class="form-control hidethis" style="display:none" >
</div>
<div class="form-group hidethis " style="display:none" >
<label for="Id" class=" control-label col-md-4 text-left"> Id </label>
<div class="col-md-6">
<input type="text" id="id" name="id">
</div>
<div class="col-md-2">
</div>
</div>
<div class="form-group hidethis " style="display:none">
<label for="Cod Carrello" class=" control-label col-md-4 text-left"> Cod Carrello </label>
<div class="col-md-6">
<?php
$persistent = DB::table('carrello')->where('entry_by', \Session::get('uid'))->first();
if (empty($persistent)) {
$chars = "abcdefghijkmnopqrstuvwxyz023456789";
srand((double)microtime()*1000000);
$i = 0;
$code = '' ;
while ($i <= 20) {
$num = rand() % 33;
$tmp = substr($chars, $num, 1);
$code = $code . $tmp;
$i++; } ?>
<input type="text" name="cod_carrello" value="{{ $code }}" id="cod_carrello">
<?php } else {
$cod_carrello = $persistent->cod_carrello; ?>
<input type="text" name="cod_carrello" value="{{ $cod_carrello }}" id="cod_carrello">
<?php } ?>
</div>
<div class="col-md-2">
</div>
</div>
<div class="form-group " >
<label for="Quantita" class=" control-label col-md-4 text-left"> Quantita </label>
<div class="col-md-6">
<input type="text" class="form-control" id="quantita" name="quantita">
</div>
<div class="col-md-2">
</div>
</div>
</fieldset>
</div>
<div class="modal-footer" style="background-color:white">
<button type="submit" id="add_to_cart" class="btn btn-assertive">Aggiungi</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Chiudi</button>
</div>
</div>
</div>
</div>
That is an Ajax cart.
This is the Jquery script:
$('#add_to_cart').click(function(){
var button = $(event.relatedTarget) // Button that triggered the modal
var id_tariffa = button.data('tariffa')
// If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
var modal = $(this)
modal.find('.hidden input').val(id_tariffa);
var cod_carrello = document.getElementById("cod_carrello").value;
var quantita = document.getElementById("quantita").value;
$.ajax({
url: 'carrello-ajax',
type: "post",
data: {'id_tariffa':id_tariffa, 'cod_carrello':cod_carrello, 'quantita':quantita, '_token': $('input[name=_token]').val()},
success: function(data){
if ( data.OK == 1 ) {
var mod_carrello_original = $("#mod_carrello").html();
$('#mod_carrello').html('<h1 align="center" style="color:green; font-size: 21.5em;"><i class="fa fa-smile-o"></i></h1><br><br><h3 align="center">Servizio aggiunto correttamente al carrello</h3>');
$("#normale").on("hidden.bs.modal", function(){
$('#mod_carrello').html(mod_carrello_original);
});
} else {
$('#mod_carrello').html('<h1 style="color:green"><i class="fa fa-error"></i><br>Si è verificato un errore</h2>');
}
}
});
});
});
My problem is that after 2 times that I input and add to cart some product without any problem the modal no longer updates content nor shows every time the success message.
I hope that someone can help me.
Solved using a fresh div with the same content bu different id

Categories