Showing fake path while updating the image in the database - php

<script type="text/javascript">
$('#t').on('click','#btns',function() {
var id = $(this).attr('data-id');
var image = $(this).attr('data-image');
$('#dats').val(id);
$('#Mimage').val(image);
});
$(document).ready(function() {
$.ajax({
type: "POST",
url: "query1.php",
success: function(data) {
var parsed = $.parseJSON(data);
$.each(parsed, function(i,parsed) {
$('#t').append('<tr><td>'+parsed.id+'</td><td id="edi"><img src="upload/'+parsed.image+'" height = "50px" width = "50px"></td><td>'+'<button class="button info" name="btn" data-toggle="modal" data-target="#Mpn" id="btns" data-id="'+parsed.id+'" data-image="'+parsed.image+'">Edit</button>'+'<button class="button info1" name="btn" data-toggle="modal" data-target="#Mpd" id="btns" data-id="'+parsed.id+'" data-image="'+parsed.image+'">Delete</button>'+'</td></tr>');
});
}
});
$('body').on('click','#update',function(e) {
alert("hi");
var id = $('#dats').val();
alert(id);
var images = $('#Limage').val();
alert(images);
$.ajax({
type:"POST",
url:"upd.php",
data:{mode:'upd',id:id,images:images},
success:function(data){
alert(data);
alert("successfully updated");
}
});
});
});
</script>
<!Doctype html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="modal fade" id="Mpn" tabindex="-1" role="dialog" aria-labelledby="edit-modal-label">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form class="form-horizontal" id="edit-form">
<input type="hidden" id="dats" name="id" >
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 align="center" class="modal-title" id="edit-modal-label" >Save Changes</h4>
</div>
<div class="modal-body">
<div class="form-group" enctype="multipart/form-data">
<label for="username" class="col-sm-2 control-label">Image</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="Mimage" name="image" />
</br>
<input type="file" class="form-control" id="Limage" name="image" placeholder=""required>
</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="update" id="update">Update</button>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
<?php
if(($_POST['mode'])=='upd') {
$id = $_POST['id'];
echo $id;
$images = $_POST['images'];
echo $images;
$query = mysqli_query($con,"UPDATE image SET image = '$images' WHERE id = '".$_POST["id"]."'");
<img class="img-responsive" src= "upload/3.jpg" alt="image" id="Mimage" name="image" />
if($query == true) {
echo "File Uploaded";
}
}
?>
Context:
This code is to update the image in the database.This is not working properly when i uploading the image the image enters into the database but as C:fakepathimg.jpg.It is not entering into the actual folder.If it is get rid of fake path the image will be updated.The image displays as fakepath.If the path is correct i think the the image will be updated.

Related

I am trying to retrieve data from a database using ajax and populate in form that is in a bootstrap modal

