passing result from php if statement, to javascript/html - javascript

I have a html file including this form with two hidden dialogues above it:
<div class="alert alert-success alert-dismissable" style="display:none;" id="success">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<strong>Success!</strong> Your asset has been added! </div>
<div class="alert alert-warning alert-dismissable" style="display:none;" id="fail">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<strong>Oops!</strong> Something went wrong! </div>
<form class="form-horizontal" action="http://localhost/php/insert.php" method="post">
<fieldset>
<!-- Form Name -->
<legend>Add An Asset</legend>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="name">Name</label>
<div class="col-md-5">
<input id="name" name="name" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="serial">Serial Number</label>
<div class="col-md-5">
<input id="serial" name="serial" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-4 control-label" for="location">Location</label>
<div class="col-md-5">
<select id="location" name="location" class="form-control">
<option value="1">Option one</option>
<option value="2">Option two</option>
</select>
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="singlebutton"></label>
<div class="col-md-4">
<button id="singlebutton" name="singlebutton" class="btn btn-primary" type="submit">Submit</button>
</div>
</div>
</fieldset>
</form>
and the php for the form is here, which is stored on a separate server and referenced:
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dissertation", $con);
$sql="INSERT INTO asset (name, serial)
VALUES
('$_POST[name]','$_POST[serial]')";
if (!mysql_query($sql,$con)) {
$errcode = "error_code=003";
}
$referer = $_SERVER['HTTP_REFERER'];
if ($errcode) {
if (strpos($referer, '?') === false) {
$referer .= "?";
}
header("Location: $referer&$errcode");
} else {
header("Location: $referer");
}
exit;
mysql_close($con)
?>
I need to some how change the if statement in the php to make the warning dialogue shown if there is an error code, and the success dialogue if not. I realise I'll need to use javascript .show() and .hide() but I don't know how to send the php response to the javascript/html file. I can't put the php in the html/javascript file, they need to stay separate.

)in your html file, do something like:
<div class="alert alert-success alert-dismissable" style="<?php echo (!isset($_GET['error_code'])||empty($_GET['error_code']))?"display:none;":"";?>" id="success">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<strong>Success!</strong> Your asset has been added! </div>
<div class="alert alert-warning alert-dismissable" style="<?php echo (isset($_GET['error_code'])&&!empty($_GET['error_code']))?"display:none;":"";?>" id="fail">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<strong>Oops!</strong> Something went wrong! </div>
...
...
:-)

Echo inline JavaScript:
<?php
if (error) {
echo "<script>$('selector').show()</script>";
} else {
echo "<script>$('selector').hide()</script>";
}

Related

Ajax reload even without changes

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

How do I redirect to same page on submitting a form in a bootstrap modal?

I have a bootstrap modal with form which is getting called from a link in my parent home page :
<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="exampleModalLongTitle">Contact</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form method="post" action="student.php" target="_parent">
<div class="form-group row">
<div class="col">
<input type="text" class="form-control" placeholder="Name" name = "name">
</div>
<div class="col">
<label class="mr-sm-2 sr-only" for="inlineFormCustomSelect">Profession</label>
<select class="custom-select mr-sm-2" id="inlineFormCustomSelect" name="profession">
<option selected>Choose...</option>
<option value="1">Student</option>
<option value="2">Parent</option>
<option value="3">Other</option>
</select>
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="e-mail" name = "email">
</div>
<div class="form-group">
<label class="mr-sm-2 sr-only" for="inlineFormCustomSelect">Type</label>
<select class="custom-select mr-sm-2" id="inlineFormCustomSelect" name="type">
<option selected value="1">Feedback</option>
<option value="2">Grievance</option>
<option value="3">Admission</option>
<option value="4">Other</option>
</select>
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Write..</label>
<textarea class="form-control" id="exampleFormControlTextarea1" rows="3" name="message"></textarea>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Send Message</button>
</div>
</div>
</div>
</div>
PHP code in my parent page to handle data of my modal form.
<?php
if(isset($_POST["submit"]))
{
$email = $_POST["email"];
$name = $_POST['name'];
$message = $_POST["message"];
$type = $_POST["type"];
$profession = $_POST["profession"];
$message = wordwrap($message,70);
$headers = "From:".$email;
$subject = "Message by".$name." ".$profession."of type".$type;
mail("yashboura303#gmail.com", $subject, $message, $headers);
echo "Your mail has been sent successfuly ! Thank you for your feedback";
}
?>
Now I want to go back to home.php after submitting my modal form so that I can used mail() function to send mail. How can I achieve this?
I obviously used "action=home.php" in form which is not working and tired "data-dismiss='modal' " in submit button tag but it's not actually submitting the form it's just closing the modal.

