I've got a forum in which user is allowed to edit and delete only his comments, I've defined an "edit" button, that by a click of mouse brings down a modal, and in that modal user is allowed to get access to the data's he/she has been sent before, I've written an ajax to target these field and update them whenever the users clicks on "edit" button, code totally makes sense, but so far the functionality doesn't, to make it more clear, user clicks, modal comes down, whatever he/she has been posted will appear in fields, and there is an "edit" button at the bottom of modal, which is responsible for changing and updating data. here is the modal code :
<button id="btn-btnedit" class="btn btn-primary " data-toggle="modal" data-target="#myModal<?php echo $list['id']; ?>">
Edit <i class="fa fa-pencil-square-o"></i>
</button>
<!-- Modal -->
<div class="modal fade" id="myModal<?php echo $list['id']; ?>" 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 class="container">
<form style="width: 550px;" action="" method="post" id="signin-form<?php echo $list['id']; ?>" role="form">
<input type="hidden" name="commentID" value="<?php echo $list['id']; ?>">
<div class="from-group">
<label for="title">Title: </label>
<input class="form-control" type="text" name="title" id="txttitle" value="<?php echo $list['title']; ?>" placeholder="Page Title">
</div>
<div class="from-group">
<label for="label">Label: </label>
<input class="form-control" type="text" name="label" id="txtlabel" value="<?php echo $list['label']; ?>" placeholder="Page Label">
</div>
<br>
<div class="from-group">
<label for="body">Body: </label>
<textarea class="form-control editor" name="body" id="txtbody" row="8" placeholder="Page Body"><?php echo $list['body']; ?></textarea>
</div>
<br>
<input type="hidden" name="editted" value="1">
<br>
<br>
<input type="submit" id="btnupdate" value="Edit">
</form>
</div>
</div>
as you can see I've assigned "editted" to my "name" attribute, which is later on used to call the query in the database, sql code is as below :
case 'postupdate';
if(isset($_GET['editted'])){
$title = $_GET['title'];
$label = $_GET['label'];
$body = $_GET['body'];
$action = 'Updated';
$q = "UPDATE posts SET title ='".$title."', label = '".$label."', body = '".$body."' WHERE id = ".$_GET['commentID'];
$r = mysqli_query($dbc, $q);
$message = '<p class="alert alert-success"> Your Post Is Succesfully '.$action.'</p>' ;
}
and here is the ajax code snippet;
$('#btnupdate').click(function() {
var tempTitle = $('#txttitle').val();
var tempLabel = $('#txtlabel').val();
var tempBody = $('#txtbody').val();
var tempUrl = "index.php?page=postupdate"+"&title="+tempTitle+"&label="+tempLabel+"&body="+tempBody+"&commentID=30&editted=1";
$.get(tempUrl);
});
I assume there is nothing advance about this segment of code, and i'm missing something very simple, any consideration is highly appreciated :)
This (untested code) may be similar to what you should do:
$('#btnupdate').click(function() {
var tempTitle = $('#txttitle').val();
var tempLabel = $('#txtlabel').val();
var tempBody = $('#txtbody').val();
var tempParams = {"page":"postupdate","title":tempTitle,"label":tempLabel,"body":tempBody,"commentID":30,"editted":1};
$.post("index.php",tempParams,function(data) {
alert(data);
});
});
UPDATE
Try ajax instead of get to see if some error occurs in the loading
$.ajax( {url:"index.php",data:tempParams,type: "POST"} ).done(function() {
alert( "success" );
}).fail(function() {
alert( "error" );
}).always(function() {
alert( "complete" );
});`
UPDATE
Start testing if the click handler works then (just to be sure!):
$('#btnupdate').click(function() { alert("yes at least the button was pressed"); });
UPDATE
Start testing if the script gets executed then:
alert("yes at least the script gets executed");
$('#btnupdate').click(function() { alert("yes at least the button was pressed"); });
If not you must have a javascript error somewhere.
https://webmasters.stackexchange.com/questions/8525/how-to-open-the-javascript-console-in-different-browsers
If yes, your button does not get caught by JQuery (no idea why)
anyway it's got nothing to do with ajax or get!
Related
I'm trying to pass data from my database into a modal form. The purpose of this modal is so users can edit their data within the database and then save the changes to said data.
I've tried many tutorials on YouTube, as well as reading previous responses on this site using methods such as doing it through Ajax and Bootstrap Modal Event Listener & Ajax and jQuery Click function but due to my inexperience with these programming languages I've yet to understand as the examples are vastly different to my project. Below is my code for form as well as the tables in my database
Button used to open the modal:
<a class="badge badge-success p-2" role="button" data-toggle="modal" data-target="#editPostModal">Edit</a>
Modal:
<div class="modal fade" id="editPostModal" tabindex="-1" role="dialog"aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Update Post</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form action="editdata.inc.php" method="POST" enctype="multipart/form-data"> // PHP File I would like to use to run a possible "update" query
<div class="modal-body">
<div class="form-group">
<input type="text" name="themeContent" class="form-control" placeholder = "Enter theme"/>
</div>
<div class="form-group">
<input type="text" name="visualIdeaContent" class="form-control" placeholder = "Enter idea"/>
</div>
<div class="form-group">
<input type="text" name="captionContent" class="form-control" value="<?= $captionContent; ?>" placeholder = "Insert caption"/>
</div>
<div class="form-group">
<input type="date" name="dateContent" class="form-control" placeholder = "Select date"/>
</div>
<div class="form-group">
<input type="text" name="linkContent" class="form-control" placeholder = "Insert URL"/>
</div>
<div class="form-group">
<input type="file" name="visualContent" class="custom-file" placeholder = "Upload picture"/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
<button type="submit" name="editdata" class="btn btn-primary">Save Changes</button>
</div>
</form>
</div>
</div>
Database
Name: annexcms
Table: content
uidContent // Unique ID
themeContent
visualIdeaContent
captionContent
dateContent
linkContent
visualContent
All in all, I expect the modal to:
1) Open and display data from the database tied to a specific User ID
2) Have the ability to save any changes made to that data when clicking the "Save Changes" button.
3) Have the saved data updated in the database.
This is the last part of my CRUD application as I've mastered the other three features. Appreciate any help I can receive.
You need 2 controller methods:
public function respondData($id)
{
//you can ever check if id exist here or if exist at all and
//throw any exeptions if not exist, this is just example
if($checkUser->exist($id))
{
$userData = array('id' => '1, 'name' => 'Name');
return json_encode($data);
}
throw new \Exeption('User does not exist');
}
public function saveData()
{
if($_POST)
{
if(($checkUser->exist($_POST['id'])))
{
//get value from POST and check and update
return true; // or message and parse it if it was ajax request
}
}
throw new \Exeption('Method not allowed');
}
JQUERY:
You need to get data from your user and bind it to modal
You can do this this way:
add data-user to you button or a link and other method to trigger modal opening:
$(document).on('click', '#your-link', function () {
var data = $(this).data('user');
$.post({
url: 'url_to_first_action' + '?id=' + data,
data: data,
success: function(data){
//here you parse JSON ARRAY to your fields
},
});
});
Now after user submit you data to second action you can do this with straight POST request or use the ajax to serialize() post.
So after tinkering with previous code, I got this to work.
My table:
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>Theme</th>
<th>Visual Idea</th>
<th>Caption</th>
<th>Date</th>
<th>Visual</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
$table = mysqli_query($conn ,'SELECT * FROM content');
while($row = mysqli_fetch_array($table)){ ?>
<tr id="<?php echo $row['uidContent']; ?>">
<td width="200" data-target="themeContent"><?php echo $row['themeContent']; ?></td>
<td width="300" data-target="visualIdeaContent"><?php echo $row['visualIdeaContent']; ?></td>
<td width="600" data-target="captionContent"><?php echo $row['captionContent']; ?></td>
<td width="100" data-target="dateContent"><?php echo $row['dateContent']; ?></td>
<td width="200" data-target="visualContent"><img id="imgsrc" src="<?php echo $row['visualContent']; ?>"width="200"/></td>
<td style = "display:none" width="100" data-target="linkContent"><?php echo $row['linkContent']; ?></td>
<td width="170">
<a class="badge badge-primary p-2" role="button" href="<?php echo $row['linkContent']; ?>" target="_blank">Link</a>
<a class="badge badge-success p-2" href="#" data-role="update" data-id="<?php echo $row['uidContent'] ;?>">Edit</a>
<a class="badge badge-danger p-2" role="button" href="action.inc.php?delete=<?php echo $row['uidContent'] ;?>" onclick="return confirm('Are you sure you want to delete this post? This process cannot be undone.');">Delete</a>
</td>
</tr>
<?php }
?>
</tbody>
</table>
The script:
<script>
$(document).ready(function(){
// Gets values in input fields
$(document).on('click','a[data-role=update]',function(){
var id = $(this).data('id');
var themeContent = $('#'+id).children('td[data-target=themeContent]').text();
var visualIdeaContent = $('#'+id).children('td[data-target=visualIdeaContent]').text();
var captionContent = $('#'+id).children('td[data-target=captionContent]').text();
var linkContent = $('#'+id).children('td[data-target=linkContent]').text();
var dateContent = $('#'+id).children('td[data-target=dateContent]').text();
var visualContent = $('#'+id).children('td[data-target=visualContent]').text();
$('#themeContent').val(themeContent);
$('#visualIdeaContent').val(visualIdeaContent);
$('#captionContent').val(captionContent);
$('#dateContent').val(dateContent);
$('#linkContent').val(linkContent);
$('#visualContent').val(visualContent);
$('#uidContent').val(id);
$('#updatePostModal').modal('toggle');
});
});
</script>
The only issue is that I'm not getting the image path to display as a thumbnail in the form, but I'll figure it out on my own through research.
My code is ugly, but at this point, I'm more concerned about the functionality. Thanks everyone.
I'm not sure why this modal isn't populating the post ajax data. Its actually supposed to update a row in my SQL DB upon success but the error I'm getting is "Uncaught TypeError: Cannot read property 'value' of null." Does anyone have any idea why this failing?
Updated: I apologize for leaving out the php which generated the partners item.
HTML:
while($row = mysqli_fetch_array($partners)) {
// $optionsPartners .="<option>" . $row['Partners'] . "</option>";
$optionsPartners.="<input type='checkbox' name='Partners[]' value=".$row['Partners']."> ".$row['Partners']."<br>";
}
$partnersmenu=
/*"<select name='Partners' id='Partners'>
" . $optionsPartners . "
</select>"*/
$optionsPartners;
?>
<div id="id02" class="modal">
<span onclick="document.getElementById('id02').style.display='none'"
class="close" title="Close Modal">×</span>
<!-- Modal Content -->
<form class="modal-content animate" action="modify_records.php" method="post">
<div class="container">
<h3>Edit an Existing Project</h3>
<label for="Project_Name" class="ui-hidden-accessible">Project Name:</label>
<input type="Project_Name" name="Project_Name" id="Project_Name" placeholder="Project Name">
<br><br>
<label for="Partners" class="ui-hidden-accessible">Partners:</label>
<?php
echo $partnersmenu;
?>
<br><br>
<input type="button" id="edit_button<?php echo $row['id'];?>" class="btn" value="Submit" data-dismiss="modal" onclick="edit_row('<?php echo $row['id'];?>');">
<button type="button" onclick="document.getElementById('id02').style.display='none'" class="cancelbtn">Cancel</button>
</div>
<div class="container" style="background-color:#f1f1f1">
</div>
</form>
</div>
PHP:
if(isset($_POST['edit_row']))
{
$row=$_POST['id'];
$Project_Name=$_POST['Project_Name'];
$Partners=$_POST['Partners'];
mysqli_query($conn,"update Project_Detail set Project_Name='$Project_Name',Partners='$Partners' where id=$row");
echo "success";
exit();
}
JS:
function edit_row(id)//save_row(id)
{
//var id=document.getElementById("id"+id).value;
var id=document.getElementById("id"+id);
var Project_Name=document.getElementById("Project_Name"+id).value;
var Partners=document.getElementById("Partners"+id).value;
$.ajax
({
type:'post',
url:'modify_records.php',
data:{
edit_row:'edit_row',
id:id,
Project_Name:Project_Name,
Partners:Partners,
},
success:function(response) {
if(response=="success")
{
//document.getElementById("id"+id).innerHTML=id;
document.getElementById("Project_Name"+id).innerHTML=Project_Name;
document.getElementById("Partners"+id).innerHTML=Partners;
//document.getElementById("edit_button"+id).style.display="block";
// document.getElementById("save_button"+id).style.display="none";
}
},
error: function(response) {
alert("some error");
}
});
}
I see a few problems and they all pertain to how you are calling you elements in your javascript and how your elements are labeled in your html.
Example:
<input type="Project_Name" name="Project_Name" id="Project_Name" placeholder="Project Name">
Should look like this:
<input type="text" name="Project_Name" id="Project_Name<?php echo $row['id']; ?>" placeholder="Project Name">
Look through all your elements and then look through your js so your are calling the correct ids.
Also in your html I copied in above, I changed the type to "text".
Also, I do not see an element with the id of "Partners" let alone "Partners" + id.
Hope that helps.
try
var id=document.getElementById("id");
instead of
var id=document.getElementById("id"+id);
I am working on a module where a dropdown modal has to appear after a duration of 3 mins on the page. It has an input field where digits has to be entered by the user and when he clicks on 'save', the modal should hide. Although I am getting the modal at correct time and when the digits are entered the values are being saved too but only the modal does not hides. I am just unable to figure out the reason behind it as the modal implementation is correct up to my knowledge. I am new to jquery and javascript so need suggestions and expertise of community. I am putting my code here, please have a look and any help or suggestion will be highly appreciated.
<div class="modal fade" id="myModal" role="dialog" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog">
<!-- Modal content-->
<form name="frmActive" id="frmActive" action="" method="post">
<div class="modal-content" style="height:250px;">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Ideal Time activation</h4>
</div>
<div class="modal-body">
<p>Please enter activation PIN:</p>
<p id="msg" style="color:#F00;"></p>
<input type="password" name="pin" id="pin" value="" maxlength="4" onKeyUp="checkNumber(this)" class="form-control" placeholder="Enter Pin">
<input type="hidden" id="inactiveTime">
</div>
<div class="modal-footer">
<button type="button" id="btnSubmit" name="submit" value="submit" class="btn btn-success"><i class="glyphicon glyphicon-floppy-disk"></i> Save</button>
<input type="hidden" id="module_id" value="<?php echo $moduleId ; ?>">
<input type="hidden" id="chapter_id" value="<?php echo $chapterId ; ?>">
</div>
</div>
</form>
</div>
</div>
jQuery("#btnSubmit").on("click", function(){
var pin = jQuery("#pin").val();
var chapter_id = jQuery("#chapter_id").val();
var module_id = jQuery("#module_id").val();
var nowDate = jQuery.now();
var inactiveTime = jQuery("#inactiveTime").val();
var seconds = (nowDate - inactiveTime) / 1000;
var formData = new FormData();
formData.append("pin", pin);
formData.append("seconds", seconds);
formData.append("module_id", module_id);
formData.append("chapter_id", chapter_id);
// $("#spinner").show();
$.ajax({
url: "processActivation.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
//dataType:'json',
success: function(result){
if(result == 'active')
{
$("#bt").html(result) ;
jQuery('#myModal').modal('hide');
}
else if(result == 'active')
{
jQuery('#myModal').modal('hide');
}
else
{
$("#msg").html(result) ;
}
}
});
});
And the ajax request being made for success,
$dataactivation = array("user_id"=>$uid, "module_id"=>$moduleId, "chapter_id"=>$chapterId,"time_taken"=>$time_taken, "created"=>$created);
$db->query_insert("tbl_activation", $dataactivation);
echo trim('active');
Please try console.log your result, you need to know the respond.
console.log(result);
here is the problem: if(result == 'active')
Remove echo trim('active');
change to : header('Content-Type: application/json', true, 200);
echo json_encode('active')); exit();
i hope you get it.
So I have been making a website where settings.php and saveSettings.php page where it insert $_POST functions to database.
Here is part of settings.php
echo '
<form action="saveSettings.php" method="POST">
<div class="form-group">
<textarea class="form-control no-resize" rows="4" id="profilecomment" name="profilecomment"></textarea>
</div>
<input type="submit" class="btn btn-success" name="submit" style="margin-top:10px" value="Submit" />
</form>
';
and here part of saveSettings.php
$userComment = $_POST["profilecomment"];
$updateComment = "UPDATE users SET comment = '$userComment' WHERE steamid = '$steamID' ";
header('Location: settings.php');
This is what I have tried:
I added my modal load script to settings.php page
<script>
$(window).load(function(){
$('#settingsSave').modal('show');
});
</script>
And modal script:
<div class="modal fade" id="settingsSave" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<p>You have successfully saved your settings!</p>
</div>
</div>
</div>
</div>
I am not sure if it does not popup because of that:
header('Location: settings.php');
I hope I can get some help.
First, please be aware of mysql Injection, I see you dont escape your POST parameters.
Do it like this:
$userComment = mysql_real_escape_string($_POST["profilecomment"]);
or use mysqli instead of mysql
To your question:
$(window).load(function(){
$('#settingsSave').modal('show');
});
is wrong, you must use something like:
$( document ).ready(function() {
<?
if(isset($_GET['save'])){
echo "$('#settingsSave').modal('show');";
}
?>
});
ans pass a parameter to your new location
header('Location: settings.php?save');
I have a drop down which i am filling from database (ss and source attached)
<div id="divmedium">
<label>Medium:</label> <a data-toggle="modal" role="button" href="#medium_m">[Add New Medium]</a>
<select data-placeholder="Select Medium" class="select-full" tabindex="2" id="media" name="media">
<option value=""></option>
<?php
$quee = 'SELECT `media_id` , `mediatype` FROM `media` WHERE `bus_id_fk` = "'. $_SESSION['bus_id_fk'].'" order by `mediatype` asc';
$rs=$DBH->query($quee);
while($row = $rs->fetch_assoc()){
echo "<option value=$row[media_id]>$row[mediatype]</option>";
}
?>
</select>
</div>
if i click on [Add New Medium] , a model appears in which i can add value.
<div id="medium_m" class="modal fade" tabindex="-1" role="dialog">
<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"><i class="icon-paragraph-justify2"></i> Add New Medium </h4>
</div>
<!-- Form inside modal -->
<form action="#" role="form" id="med1">
<div class="modal-body with-padding">
<div class="form-group">
<div class="row">
<div class="col-sm-9">
<label>First Medium</label>
<input type="text" name="fname" placeholder="Eugene" class="form-control">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-warning" data-dismiss="modal">Close</button>
<button type="submit" id = "m_btn" class="btn btn-primary">Submit form</button>
</div>
</form>
</div>
</div>
click on submit form (AJAX)
$(document).ready(function(){
$('#med1').submit(function(){
var formData = new FormData(this);
$.ajax({
type: 'POST',
url: 'addmedium.php',
//data: formData.serialize()
data: $(this).serialize()
})
.done(function(data){
$('#response').html(data);
if(data.status == 'success'){
$("#divmedium").html(data);
}else if(data.status == 'error'){
alert("Error on query!");
}
})
.fail(function() {
// just in case posting your form failed
alert( "Posting failed." );
});
// to prevent refreshing the whole page page
return false;
});
});
addmedium.php
<?php
session_start();
INCLUDE './config/databases.php';
header('Content-type: application/json');
$loc= $_POST['fname'];
$busid=$_SESSION['bus_id_fk'];
$sql = "INSERT INTO media (mediatype,bus_id_fk)VALUES ( '$loc','$busid' )";
//echo $sql;
if ($DBH->query($sql) === TRUE) {
// echo "New record created successfully";
} else {
// echo "Error: " . $sql . "<br>" . $DBH->error;
}
$response_array['status'] = 'success';
echo json_encode($response_array);
exit;
?>
Now the problem is
data getting inserted in the database but i am unable to refresh the
div,
After clicking on submit form model is not disappearing. i need to click on close or some where else besides model.
after clicking on Submit form , the div divmedium is disappearing.
Let me know what i am doing wrong.
I'll start from the end, if you won't mind.
after clicking on Submit form , the div divmedium is disappearing.
In your AJAX code $("#divmedium").html(data); you are replacing divmedium content with json_encode($response_array);
After clicking on submit form model is not disappearing. i need to click on close or some where else besides model.
I don't see any code that should close it. Try to add data-dismiss="modal"
data getting inserted in the database but i am unable to refresh the div
Same stuff as in 3rd question, check this and edit your AJAX success callback.