I need a help here when I click on the edit button on the image below i expect to see data populated on a form in a bootstrap modal window I am using jquery ajax method to populate the data in the form of
and the edit modal image
Here is code for the home page
<?php require_once("connect.php"); ?>
<?php require_once("fetch.php"); ?>
<?php require_once("select.php"); ?>
<?php require_once("process.php"); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Home</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="css/style.css">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<ul class="nav nav-pills">
<li>Home</li>
</ul>
<button type="button" class="btn btn-primary pull-right" data-toggle="modal" data-target="#myModal">Add</button>
<table class="table" id="table">
<tr>
<th>S/N</th>
<th>Name</th>
<th>Email</th>
<th>Description</th>
<th>Edit</th>
<th>View</th>
<th>Delete</th>
</tr>
<?php
$query = "SELECT * FROM contact";
$runQuery = mysqli_query($connect, $query);
if(!$runQuery){
die("Could not run select query ".mysqli_error($connect));
}
$sn = 1;
while($row = mysqli_fetch_assoc($runQuery)){ ?>
<tr>
<td><?php echo $sn++ ?></td>
<td><?php echo $row["name"] ?></td>
<td><?php echo $row["email"] ?></td>
<td><?php echo $row["description"] ?></td>
<td>
<button type="button" data-toggle="modal" data-target="#myModal" class="btn btn-warning btn-sm edit-data" id="<?php echo $row['userid'] ?>">Edit</button>
</td>
<td>
<button type="button" data-target="#viewModal" data-toggle="modal" class="btn btn-primary btn-sm view-data" id="<?php echo $row['userid'] ?>">View</button>
</td>
<td>
<button type="button" class="btn btn-danger btn-sm del-data" id="<?php echo $row['userid'] ?>">Danger</button>
</td>
</tr>
<?php } ?>
</table>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Data</h4>
</div>
<div class="modal-body">
<div id="success" class="alert alert-success"></div>
<form class="form" method="POST" id="insertData">
<div id="nameError" class="alert alert-danger"></div>
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name" id="name">
</div>
<div id="emailError" class="alert alert-danger"></div>
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email" id="email">
</div>
<input type="hidden" name="userid" id="contactUserId">
<div id="descriptionError" class="alert alert-danger"></div>
<div class="form-group">
<label>Description</label>
<textarea name="description" id="description" class="form-control"></textarea>
</div>
<input type="submit" class="btn btn-primary" value="Add" name="add" id="add">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div id="viewModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">View Data</h4>
</div>
<div class="modal-body" id="contactDetail">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/myscript.js"></script>
</body>
</html>
This code is for entering and updating data in the database process.php
<?php
if(!empty($_POST)){
$name = $_POST["name"];
$email = $_POST["email"];
$description = $_POST["description"];
$userid = $_POST["userid"];
if($userid != ''){
$query = "UPDATE contact SET name = '$name', email='$email', description='$description' WHERE userid = $userid ";
$runQuery = mysqli_query($connect, $query);
if(!$runQuery){
die("Could not run query ".mysqli_error($connect));
}
}else{
$query = "INSERT INTO contact(name, email, description) VALUES ";
$query .=" ('$name', '$email', '$description')";
$runQuery = mysqli_query($connect, $query);
if(!$runQuery){
die("Could not run insert query ".mysqli_error($connect));
}
}
}
This code retrieves data from database
<?php
if(isset($_POST['userid'])){
$editId = (int)$_POST['userid'];
$query = "SELECT * FROM contact WHERE userid = $editId";
$runQuery = mysqli_query($connect, $query);
if(!$runQuery){
die("Could not run query ".mysqli_error($connect));
}
$getData = mysqli_fetch_assoc($runQuery);
echo json_encode($getData);
}
This is my js file
$(document).ready(function(){
$("#insertData").submit(function(event){
event.preventDefault();
if($("#name").val() == ""){
$("#nameError").css("display", "block").html("Name is required");
}else if ($("#email").val() == "") {
$("#emailError").css("display", "block").html("Email is required");
}else if ($("#description").val() == "") {
$("#descriptionError").css("display", "block").html("Description is required");
}else{
$.ajax({
url: "index.php",
method: "POST",
data: $("#insertData").serialize(),
success: function(data){
$("#success").css("display", "block").html("Data added");
$("#insertData")[0].reset();
}
});
}
});
$(document).on("click", ".edit-data", function(){
var contactId = $(this).attr("id");
$.ajax({
url:"index.php",
method: "POST",
data: {contactId:contactId},
dataType: "json",
success: function(data){
$("#name").val(data.name);
$("#email").val(data.email);
$("#description").val(data.description);
$("#contactUserId").val(data.userid);
$("#add").val("Update");
$("#myModal").modal("show");
}
});
});
$(document).on('click', '.view-data', function(){
var contactId = $(this).attr("id");
if(contactId != '')
{
$.ajax({
url:"index.php",
method:"POST",
data:{contactId:contactId},
success:function(data){
$('#contactDetail').html(data);
$('#viewModal').modal('show');
}
});
}
});
});
You are sending contactId and in your PHP you are looking for userid. Change your data to data: { userid: userid }.
$(document).on("click", ".edit-data", function() {
var userid = $(this).attr("id");
$.ajax({
url: "index.php",
method: "POST",
data: { userid: userid },
dataType: "json",
success: function(data) {
$("#name").val(data.name);
$("#email").val(data.email);
$("#description").val(data.description);
$("#contactUserId").val(data.userid);
$("#add").val("Update");
$("#myModal").modal("show");
}
});
});