Form inside bootstrap modal not updating values in mysql

I have a table in my page which displays data about a certain request.
When I click the 'Add Cedula Number', which is a button, it shows a bootstrap modal. And inside it, has a form.
The value in the ID which is 14 is the ID of that row and it came from this code:
<td class=" ">
<button class="btn btn-primary btn-xs" id="<?php echo $data['idPerson'];?>" data-toggle="modal" data-target="#myModal"> Add Cedula Number </button>
</td>
Now, in order to pass the value in the modal, I used this code:
<script>
$('#myModal').on('show.bs.modal', function (e) {
$(this).find('.modal-body').html(' <div class="form-group"><label class="col-sm-3 control-label">ID</label><div class="col-sm-9"><input type="text" value = ' + e.relatedTarget.id +' class="form-control" id="person_id" name="person_id" readonly="readonly"></div></div> <div class="form-group"> <label class="col-sm-3 control-label">Date</label><div class="col-sm-9"><input type="date" readonly="readonly" class="form-control" id="cedula_date" value="<?php echo date("Y-m-d");?>" name="cedula_date"></div></div> <div class="form-group"> <label class="col-sm-3 control-label">Cedula Number</label><div class="col-sm-9"><input type="number" class="form-control" id="cedula_number" name="cedula_number"/></div></div>' );
})
</script>
This is my modal code:
<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>
<form id="addCedula" action="paid_cedula.php" class="form-horizontal calender" name = "addCedula" enctype="multipart/form-data" method="post" role="form">
<div class="modal-body"></div>
<div class="modal-footer" style="margin:0;">
<button type="button" class="btn btn-default"
data-dismiss="modal">Close</button>
<button id="send" type="submit" class="btn btn-success" name="addCedula">Save Record</button>
</div>
</form>
</div>
</div>
</div>
And my php code is this:
<?php
include 'config.php';
if(isset($_POST['addCedula'])){
$id = $_POST['person_id'];
$date = $_POST['cedula_date'];
$number = $_POST['cedula_number'];
$sql = mysqli_query($conn, "UPDATE person SET dateOfCedulaPayment='$date' AND cedulaNumber='$number' WHERE idPerson='$id';");
mysqli_close($conn);
}
?>
I've been trying to look for the error for hours now. I really can't seem to find where. The value doesn't update in the database. Where did I go wrong? Your help will be much appreciated. Thank you.
#Fred's answer solved the problem (error in Update Query), Here is my 2 cent
This script is overkill to pass the data to modal.
<script>
$('#myModal').on('show.bs.modal', function (e) {
$(this).find('.modal-body').html(' <div class="form-group"><label class="col-sm-3 control-label">ID</label><div class="col-sm-9"><input type="text" value = ' + e.relatedTarget.id +' class="form-control" id="person_id" name="person_id" readonly="readonly"></div></div> <div class="form-group"> <label class="col-sm-3 control-label">Date</label><div class="col-sm-9"><input type="date" readonly="readonly" class="form-control" id="cedula_date" value="<?php echo date("Y-m-d");?>" name="cedula_date"></div></div> <div class="form-group"> <label class="col-sm-3 control-label">Cedula Number</label><div class="col-sm-9"><input type="number" class="form-control" id="cedula_number" name="cedula_number"/></div></div>' );
})
All you need is change id="<?php echo $data['idPerson'];?>" to data-id="<?php echo $data['idPerson'];?>" and following 3 to 4 lines of script do the same job.
$(document).ready(function(){
$('#myModal').on('show.bs.modal', function (e) {
var id = $(e.relatedTarget).data('id');
alert(id);
$("#person_id").val(id);
});
});
Modal HTML
<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>
<form id="addCedula" action="paid_cedula.php" class="form-horizontal calender" name = "addCedula" enctype="multipart/form-data" method="post" role="form">
<div class="modal-body">
<div class="form-group">
<label class="col-sm-3 control-label">ID</label>
<div class="col-sm-9">
<input type="text" value = "" class="form-control" id="person_id" name="person_id" readonly="readonly">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Date</label>
<div class="col-sm-9">
<input type="date" readonly="readonly" class="form-control" id="cedula_date" value="<?php echo date("Y-m-d");?>" name="cedula_date">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Cedula Number</label>
<div class="col-sm-9">
<input type="number" class="form-control" id="cedula_number" name="cedula_number"/>
</div>
</div>
</div>
<div class="modal-footer" style="margin:0;">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="send" type="submit" class="btn btn-success" name="addCedula">Save Record</button>
</div>
</form>
</div>
</div>
</div>
Your query is incorrect. That isn't how UPDATE works. You need to use a comma and not the AND logical operator http://dev.mysql.com/doc/en/logical-operators.html
UPDATE person SET dateOfCedulaPayment='$date', cedulaNumber='$number' WHERE idPerson='$id';
Reference:
http://dev.mysql.com/doc/en/update.html
Checking for errors on your query would have triggered a syntax error:
http://php.net/manual/en/mysqli.error.php
Sidenote: To see if your query (UPDATE) was truly successful, use mysqli_affected_rows().
http://php.net/manual/en/mysqli.affected-rows.php
In not doing so, you may get a false positive.
Nota:
Your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements.

