Hi im doing an App with Datatables and i have a problem when i want to try to edit a record in the datatables this is my js function in app.blade.php
$(document).on('click', '.editButton', function(e) {
e.preventDefault();
var id = $(this).data("id");
var editRoute = "{{ url('admin/user/' . auth()->user()->id . '/messages') }}";
console.log(id);
token();
$.ajax({
/* url: "{{ route('admin.messages.edit', ['user' => auth()->user()->id, 'message' => ':id']) }}".replace(':id', id), */
url: editRoute + "/" + id,
type: "GET",
/* dataType: 'json', */
success: function(result) {
console.log(result)
var message = result.data;
console.log(message);
$('.id').val(message.id);
$('.text').val(message.text);
$('.url').val(message.url);
$('.note').val(message.note);
$('.tipes').val(message.tipes);
$('.start_time').val(message.start_time);
$('.end_time').val(message.end_time);
$('.active').val(message.active);
$('#modalEdit').modal('show');
$('.modal-title').text('Update Message');
},
error: function(xhr, status, error) {
console.log(xhr.responseText);
}
});
});
the console.log(result) is empty and console.log(message) is undefined
this is the edit function in the controller
public function edit(Request $request)
{
$result = Message::where('id', $request->id)->first();
if ($result) {
return response()->json([
'message' => "Data Found",
"code" => 200,
"data" => $result
]);
} else {
return response()->json([
'message' => "Internal Server Error",
"code" => 500
]);
}
}
i want to edit the message with a modal, but the js fuction doesnt work properly, the var message is undefined
this is my route file
Route::middleware('auth')
->namespace('Admin')
->name('admin.')
->prefix('admin')
->group(function () {
Route::get('/', 'HomeController#index')->name('home');
Route::resource('/user', 'UserController');/* ->except(['edit', 'update']); */
Route::resource('/user/{user:id}/messages', 'MessagesController');
/* Route::resource('user.messages', MessagesController::class); */
});
Route::get('messages', 'Admin\MessagesController#getMessages')->name('get.messages');
Auth::routes();
this is my table structure
enter image description here
and its my form for edit the message
<div id="modalEdit" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Modal Header</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<form id="update">
<div class="modal-body">
<div class="form-group">
<label for="text">Testo</label>
<input type="text-area" class="form-control text" id="text" name="text">
</div>
<div class="form-group">
<label for="url">URL</label>
<input type="text" class="form-control" id="url" name="url">
</div>
<div class="form-group">
<label for="note">Note</label>
<input type="text" class="form-control" id="note" name="note">
</div>
<div class="form-group">
{{-- <label for="tipes">Tipo</label>
<input type="text" class="form-control" id="tipes" name="tipes"> --}}
<label for="tipes">Tipo</label>
<select name="tipes" id="tipes">
<option value="A">A</option>
<option value="B">B</option>
</select>
</div>
<div class="form-group">
<label for="start_time">Inizio</label>
<input type="date" class="form-control" id="start_time" name="start_time">
</div>
<div class="form-group">
<label for="end_time">Fine</label>
<input type="date" class="form-control" id="end_time" name="end_time">
</div>
<div class="form-group">
<label for="active">Attivo</label>
{{-- <input type="text" class="form-control" id="active" name="active"> --}}
<label for="active">Attivo</label>
<select name="active" id="active">
<option value="1">Si</option>
<option value="0">No</option>
</select>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Update</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
public function edit(Request $request,$id)
{
$result = Message::where('id', $id)->get();
if ($result) {
return response()->json([
'message' => "Data Found",
"code" => 200,
"data" => $result
]);
} else {
return response()->json([
'message' => "Internal Server Error",
"code" => 500
]);
}
}
you need to pass $id parameter into function edit! try it! may be it works
$(document).ready(function() {
$('.editbutten').on('click', function(e) {
e.preventDefault();
var id = $(this).data("id");
var editRoute = "{{ url('admin/user/' . auth()->user()->id . '/messages') }}";
console.log(id);
token();
$.ajax({
/* url: "{{ route('admin.messages.edit', ['user' => auth()->user()->id, 'message' => ':id']) }}".replace(':id', id), */
url: editRoute + "/" + id,
type: "GET",
/* dataType: 'json', */
success: function(result) {
console.log(result)
var message = result.data;
console.log(message);
$('.id').val(message.id);
$('.text').val(message.text);
$('.url').val(message.url);
$('.note').val(message.note);
$('.tipes').val(message.tipes);
$('.start_time').val(message.start_time);
$('.end_time').val(message.end_time);
$('.active').val(message.active);
$('#modalEdit').modal('show');
$('.modal-title').text('Update Message');
},
error: function(xhr, status, error) {
console.log(xhr.responseText);
}
});
});
});
Related
I'm writing a code for the system administrator to be able to reset the users' passwords in their accounts in case they forget said password.
I'm currently having problems passing the target user's ID through Ajax to change said user's password, through debugging tool, the system returns an "undefined" response for "id:", although the "_token" and "password" fields were sent fine.
HTML code for the form
<form id="form-reset-password">
<div class="container my-2">
<div class="row">
<div class="col-md-12">
<div class="form-row">
<input type="hidden" id="token" name="_token" value="{{csrf_token()}}">
</div>
<div class="form-group">
<label>New Password</label>
<input type="text" class="form-control" id="reset-password" name="password" readonly>
</div>
<div class="form-group text-right mt-4">
<button type="button" class="btn btn-dark" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success btn-confirmreset">Reset</button>
</div>
</div>
</div>
</div>
</form>
Javascript for generating the data-table where it shows the list of User accounts. On the side of the table, the admin can click a button to reset the password of said user.
$(document).ready(function() {
getRoles();
var accounts;
$('#account-management').addClass('active');
accounts = $("#table-accounts").DataTable({
ajax: {
url: "/users/get-all-users",
dataSrc: ''
},
responsive:true,
"order": [[ 7, "desc" ]],
columns: [
{ data: 'id'},
{ data: 'organization_name', defaultContent: 'n/a' },
{ data: 'first_name' },
{ data: 'last_name' },
{ data: 'email'},
{ data: 'student_number'},
{ data: 'role.name'},
{ data: 'created_at'},
{ data: null,
render: function ( data, type, row ) {
var html = "";
if (data.status == 1) {
html += '<span class="switch switch-sm"> <input type="checkbox" class="switch btn-change-status" id="'+data.id+'" data-id="'+data.id+'" data-status="'+data.status+'" checked> <label for="'+data.id+'"></label></span>';
} else {
html += '<span class="switch switch-sm"> <input type="checkbox" class="switch btn-change-status" id="'+data.id+'" data-id="'+data.id+'" data-status="'+data.status+'"> <label for="'+data.id+'"></label></span>';
}
html += "<button type='button' class='btn btn-primary btn-sm btn-edit-account mr-2' data-id='"+data.id+"' data-account='"+data.id+"'>Edit</button>";
html += "<button type='button' class='btn btn-secondary btn-sm btn-reset-password' data-id='"+data.id+"' data-account='"+data.id+"'><i class='fas fa-key'></i></button>";
return html;
}
},
],
columnDefs: [
{ className: "hidden", "targets": [0]},
{ "orderable": false, "targets": 7 }
]
});
Javascript for the random password generator and reset password
function resetPassword() {
$.ajax({
type: 'GET',
url: '/user/get-new-password',
processData: false,
success: function(data) {
$('#reset-password').val(data.password);
}
});
}
$(document).on('click', '.btn-reset-password', function() {
$('#reset-password-modal').modal('show');
resetPassword();
});
$(document).on('submit', '#form-reset-password', function() {
var confirm_alert = confirm("Are you sure you want to reset this account's password?");
if (confirm_alert == true) {
// var id = $(this).attr('data-id');
var id = $('.btn-confirmreset').attr('data-id');
$.ajax({
url: "/auth/reset-password",
type: "POST",
data: $(this).serialize()+"&id="+id,
success: function(data) {
if (data.success === true) {
alert("Password successfully reset!");
location.reload();
}
else {
alert("Something went wrong");
}
}
});
return false;
}
});
Thank you for your help!
<form id="form-reset-password">
<div class="container my-2">
<div class="row">
<div class="col-md-12">
<div class="form-row">
<input type="hidden" id="token" name="_token" value="{{csrf_token()}}">
<input type="hidden" id="user_id" name="user_id" value=""> // initiate the hidden input here
</div>
<div class="form-group">
<label>New Password</label>
<input type="text" class="form-control" id="reset-password" name="password" readonly>
</div>
<div class="form-group text-right mt-4">
<button type="button" class="btn btn-dark" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success btn-confirmreset">Reset</button>
</div>
</div>
</div>
</div>
</form>
<script type="text/javascript">
$(document).on('click', '.btn-reset-password', function() {
var user_id_value = $(this).attr('data-id'); // Get the user id from attr
$('#user_id').val(user_id_value); // Assign the user id to hidden field.
$('#reset-password-modal').modal('show');
resetPassword();
});
$(document).on('submit', '#form-reset-password', function() {
var confirm_alert = confirm("Are you sure you want to reset this account's password?");
if (confirm_alert == true) {
// var id = $(this).attr('data-id');
//var id = $('.btn-confirmreset').attr('data-id'); // Remove this, it won't work , because this button doesn't contain the data-id
var id = $('#user_id').val(user_id_value); // You can get the value from hidden field
$.ajax({
url: "/auth/reset-password",
type: "POST",
data: $(this).serialize()+"&id="+id,
success: function(data) {
if (data.success === true) {
alert("Password successfully reset!");
location.reload();
}
else {
alert("Something went wrong");
}
}
});
return false;
}
});
</script>
Please refer the above code, You can pass the user id while modal pop up call and set that id to hidden value. then you can access that id from the hidden input. when you submit "form-reset-password" form.
Please look at comments on the above code
Maybe the attr() function is looking for native HTML attribute. So use the following snippet will help.
var id = $('.btn-confirmreset').data('id');
I am using Laravel 6 and i would also like to say that i am not that much experienced working on Laravel.
I have searched SO and google as well but not got any solution to this problem. Below are the files and code
PordController.php
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Prod;
use App\Section;
use Illuminate\Support\Facades\Validator;
class ProdsController extends Controller
{
function __construct () {
$this->middleware('role:admin');
}
public function index(Request $request)
{
$tasks = Prod::orderBy('id', 'desc')->get();
$section = Section::all();
$arr['tasks'] = $tasks;
$arr['sections'] = $section;
return view('admin.pords',$arr);
}
public function store(Request $request)
{
$validator = Validator::make($request->input(), array(
'name' => 'required',
));
if ($validator->fails()) {
return response()->json([
'error' => true,
'messages' => $validator->errors(),
], 422);
}
if ($files = $request->file('fileUpload')) {
$destinationPath = public_path('images'); // upload path
$profileImage = rand() .".". $files->getClientOriginalExtension();
$files->move($destinationPath, $profileImage);
}
$task = Prod::create($request->all());
return response()->json([
'error' => false,
'task' => $task,
], 200);
}
public function show($id)
{
$task = Prod::find($id);
return response()->json([
'error' => false,
'task' => $task,
], 200);
}
public function update(Request $request, $id)
{
$validator = Validator::make($request->input(), array(
'name' => 'required',
));
if ($validator->fails()) {
return response()->json([
'error' => true,
'messages' => $validator->errors(),
], 422);
}
$task = Prod::find($id);
$task->name = $request->input('name');
$task->save();
return response()->json([
'error' => false,
'task' => $task,
], 200);
}
public function destroy($id)
{
$task = Prod::destroy($id);
return response()->json([
'error' => false,
'task' => $task,
], 200);
}
}
prods_add.blade.php
<!-- Add Task Modal Form HTML -->
<div class="modal fade" id="addTaskModal">
<div class="modal-dialog">
<div class="modal-content">
<form id="frmAddTask" enctype="multipart/form-data" method="POST">
<div class="modal-header">
<h4 class="modal-title">
add
</h4>
<button aria-hidden="true" class="close" data-dismiss="modal" type="button">
×
</button>
</div>
<div class="modal-body">
<div class="alert alert-danger" id="add-error-bag">
<ul id="add-task-errors">
</ul>
</div>
<div class="form-group">
<label>
name
</label>
<input class="form-control" id="name" name="name" required="" type="text">
</input>
</div>
<div class="form-group">
<label>
desc
</label>
<input class="form-control" id="desc" name="description" required="" type="text">
</input>
</div>
<div class="form-group">
<label>
member
</label>
<input class="form-control" id="member" name="member" required="" type="number">
</input>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>
isfiles allow
</label>
<input class="form-control" type="checkbox" id="isfile" name="isfile" value="true" checked>
</input>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>
camera allow
</label>
<input class="form-control" type="checkbox" id="isvideo" name="isvideo" value="true" checked>
</input>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>
mic allow
</label>
<input class="form-control" type="checkbox" id="ismic" name="ismic" value="true" checked>
</input>
</div>
</div>
</div>
<div class="form-group">
<label>
sections
</label>
<select id="section_id" name="section_id" class="form-control">
#foreach ($sections as $section)
<option value="{{$section->id}}">{{$section->name}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<div class="form-group">
<label for="file"> <div class="btn btn-primary btn-sm float-left">
<span>Choose file</span>
</div></label>
<input style="color:black" type="file" class="form-control-file" id="file" name="fileUpload">
</div>
</div>
</div>
<div class="modal-footer">
<input class="btn btn-default" data-dismiss="modal" type="button" value="cancel">
<button class="btn btn-info" id="btn-add" type="button" value="add">
add
</button>
</input>
</div>
</form>
</div>
</div>
</div>
pords.js
$(document).ready(function() {
$("#btn-add").click(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var car = 0;
var car1 = 0;
var car2 = 0;
var x = document.getElementById("isfile").checked;
if(x === true){
car = 1;
}
if(document.getElementById("isvideo").checked === true){
car1 = 1;
}
if(document.getElementById("ismic").checked === true){
car2 = 1;
}
console.log($("#file").get(0).files[0]);
var filess = $("#file").get(0).files[0];
$.ajax({
type: 'POST',
url: '/admincp/prods',
data: {
name: $("#frmAddTask input[name=name]").val(),
description: $("#frmAddTask input[name=description]").val(),
display: 1,
sessionid: 'sadasdasdasdasd',
password: 'sadasdasdasdasd',
fileUpload: filess,
img: "path",
member: $("#frmAddTask input[name=member]").val(),
isfile: car,
isvideo: car1,
ismic: car2,
section_id: $("#frmAddTask select[name=section_id]").val(),
},
processData: false,
dataType: 'json',
success: function(data) {
$('#frmAddTask').trigger("reset");
$("#frmAddTask .close").click();
window.location.reload();
},
error: function(data) {
var errors = $.parseJSON(data.responseText);
$('#add-task-errors').html('');
$.each(errors.messages, function(key, value) {
$('#add-task-errors').append('<li>' + value + '</li>');
});
$("#add-error-bag").show();
}
});
});
$("#btn-edit").click(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'PUT',
url: '/admincp/prods/' + $("#frmEditTask input[name=id]").val(),
data: {
name: $("#frmEditTask input[name=name]").val(),
},
dataType: 'json',
success: function(data) {
$('#frmEditTask').trigger("reset");
$("#frmEditTask .close").click();
window.location.reload();
},
error: function(data) {
var errors = $.parseJSON(data.responseText);
$('#edit-task-errors').html('');
$.each(errors.messages, function(key, value) {
$('#edit-task-errors').append('<li>' + value + '</li>');
});
$("#edit-error-bag").show();
}
});
});
$("#btn-delete").click(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'DELETE',
url: '/admincp/prods/' + $("#frmDeleteTask input[name=id]").val(),
dataType: 'json',
success: function(data) {
$("#frmDeleteTask .close").click();
window.location.reload();
pushnotify('تم الحذف بنجاح ');
},
error: function(data) {
console.log(data);
}
});
});
});
function addTaskForm() {
$(document).ready(function() {
$("#add-error-bag").hide();
$('#addTaskModal').modal('show');
});
}
function editTaskForm(task_id) {
$.ajax({
type: 'GET',
url: '/admincp/prods/' + task_id,
success: function(data) {
$("#edit-error-bag").hide();
$("#frmEditTask input[name=name]").val(data.task.name);
$("#frmEditTask input[name=id]").val(data.task.id);
$('#editTaskModal').modal('show');
},
error: function(data) {
console.log(data);
}
});
}
function deleteTaskForm(task_id) {
$.ajax({
type: 'GET',
url: '/admincp/prods/' + task_id,
success: function(data) {
$("#frmDeleteTask #delete-title").html("Delete Task (" + data.task.name + ")?");
$("#frmDeleteTask input[name=id]").val(data.task.id);
$('#deleteTaskModal').modal('show');
},
error: function(data) {
console.log(data);
}
});
}
The error in js file because without fetching the image value works great
When I add a value the image gets the error
The problem could be here:
$task = Prod::create($request->all());
try to make
public function store(Request $request)
{
dd($request->all());
}
and in network see the response.
also, when you make Prod::create($request->all());
it request everything like __token and so on
Sending data via POST form. Why doesn't the controller see all of the values? I've been playing around with the validation, so even setting those to 'required' doesn't change anything...
Form snippet:
<form action="{{ Protocol::home() }}/offers/make" method="POST" id="sendOffer">
<div class="modal-body">
<meta name="csrf-token" content="{{ csrf_token() }}">
<!-- Price -->
<div class="form-group" style="display:none;">
<label>{{ Lang::get('ads/show.lang_your_price') }}</label>
<input type="text" id="price_id" name="price" value="0">
<span class="help-block">{{ Lang::get('ads/show.lang_the_amount_required') }} <b>{{ Helper::getPriceFormat($ad->price, $ad->currency) }}</b></span>
</div>
<!-- location -->
<div class="form-group">
<label>location label</label>
<input type="text" placeholder="Andover MA" id="location_id" class="form-control" name="location_name">
</div>
<!-- Email Address -->
<div class="form-group">
<label>email label</label>
<input type="email" required="" placeholder="email" id="email_name" class="form-control" name="email_name">
</div>
<!-- Phone -->
<div class="form-group">
<label>phone label</label>
<input type="text" maxlength="12" placeholder="555-867-5309" id="friendNumber" class="form-control" name="phone_name">
</div>
<!--Time section-->
<div class="form-group">
<label>The time</label>
<input type="time" id="time_id" name="time_name"
min="9:00" max="18:00" required>
</div>
<!-- Post ID -->
<div class="form-group">
<label>{{ Lang::get('ads/show.lang_post_id') }} (for reference)</label>
<input type="text" readonly="" placeholder="{{ Lang::get('ads/show.lang_post_id') }}" id="postID" value="{{ $ad->ad_id }}" class="form-control" name="ad_id">
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success">{{ Lang::get('ads/show.lang_send_offer') }}</button>
</div>
</form>
Controller:
/**
* Make New Offer
*/
public function make(Request $request)
{
// Check ajax request
if ($request->ajax()) {
$rules = array(
'location_name' => '',
'email_name' => '',
'phone_name' => '',
'time_name' => '',
'ad_id' => 'required'
);
//run rules
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
// error
$response = array(
'status' => 'error',
'msg' => __(print_r($request->all())),
);
return Response::json($response);
}else{
// Get Inputs
$price = $request->get('price');
$location_name = $request->input('location_name');
$email_name = $request->input('email_name');
$phone_name = $request->input('phone_name');
$time_name = $request->input('time_name');
$ad_id = $request->input('ad_id');
$input = $request->all();
//let's figure it out:
dd($input);
// Success test
$response = array(
'status' => 'success',
'msg' => __('return/success.lang_offer_submitted'),
);
return Response::json($response);
Output in console (only showing price and ad_id for some reason):
array:2 [
"price" => "0"
"ad_id" => "1988726232"
]
Route:
// Make an Offer
Route::post('offers/make', 'Ads\OffersController#make');
The error was a result of me forgetting to include these fields in the ajax request smh
var _root = $('#root').attr('data-root');
var offerPrice = document.getElementById('offerPrice').value;
var postID = document.getElementById('postID').value;
var location_name = document.getElementById('location_name').value;
var email_name = document.getElementById('email_name').value;
var phone_name = document.getElementById('phone_name').value;
var time_name = document.getElementById('time_name').value;
$.ajax({
type: "POST",
url: _root + '/offers/make',
data: {
price: offerPrice,
ad_id: postID,
location_name: location_name,
email_name: email_name,
phone_name: phone_name,
time_name: time_name
},
Hi I am trying to send form data using ajax to my controller in Laravel. In my controller I am trying to return $request->all() to see if the form data is present. I am getting an error 500 internal server error and I am not sure why. I have setup my Exceptions/Handler.php to receive errors and also checked the error log.
Here is my HTML and Ajax:
<div class="container">
<div class="row">
<h1>Create your post</h1>
<div class="form-group">
<label for="title">Title</label>
<input type="text" name="title" id="title" class="form-control">
</div>
<div class="form-group">
<label for="post">Post</label>
<textarea name="post" rows="8" cols="80" id="post" class="form-control"></textarea>
</div>
<div class="form-group">
<label for="image">Add image</label>
<input type="file" name="image" id="image" class="form-control">
</div>
<input type="submit" name="submit" value="Submit Post" id="submit" class="btn btn-primary">
</div>
</div>
<script>
$(document).ready(function(){
$("#submit").on("click", function(e){
e.preventDefault();
var formData = new FormData();
var fileData = $('#image').prop('files')[0];
var title = $('#title').val();
var post = $('#post').val();
formData.append('fileData', fileData);
formData.append('title', title);
formData.append('post', post);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr("content")
}
});
$.ajax({
url:'/post/create/create',
type: "POST",
data: {
formData: formData
},
dataType: 'json',
success:function(response){
toastr.success(response.response);
},
error: function(error){
toastr.error(error.error)
}
});
});
});
</script>
Here is my controller:
public function create(Request $request) {
$request->all();
return response()->json(['responseText' => 'Success!'], 200)
}
missing ;
public function create(Request $request) {
$request->all();
return response()->json(['responseText' => 'Success!'], 200); //<--here
}
I have this textarea in my MVC project
<textarea id="edit-content" name="content" placeholder="Text content goes here">#Model.content</textarea>
but when I try to send this to a Json call like this
<script type="text/javascript">
function save() {
var $title = $('#edit-title'),
$content = $('#edit-content'),
$messageLoading = $('#message-edit-loading'),
$messageError = $('#message-edit-error'),
$id = $('#edit-id');
updateComment($id.val(), $title.val(), $content.val())
.done(function (data) {
if (data.IsValid()) {
$messageError.html('');
$messageError.removeClass('hidden');
$messageLoading.removeClass('hidden');
$messageLoading.html('The text is saved');
} else {
$messageError.removeClass('hidden');
$messageError.html(data.Message);
}
})
.fail(function (xhr, message) {
$messageError.removeClass('hidden');
$messageError.html('Registration failed: ' + message);
})
};
</script>
I get the original value of #Model.content instead of the new value.
Edit
my script.js code
function updateComment(id, title, content) {
return $.get("/Chapter/GetJSON_Update",
{
id: id,
title: title,
content: content
},
'json');
};
the entire code from my Edit.cshtml
#model Academia_Unitate.Models.Chapter
#{
ViewBag.Title = "Edit " + Model.title;
Layout = "~/Views/Shared/_Layout.cshtml";
}
#Html.Partial("~/Views/Shared/_TinyMCE.cshtml")
<div id="edit">
<h1>
Edit #Model.type.name
</h1>
<div class="" role="form">
<div class="form-group">
<label class="sr-only" for="title">Title</label>
<input class="form-control" type="text" id="edit-title" placeholder="Enter a title" value="#Model.title" required="required" />
</div>
<div class="form-group">
<label class="sr-only" for="content">Content</label>
<textarea id="edit-content" name="content" placeholder="Text content goes here">#Model.content</textarea>
</div>
<button type="submit" class="btn btn-success" id="save-btn" onclick="save()"><span class="glyphicon glyphicon-ok"></span> Save</button>
<span id="message-edit-loading" class="alert hidden"></span>
<span id="message-edit-error" class="alert alert-danger hidden"></span>
</div>
</div>
<input type="hidden" value="#Model.id" id="edit-id"/>
<script type="text/javascript">
function save() {
var $title = $('#edit-title'),
$content = $('#edit-content'),
$messageLoading = $('#message-edit-loading'),
$messageError = $('#message-edit-error'),
$id = $('#edit-id');
updateComment($id.val(), $title.val(), $content.val())
.done(function (data) {
if (data.IsValid()) {
$messageError.html('');
$messageError.removeClass('hidden');
$messageLoading.removeClass('hidden');
$messageLoading.html('The text is saved');
} else {
$messageError.removeClass('hidden');
$messageError.html(data.Message);
}
})
.fail(function (xhr, message) {
$messageError.removeClass('hidden');
$messageError.html('Registration failed: ' + message);
})
};
</script>
You most likely have more than one on your page, either make their id attributes unique or target the index in your jQuery.