PHP-jQuery-AJAX: How to POST values while using a form in Modal

I'm having an issue passing input and textarea values from a form in modal to AJAX so I can pass them to php.
The input field and textarea values are coming up blank when I submit the form in modal and jquery is not displaying any errors. It simply POST an empty (blank) string for each element.
for example, it shows something like this.
subject=&content=
in the dialog box, I load a name and an ID and both POST successfully but the input values which are not loaded with the form, are not being sent. I understand that the name and ID do POST because they are loaded on DOM along with the form but I do not know how to pass values that are not loaded along with the form in modal.
This is a sample of the form.
<?php while($row = mysqli_fetch_array($res)){
//row data for each post
$r_id = $row['r_id'];
$name = $row['name'];
?>
<div id="m_f_box" class="modal fade msg-box-custom" tabindex="-1" data-width="400">
<div class="modal-header-custom">
<h5 class="modal-title">Send to <span><?php echo $name ?></span></h5>
</div>
<form id="user_m_form" name="user_m_form" action="#" method="POST">
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<div id="s_row" class="col_full">
<h5>Asunto</h5>
<input id="m_subject" name="m_subject" class="required sm-form-control" type="text" maxlength="40"></input>
</div>
<div id="m_row" class="col_full">
<h5>Mensaje</h5>
<textarea id="m_content" name="m_content" class="required sm-form-control" type="text"></textarea>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" id="send_m" name="user_m_form" class="button button-mini button-blue" value="<?php echo $r_id ?>">Send</button>
<button type="button" id="can_m" name="can_m" data-dismiss="modal" class="button button-mini button-blue">Cancel</button>
</div>
</form>
</div>
<?php } ?>
This is a sample of the jquery/ajax call.
<script type="text/javascript">
$(document).on('click', '#send_m', function(e){
e.preventDefault();
var r_id = $('#send_m').val();
var subject = $('#m_subject').val();
var content = $('#m_content').val();
//var form_data = $('#user_m_form').serialize(); test with serialized form data.
//alert(subject); test what is being sent as an alert
//console.log(subject); test what is being sent to view in console
$.ajax({
type:'POST',
url:'test_file.php',
data: { r_id : recipient_id,
subject : subject,
content : content,
},
cache: false,
success:function(res){
//do some stuff
}
});
return false;
});
</script>
Any ideas on why and/or how to POST these values?
Thanks in advance,
Note: Excuse the formatting for the HTML portion. It's hard to properly format everything using a phone.
Note: If you are trying to define multiple modal using while loop,
Your HTML
<div id="m_f_box" class="modal fade msg-box-custom" tabindex="-1" data-width="400">
<div class="modal-header-custom">
<h5 class="modal-title">Send to <span><?php echo $name ?></span></h5>
</div>
<form id="user_m_form" name="user_m_form" action="#" method="POST">
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<div id="s_row" class="col_full">
<h5>Asunto</h5>
<input id="m_subject_<?php echo $row['r_id']; ?>" name="m_subject" class="required sm-form-control" type="text" maxlength="40"></input>
</div>
<div id="m_row" class="col_full">
<h5>Mensaje</h5>
<textarea id="m_content_<?php echo $row['r_id']; ?>" name="m_content" class="required sm-form-control" type="text"></textarea>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" id="<?php echo $row['r_id']; ?>" name="user_m_form" class="button button-mini button-blue send" value="<?php echo $r_id ?>">Send</button>
<button type="button" id="can_m" name="can_m" data-dismiss="modal" class="button button-mini button-blue">Cancel</button>
</div>
</form>
</div>
<?php } ?>
Your Script
<script type="text/javascript">
$(document).on('click', '.send', function(e){
var r_id = (this).attr('id');
var subject = $('#m_subject'+id).val();
var content = $('#m_content'+id).val();
//......
//.......
});
</script>
Note: You just need to understand the JQuery selector (ID and Class). See the difference between #ID and .Class selectors in Jquery.
You are generating multiple Modal with same ID and try to get those field values using IDs (selector). But the IDs for each modal input fields must be unique to get the value. and for on click operation the button must have unique ID or you just need to define class as above code has.
See how I have defined class for click button and getting ID for each modal. Modal must be unique in the sense of their field.
Example done POST request with Ajax call on ModalBox
My View page code:
<div class="panel panel-default">
<div class="panel-body">
<p class="text-danger">There are total <span class="text-bold">{{ sizeof($data) }}</span> Departments.</p>
<table class="table" id="department-data">
<tr>
<th>#</th>
<th>Name</th>
<th>Edit</th>
<th>Delete</th>
<th>Manage</th>
</tr>
<?php $order = 0; ?>
#foreach($data as $key)
<tr>
<td>{{ ++$order }}</td>
<td id="department_name">{{ $key->title }}</td>
<td>
<a href="#">
<button class="btn btn-default edit-department" data-toggle="modal" data-target="#updateDepartmentModel" id="{{ $key->id }}"><i class="fa fa-pencil"></i></button>
</a>
</td>
<td>
<button id="{{ $key->id }}" class="btn btn-danger delete-btn" data-toggle="modal" data-target="#delete-department"><i class="fa fa-trash"></i></button>
</td>
<td>
<a href='program/{{ $key->id }}' id="delete-id">
<button class="btn btn-primary"><i class="fa fa-cog"></i></button>
</a>
</td>
</tr>
#endforeach
</table>
</div>
</div>
Modals on the same page:
<!-- Add New Department Modal -->
<div class="modal fade" id="newDepartmentModel" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Add New Department</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form action="{{ url('department/create') }}" method="POST">
{{ csrf_field() }}
<div class="modal-body">
<div class="form-group">
<label for="title">Department Name:</label>
<input type="text" class="form-control" id="title" name="title">
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Add</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
<!-- ./Model -->
<!-- Update Department Modal -->
<div class="modal fade" id="updateDepartmentModel" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Update a Department</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form>
<div class="modal-body">
<div class="form-group">
<label for="old-title">Department Name:</label>
<input type="text" class="form-control" id="old-title" name="title">
</div>
</div>
<div class="modal-footer">
<button type="submit" id="edit-dept" class="btn btn-primary edit-dept">Edit</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
<!-- ./Model -->
Here is Script:
<script type="text/javascript">
var token = '{{ Session::token() }}';
var url = '{{ route('department/edit') }}';
var dept_id = '';
// Setup Ajax
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
// Update the department
$(document).on('click', '.edit-department', function () {
var department_id = $(this).attr('id');
console.log(department_id);
dept_id = department_id;
$.get('department/'+department_id, function (data) {
$('#old-title').val(data.title);
console.log(data);
});
});
// Handle Post Request (Edit Department)
$(document).ready(function () {
$('#edit-dept').click(function () {
$.ajax({
method: 'POST',
url: url,
data: { id: dept_id, title: $('#old-title').val(), _token: token},
dataType: 'JSON'
}).done(function (data) {
//console.log(data);
});
});
});
</script>
Routes is:
Route::post('department/edit', function (\Illuminate\Http\Request $request){
$id = $request->input('id');
$title = $request->input('title');
DB::table('departments')->where('id', $id)->update(array('title' => $title));
return redirect('department')->with('alert_info', 'Department was successful Update!');})->name('department/edit');
Put this line on page Head:
<!-- csrf for meta -->
<meta name="csrf-token" content="{{ csrf_token() }}" />
And in Controller Create and Get routes:
Route::post('department/create', 'DepartmentController#store');
Route::get('department/{id}', 'DepartmentController#showById');
And these definitions:
public function store(StoreDepartmentPostRequest $request)
{
$department = new Department;
$department->title = $request->input('title');
$department->timestamps = time();
$department->save();
return redirect('department')->with('alert_success', 'Department was successful added!');
}
public function showById($id){
$data = Department::findOrFail($id);
return response()->json($data);
}