Showing AJAX Confrimation into a modal

I have a form which basically inserts the form data into database. I am doing this by AJAX request. Now, So when the data is inserted the success info of "rentinsert.php" is shown in the form page which is showing "Your order has bee placed". What i want to do is to show it into a modal. So how to show the success message upon AJAX in a modal. Below is my code -
the html -
<form method="post" id="rentalform" action="rentinsertdb.php">
<div class="form-group space" >
<label for="focusedinput" class="col-sm-2 control-label">Full Name</label>
<div class="col-sm-8 tabular-border">
<input type="text" class="form-control" placeholder="Enter full name" name="rentname">
</div>
</div>
<div class="form-group space" >
<label for="focusedinput" class="col-sm-2 control-label">Choose your ride</label>
<div class="col-sm-8 tabular-border">
<div class="dropdown">
<select class="btn btn-default dropdown-toggle" name="rentcar" >
<option>Choose your ride</option>
<option value="Toyota Alion 2008">Toyota Alion 2008</option>
<option value="Toyota Alion 2008">Toyota Premio 2008</option>
<option value="Toyota Alion 2008">Toyota Corolla 2006</option>
<option value="Toyota Alion 2008">Toyota Noah 2010</option>
</select>
</div>
</div>
</div>
<!-- <div class="form-group space" >
<label for="focusedinput" class="col-sm-2 control-label">Phone Number</label>
<div class="col-sm-8 tabular-border">
<input type="text" class="form-control" id="focusedinput" placeholder="Enter phone number">
</div>
<div class="col-sm-2">
<p class="help-block"></p>
</div>
</div> -->
<div class="form-group space" >
<label for="focusedinput" class="col-sm-2 control-label">Phone Number</label>
<div class="col-sm-8 tabular-border">
<input type="text" class="form-control" name="rentphone" placeholder="Enter phone number">
</div>
<div class="col-sm-2">
<p class="help-block"></p>
</div>
</div>
<div class="form-group space">
<label for="txtarea1" class="col-sm-2 control-label">Pick up address</label>
<div class="col-sm-8 tabular-border"><textarea name="rentaddress" cols="50" rows="4" class="form-control" placeholder="Enter Full Address; For example: House#38, Road 7/a, Dhanmondi, Dhaka-1205, Bangladesh"></textarea></div>
</div>
<div class="col-sm-8 col-sm-offset-2 space">
<button class="btn-primary btn" style="background-color:#03a9f4; border-color:#03a9f4;" id="submitrent"> Confirm </button>
</div>
</form>
</div>
<span id="result"></span>
<script type="text/javascript">
$("#submitrent").click( function() {
$.post( $("#rentalform").attr("action"),
$("#rentalform :input").serializeArray(),
function(info){ $("#result").html(info);
});
// clearInput();
});
$("#rentalform").submit( function() {
return false;
});
// function clearInput() {
// $("#myForm :input").each( function() {
// $(this).val('');
// });
// }
</script>
rentinsert.php -
<?php
header("Access-Control-Allow-Origin: *");
include_once "rentconnection.php";
// echo "<pre>";
// print_r($_POST);
$sql = "INSERT INTO `rental`
(`name`,`car`,`phone`,`address`)
VALUES ('".$_POST['rentname']."','".$_POST['rentphone']."','".$_POST['rentcar']."','".$_POST['rentaddress']."');";
if(mysqli_query($con, $sql)){
?>
<body style= "background-color:#1D726A">
<h1>Your Order Has Been Placed! </h1>
</body>
<?php
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
mysqli_close($con);
?>
You need to echo your message when you successfully insert data into database
if (mysqli_query($con, $sql)) {
echo "<body style= 'background-color:#1D726A'><h1>Your Order Has Been Placed! </h1></body>";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
mysqli_close($con);
if (mysqli_query($con, $sql)) {
echo json_encode(array('message' => 'Your Order Has Been Placed!'));
exit();
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
mysqli_close($con);
Add modal
<div class="modal fade" id="modal-content">
<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">Modal title</h4>
</div>
<div class="modal-body">
<p id="msg">Message here!</p>
</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><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
Show message in view
("#submitrent").click( function() {
$.post( $("#rentalform").attr("action"),
$("#rentalform :input").serializeArray(),
function(info){
var obj = jQuery.parseJSON(info);
$("#msg").html(obj.message);
$("#modal-content").modal('show');
});
// clearInput();
});

Can't access DOM from SCM Music Player

I am building a website using SCM Music Player (an open source web player), and I would like to use the "finish" callback to modify my DOM when the music stops. I can access this callback and execute a "console.log()", but I can't access DOM... I've noticed that this script uses Knockout library, but I don't know how it works and if it is necessary... Here is my code from scm.js:
finish = function(){
//repeat one start again, otherwise next song
if(repeatMode()==2) start();
else {
console.log('Next son de scm.js :');
var div = ko.observable($('#ajouterSon').attr('role'));
console.log('Div: ' + div);
next();
}
};
And the kind of changes I do when I play a song :
$('.musiqueLink').on('click', function(event) {
console.log('clic musique - last id = ' + lastidmusique);
event.preventDefault();
if(lastidmusique != null)
document.getElementById('row'+lastidmusique).setAttribute("class", "row");
document.getElementById('row'+$(this).attr('data-idmusique')).setAttribute("class", "row highlighted");
SCM.play({title:$(this).attr('data-titre'),url:$(this).attr('data-lien')});
lastidmusique = $(this).attr('data-idmusique');
});
The dom which contains 'ajouterSon' :
<body style=" background-image: url('imgs/backgrnd.jpg'); background-size: 100% 100%; background-repeat:no-repeat; background-attachment:fixed;">
<div id="ajouterSon" class="modal fade" tabindex="-1" role="dialog" 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>
<h1 class="text-center">Ajouter un son</h1>
<?php
?>
</div>
<div class="modal-body">
<form class="form col-md-12 center-block" id="ajoutSon">
<div class="form-group">
<input type="text" title="Titre du son" class="form-control input-lg" placeholder="Titre" id="titre">
</div>
<div class="form-group">
<input type="text" title="Auteur du son" class="form-control input-lg" placeholder="Artiste" id="artiste">
</div>
<div class="form-group">
<label for="genre">Style</label>
<div class="form-group">
<select class="selectpicker" multiple id="genre">
<?php
$genres = $mysqli->query("SELECT idgenre, nom FROM GENRE");
while($row = $genres->fetch_array())
$rows[] = $row;
mysqli_free_result($genres);
foreach($rows as $row)
{
$styles = $mysqli->query("SELECT idstyle, nom FROM STYLE WHERE GENRE = ".intval($row['idgenre']));
while($rowStyles = $styles->fetch_array())
$rowsStyles[] = $rowStyles;
echo "<optgroup label=\"".$row['nom']."\">";
foreach ($rowsStyles as $rowStyles)
echo "<option value=\"".$rowStyles['idstyle']."\">".$rowStyles['nom']."</option>";
echo "</optgroup>";
mysqli_free_result($styles);
unset($rowsStyles);
}
unset($rows);
?>
</select>
</div>
</div>
<div class="form-group">
<input type="text" title="Décris ton son" class="form-control input-lg" placeholder="Description" id="description">
</div>
<div class="form-group">
<input type="url" title="Lien Youtube/Soundcloud" class="form-control input-lg" placeholder="Lien Youtube/Soundcloud" id="lien">
</div>
<div class="form-group">
<button class="btn btn-primary btn-lg btn-block" type="submit" id="submit">Ajouter</button>
</div>
</form>
</div>
<div class="modal-footer">
<div class="col-md-12">
<button type="button" class="btn" data-dismiss="modal" aria-hidden="true">Annuler</button>
</div>
</div>
</div>
</div>
</div>
...
</body>
I precise that I have placed my include balise for the JS just above the end of the body.
Thank you for your help,
Théo

Categories