Jquery ajax not working in bootstrap modal

I tried using jquery ajax to send a request to a php file, but it wasn't working.
I've searched many topics to see if they could be of help but all to no avail.
Here is my code.
NOTE: the variable are well declared but to save time, I may not be able to post them all because they are fetched from the database.
foreach($fetch_products as $row)
{
$i++;
$start_from = $i+$offset;
$super_id = $row['super_id'];
$super_name = $row['name'];
?>
<div class="modal inmodal" id="EditModal<?php echo $super_id;?>" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content animated flipInY">
<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"><i class="fa fa-pencil"></i> Edit <?php echo $super_name;?></h4>
</div>
<div class="modal-body">
<form id="update_super_product_form<?php echo $super_id;?>" action="" method="post" class="form-horizontal">
<input type="hidden" name="super_id" value="<?php echo $super_id;?>"/>
<input type="hidden" name="current_page" value="<?php echo $current_page;?>"/>
<input type="hidden" name="per_page" value="<?php echo $per_page;?>"/>
<label>Product name</label>
<input type="text" name="product_name" id="product_name" value="<?php echo $super_name;?>" class="form-control">
<br/>
<div id="update_super_product_status<?php echo $super_id;?>"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-white" data-dismiss="modal"><i class="fa fa-times-circle"></i> Close</button>
<button type="submit" id="update_super_product_btn<?php echo $super_id;?>" class="btn btn-primary"><i class="fa fa-check"></i> Save changes</button>
</div>
</form>
</div>
</div>
</div>
<script type='text/javascript'>
$("#update_super_product_form<?php echo $super_id;?>").submit(function(e)
{
e.preventDefault();
var current_page = "<?php echo $current_page;?>";
var per_page = "<?php echo $per_page;?>";
var data = new FormData($(this)[0]);
var btn = $("#update_super_product_btn<?php echo $super_id;?>");
var status = $("#update_super_product_status<?php echo $super_id;?>");
$.ajaxSetup(
{
beforeSend:function()
{
btn.attr("disabled",true);
btn.html("Please wait <img src='img/loading.gif'/>");
alert("xx");
},
complete:function()
{
btn.attr("disabled",false);
btn.html("<i class='fa fa-check'></i> Save changes");
alert("xxx");
}
});
$.ajax(
{
type: "POST",
data: data,
url: "gotcha.php?UpdateSuperProduct",
cache:false,
success: function(msg)
{
status.fadeIn("");
status.html(msg).delay(4000).fadeOut("slow");
btn.attr("disabled", false);
}
});
});
</script>
I'll be glad if you help.
Thanks

Bootstrap modal form submit not working

please i need someone to help me check if i'm missing something. The form in the Bootstrap modal wont submit.
my HTML codes for the modal (sidebar.php)
<!-- start Joel's 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">E-Logbook Entry</h4>
</div>
<div class="modal-body">
<form id="modal-form" method="post" action="notes_functions.php">
<fieldset>
<label>Log Entry</label>
<textarea rows="4" cols="50" class="form-control" name="note_content" placeholder="What have you learnt today?..."></textarea>
</form>
</div>
<div class = "modal-footer">
<button type = "button" class = "btn btn-default" data-dismiss = "modal">
Close
</button>
<input type="submit" name="submit" class="btn btn-default" id="submitnote" value="Submit" />
</div>
</div>
</div>
</div>
<!-- end Joel's modal -->
codes for the PHP file (notes_functions.php)
<?php
include_once 'database-config.php';
if (isset($_POST['submitnote'])) {
$noteContent = strip_tags($_POST['note_content']);
$sql = "INSERT INTO account_notes (note_contents) VALUES ('$noteContent')";
$dbh->exec($sql);
echo "New record created successfully";
echo "Log details = ".$note_contents;
}
?>
my AJAX codes for submitting the form
<script type="text/javascript">
var frm = $('#modal-form');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
dataType: "JSON",
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
</script>
I can't seem to spot the error :-(
your submit button is not in the form. place it in the form or add this to the button
form="modal-form"
like so:
<input type="submit" name="submit" class="btn btn-default" id="submitnote" value="Submit" form="modal-form" />
Two things:-
1.Instead of if (isset($_POST['submitnote'])) { use if (isset($_POST['submit'])) {
2.Put ev.preventDefault(); before $.ajax({

Passing variables to a bootstrap modal form

I have a table that shows film reviews stored in a mysql database. Each of these reviews can be edited with a form that resides within a bootstrap modal. The problem I have is I can't understand how to give each form within the modal a unique ID. At the moment the modal only ever echoes varibales from the first row of reviews in the database. Many thanks.
The Jquery
<script type="text/javascript">
//Edit Review
$(document).ready(function(){
$(".editReview").click(function (e) {
$('#myModal').modal({
e.preventDefault();
var username = $(this).data("username");
var film_id = $(this).data('filmid');
var id = $(this).data('id');
var review = $(this).data('review');
$.post('ajax_editReview.php', {username: username, film_id: film_id, id: id, review: review},
function(data){
$('#myModal').modal('hide');
$("#message").html(data);
$("#review").val('');
$("#message").fadeIn(500);
$("#message").fadeOut(2500);
});
return false;
});
});
</script>
The Form
<div class="container">
<?php
$sql = "SELECT * FROM user_reviews WHERE username='$username' ORDER BY DATE desc";
$result = $db_conx->query($sql);
while($row = $result->fetch_assoc()) {
$id = $row['id'];
$film_id = $row['film_id'];
$review = $row['review'];
$movie = $tmdb->getMovie ($film_id);
echo '
<div class="row">
<div class="col-md-1">
<img id="image1" src="'. $tmdb->getImageURL('w150') . $movie->getPoster() .'" width="80" />
</div>
<div class="col-md-4">
<h3>
' . $movie->getTitle() .'
</h3>';
<p>
'.$review. '
</p>
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-success btn-xs pull-right" data-toggle="modal" data-id="'.$id.'" data-username="'. $username.'" data-filmid="'.$film_id .'" data-target="#myModal">edit review</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><h3> Edit your review for '. $movie->getTitle().'</h3></h4>
</div>
<div class="modal-body">
<form>
<div class="editReview">
<div class="form-group">
<label for="review">Review:</label>
<textarea class="form-control" rows="5" id="review" placeholder="'. $review.'" name="review"></textarea>
<input type="hidden" id="username" name="username" value="'.$username.'">
<input type="hidden" id="film_id" name="film_id" value="'. $film_id.'">
<input type="hidden" id="film_title" name="film_title" value="'.$movie->getTitle.'">
<input type="hidden" id="id" name="id" value="'.$id.'">
</div>
<button type="submit" id="FormSubmitReview" data-dismiss="modal" class="btn btn-danger btn-sm pull-right">Save Review</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-7">
</div>
</div>';
}
?>
You need to have the modal only once on your page and it seems like you a creating a new one for every review, you don't need to do that, just output it once.
You then need to use the event show.bs.modal like so.
$('#myModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var username = button.data("username");
var film_id = button.data('filmid');
var id = button.data('id');
var review = button.data('review');
....
});

Categories