Here is my code:
<td class="tedit">
<%= Html.ActionLink(item.Comments, "Comments", new { jobNumber = item.JobNumber, ordNumber = item.OrderNumber }, new { #class = "modalEdit" })%>
</td>
<div id="resultEdit" title="Edit Comments" style="display: none;">
<% Html.RenderPartial("AddComments", Model.InnerModel.RoadReportModelProp); %>
</div>
<script type="text/javascript">
$(document).ready(function () {
//initialize the dialog
$("#resultEdit").dialog({ modal: true, width: 300, resizable: true, position: 'center', title: 'Add Comments', autoOpen: false,
buttons: { "Save": function () {
var dlg = $(this);
dlg.Close();
}}
});
});
$(function () {
$('.modalEdit').click(function () {
//load the content from this.href, then turn it into a dialog.
$('#resultEdit').load(this.href).dialog('open');
$.unblockUI();
return false;
});
});
</script>
I need to send a POST request to the controller when I click on the SAVE button in the dialog, but I am not able to send a POST.
Please help.
You should be able to use $.post to save your data. For example
$.post(url, data, function(response) {
// Do something with response
});
You will need to collect the data from the dialog.
Regards,
Huske
<div>
<% using (Html.BeginForm("Post-FormActionName", "Controllername"))
{
%>
<div class="fieldsColumn">
<label>Name: *</label>
<%=Html.TextBoxFor("Name")%>
</div>
<div class="fieldsColumn">
<input id="submit" type="submit" value="Save"/>
</div>
<%}%>
</div>
You can use the following to Post, further, can you provide the code for the form you want to post, & also the controller you have created:
<script type="text/javascript">
$(document).ready(function() {
//get the form
var f = $("#idofForm");
var action = f.attr("action");
var serializedForm = f.serialize();
$.post(action, serializedForm, function() {
alert('we are back');
}
});
</script>
Related
I have created a Blog website and I want to add the functionality to delete a post object while clicking on the Delete button without rendering a separate HTML page rather using the confirm method in JavaScript.
And I have no idea to complete that.
i think you use a .remove method in model object or field
model.field.remove(model_object)
and use this for javascript confirm method
<button onclick="myFunction()">DELETE</button>
<p id="demo"></p>
<script>
function myFunction() {
var txt;
var r = confirm("Press a button!");
if (r == true) {
txt = "You pressed OK!";
} else {
txt = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
use this javascript code inside template where the delete button present
i Think this will help you
If you want to delete an object without reload the webpage, you will need to use ajax.
You can define a delete url for each post same as you generate an absolute url. It is easy to do. Here is my approach using jquery ajax and function based django view.
#models.py
class MyModel(models.Model):
def delete_url(self):
return reverse('delete-model', kwargs={'pk': self.id}
#views
def delete_model(request, pk):
item = get_object_or_404(Model, id=pk)
if item:
ref = item.id
item.delete()
data = {'ref': ref, 'message': 'Object with id %s has been deleted' %ref}
return JsonResponse(data)
#urls.py
path('delete/<pk>/', delete_model, name='delete-model')
$(document).ready(function () {
$(".comfirm-delete").click(function (e) {
e.preventDefault();
var proceed = confirm('Proceed with deletion');
if (proceed == true) {
var endpoint = $(this).attr('data-url')
$.ajax({
method: 'GET',
url: endpoint,
success: function (data) {
$.notify({
// options
title: '<b>Message<b> ',
message: data.message,
}, {
// settings
type: 'success',
delay: 3000,
allow_dismiss: true,
});
$("#item" + data.ref).hide(1000)
},
error: function (error_data) {
console.log(error_data);
$.notify({
title: '<b>Error</b><br>',
message: 'Sorry, something gone wrong'
}, {
type: 'danger',
delay: 3000,
})
}
})
} else {
e.preventDefault();
$.notify({
title: '<b>Action cancelled</b><br>',
message: 'This one is not <span class="text-danger">Deleted</span>'
}, {
type: 'info',
delay: 3000,
})
}
})
})
.comfirm-delete {
color: red;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-notify/0.2.0/css/bootstrap-notify.css" integrity="sha256-ibUTW+jDj+F8d1T1KZ4DOujRmVTFfvMKL9y14QgEaPQ=" crossorigin="anonymous" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-notify/0.2.0/js/bootstrap-notify.min.js"></script>
<table>
<tbody>
{% for obj in objects %}
<tr id="item{{obj.id}}">
<td>{{obj.info}}</td>
<td data-url="{{obj.delete_url}}" class="comfirm-delete">Delete</td>
</tr>
{% endfor %}
</tbody>
</table>
can someone please help me with this I am stuck and I need your help.. :/
So my problem is this:
I have on the left side the events(appointments) which contain data like(title and datetime) what I need is when I drag the event and drop on the calendar this event holds the data info I want that to automaticlly go to that date slot, so to be pulled to that date slot even though i dropp it somwhere else.
So this is my code:
<div id='external-events'>
#foreach($appointments as $appointment)
<div class='fc-event {{ $colors[array_rand($colors)] }}' apo_id="{{$appointment->id}}" >
{{$appointment->firstname}} <br>{{$appointment->start_at}}</div><br>
#endforeach
<p>
<input type='checkbox' id='drop-remove' checked/>
<label for='drop-remove'>remove after drop</label>
</p>
</div>
<div class="tab-content tabcontent-border">
<?php $i=1; ?>
#foreach($agents as $key=> $agent)
<div class="tab-pane agent tabs{{$key}}" id="agent{{$agent->id}}" agent_id="{{$agent->id}}" role="tabpanel">
<div class="card-body b-l calender-sidebar">
<div id='calendar-container'>
<div id='calendar{{$agent->id}}' class="calendar" agent-id="{{{$agent->id}}}"></div>
</div>
</div>
</div>
<?php $i++; ?>
#endforeach
</div>
And here I have my js:
<script src="{{ asset('app/assets/libs/fullcalendar/dist/fullcalendar.min.js') }}"></script>
<script>
$(document).ready(function(){
var appointments = <?php echo json_encode($appointments_agents) ?>;
console.log(appointments);
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
var agent_id = $(e.target).attr("agent_idja")
$('#external-events .fc-event').each(function() {
$(this).data('event', {
title: $.trim($(this).text()),
stick: true
});
$(this).draggable({
zIndex: 999,
revert: true,
revertDuration: 0
});
});
var getEvent = [];
for(i=0; i<appointments.length; i++)
if(appointments[i]['agent_id'] == agent_id){
var firstname = appointments[i]['firstname'];
var start_at = appointments[i]['start_at'];
color1 = '#000',
color2 = '#ef6e6e',
color3 = '#22c6ab',
color4 = 'yellow'
var colors = [color1,color2,color3, color4];
var colorss = colors[Math.floor(Math.random()*colors.length)];
var insertEvents = {};
insertEvents =
{
title: firstname,
start: start_at,
color : colorss,
}
getEvent.push(insertEvents);
}
$('#calendar' + agent_id).fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
droppable: true,
events: getEvent,
drop: function(event) {
var apo_id = $(this).attr('apo_id');
console.log(agent_id);
$.ajax({
method: "POST",
url: "{{ url('/change-agent') }}",
data: {
_token: "{{ csrf_token() }}",
agent_id: agent_id,
appointment_id:apo_id
},
success: function () {
console.log("ok");
},
error: function () {
console.log("error");
}
});
if ($('#drop-remove').is(':checked')) {
$(this).remove();
}
}
});
});
});
</script>
So here I am using this js for showing events that are alreay assigned to an agent, and with ajax on drop to assign to that agent of that selected tab.
But as I explained the event wont be pulled to that particular slot. Can you please help..?
I'm creating a blog on laravel and so far I have the successful js code for posts that contain a title and content. But I'm having some trouble writing the js function for tags.
I would like to do the same for tags but I'm getting errors on everything I try.
<script src="https://cloud.tinymce.com/stable/tinymce.min.js?apiKey=fg5tc8gb4rtw6p9n3njd2hi4965rketxda84pbcfs09hb5x2"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tinymce/4.6.4/tinymce.min.js"></script>
<script type="text/javascript">
tinymce.init({
selector: '.myeditablediv',
plugins: 'code , save, autoresize , textcolor colorpicker , emoticons, textpattern , wordcount',
toolbar: 'save , restoredraft , forecolor backcolor, emoticons',
save_onsavecallback: function () {
var content = tinymce.activeEditor.getContent();
console.log(content);
}
});
$(document).on('click', '#SubmitBtn', function () {
var content = tinymce.activeEditor.getContent();
var data = {
'title': $('#title').val(),
'content': content,
'_token': '{{csrf_token()}}'
};
$.post('/postData', data, function () {
console.log(data);
});
});
</script>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Create the title</h1>
<form>
{{csrf_field()}}
<label for="title">Click here to edit the title of your post!</label>
<input type="text" name="title" id="title"/>
<h1>Create the content</h1>
<div class="myeditablediv">Click here to edit the content of your post!</div>
</form>
<input type="button" name="Submit" id="SubmitBtn" value="Submit"/>
</body>
</html>
<script src="https://cloud.tinymce.com/stable/tinymce.min.js?apiKey=fg5tc8gb4rtw6p9n3njd2hi4965rketxda84pbcfs09hb5x2"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tinymce/4.6.4/tinymce.min.js"></script>
<script type="text/javascript">
tinymce.init({
selector: '.myeditabletag', // change this value according to your HTML
menu: {
view: {title: 'Edit', items: 'cut, copy, paste'}
},
save_onsavecallback: function () {
var content = tinymce.activeEditor.getContent();
console.log(content);
}
});
$(document).on('click', '#SubmitBtn', function () {
var name = tinymce.activeEditor.getContent();
var data = {
'name': name,
'_token': '{{csrf_token()}}'
};
$.post('/postTags', data, function () {
console.log(data);
});
});
</script>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Create a new Tag</h1>
<form>
{{csrf_field()}}
{{--<input type="text" name="name" id="name"/>--}}
<div class="myeditabletag">Click here to edit the name of your tag!</div>
</form>
<input type="button" name="Submit" id="SubmitBtn" value="Submit"/>
</body>
</html>
Here is the route for /postData for tags and posts:
Route::post('/postTags', ['uses' => 'TagController#store']);
Route::post('/postData', ['uses' => 'PostController#store']);
And here is the PostController and TagController store method:
public function store(Request $request)
{
$post = new Post;
$post->title = $request['title'];
$post->content = $request['content'];
$post->save();
}
public function store(Request $request)
{
$tag = new Tag;
$tag->name = $request['name'];
$tag->save();
}
You have a mistake in your JS code. You are selecting an ID that doesn't exist. You need to select the content of the changed tag, and send that as the data['name']. Try the following code:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tinymce/4.6.4/tinymce.min.js"></script>
<script type="text/javascript">
tinymce.init({
selector: '.myeditabletag', // change this value according to your HTML
menu: {
view: {title: 'Edit', items: 'cut, copy, paste'}
},
save_onsavecallback: function () {
var content = tinymce.activeEditor.getContent();
console.log(content);
}
});
$(document).on('click', '#SubmitBtn', function () {
var name = tinymce.activeEditor.getContent();
var data = {
'name': name,
'_token': '{{csrf_token()}}'
};
console.log(data);
$.post('/postTags', data, function () {
});
});
</script>
I have the following script which is rendering a partial view inside a dialog box:
$(function () {
$('#addressLookupBtn').click(function () {
$('#dialog').dialog({
title: 'Address Lookup Tool',
modal: true,
width: '1200',
height: 'auto',
resizable: false,
show: {
effect: "fade",
duration: 2000
},
hide: {
effect: "fade",
duration: 1000
},
open: function (event, ui) {
//Load the AddressLookup action which will return
//the partial view: _AddressLookup
$(this).load("#Url.Action("AddressLookup", new { evpId = Model.EvpId })");
}
}).dialog('open');
});
});
The problem is, when I submit the partial view, there are 2 POSTS being made to the server, I think the submit for the partial view is also being bound to the $('#addressLookupBtn').click. Can anyone see where I'm going wrong?
more info
Partial view
#using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "updatearea" }))
{
<div id="updatearea" class="form-group">
<div style="width:300px; display:block; float:left;">
#Html.TextBox("PostCode", null, new { #class = "form-control" })
</div>
<div id="NewAddressLine">
<input type="submit" value="Lookup Postcode" class="btn btn-default" />
</div>
</div>
}
It looks like the post is being submitted using both a normal form submit and as a jquery event.
Perhaps change it to a button (instead of submit) and use only the jquery submit, or remove the jquery event and use only the normal form submit.
As per comments - An example of using jquery ajax instead of MS ajax:
The script:
$(document).ready(function() {
event.preventDefault(); // stop the form from submitting the normal way
$('#MyForm').submit(function(event) {
$.post(
$('#MyForm').attr('action'),
{ 'PostCode' : $('input[name=PostCode]').val() }
)
.done(function(data) {
alert('Post worked, and data was returned. Parse and/or present.');
$('#updatearea').html(data); //Replace the current contents of "updatearea" with the returned contents
});
});
});
The PartialView:
#using (Html.BeginForm("MyAction", "MyController", new { #id = "MyForm" }))
{
<div id="updatearea" class="form-group">
<div style="width:300px; display:block; float:left;">
#Html.TextBox("PostCode", null, new { #class = "form-control" })
</div>
<div id="NewAddressLine">
<input type="submit" value="Lookup Postcode" class="btn btn-default" />
</div>
</div>
}
It looks like you are calling open, and still have autoOpen set to true (it is true by default). This is causing open event to run twice. Try setting autoOpen to false
$('#dialog').dialog({
...
autoOpen: false,
...
});
https://api.jqueryui.com/dialog/#option-autoOpen
It turns out I didn't need to change anything other than move the following bundle reference from _Layout to my Edit view:
#Scripts.Render("~/bundles/unobtrusive-ajax")
I have an ajax function on the initialize of the main router that seems to hinder the event of my signin button in signin.js. When I click the signin button, it doesn't perform its function, instead the browser places the inputs on the URL, (i.e. username and password).
But when I remove the ajax function on the initialize, I can successfully log in.
I've included some of the codes I'm working on. Thanks
main.js
initialize: function(){
$.ajax({
type: "GET",
url: "something here",
contentType: "application/json",
headers: {
'someVar': something here
},
statusCode: {
404: function() {
console.log('404: logged out');
if (!this.loginView) {
this.loginView = new LoginView();
}
$('.pagewrap').html(this.loginView.el);
},
200: function() {
console.log('200');
if (!this.homeView) {
this.homeView = new HomeView();
}
$('.pagewrap').html(this.homeView.el);
}
}
});
// return false;
},
signin.js
var SigninView = Backbone.View.extend ({
el: '#signin-container',
events: {
"click #btn-signin" : "submit"
},
submit: function () {
console.log('signin');
$.ajax({ ... });
return false;
}
});
var toSignin = new SigninView();
window.anotherSigninView = Backbone.View.extend({
initialize: function() {},
render: function() {}
});
home.js
window.HomeView = Backbone.View.extend ({
initialize: function() {
this.render();
},
render: function() {
$(this.el).html( this.template() );
return this;
}
});
some html
<form id="signin-container">
<table id="tbl-signin">
<tr>
<td><div class="input-box"><input class="input-text" type="text" name="username" placeholder="Username"></div></td>
<td><div class="input-box"><input class="input-text" type="password" name="password" placeholder="Password"></div></td>
<td><input id="btn-signin" class="button" value="Sign In"></td>
</tr>
<tr>
<td class="opt"><input class="checkbox" type="checkbox" name="rememberMe" value="true"><label class="opt-signin">Remember Me?</label></td>
<td class="opt"><a class="opt-signin" href="#">Forgot Password?</a></td>
<td></td>
</tr>
</table>
</form>
You need to prevent the default behaviour of the submit button in your click handler. You can do this like so:
var SigninView = Backbone.View.extend ({
el: '#signin-container',
events: {
"click #btn-signin" : "submit"
},
submit: function (event) {
event.preventDefault();
console.log('signin');
$.ajax({ ... });
}
});
Alternatively, you might consider using the html button element which won't attempt to submit the form it's associated with.
Ok, I figured out what's your problem :)
Here is an example that resumes your code jsfiddle.net/26xf4/6. The problem is that you don't call new SigninView(); (instantiate the view) hence its events are never bound.
So, in this example try to uncomment the ligne 43 and your code will work as expected, because when you instantiate a View (new SigninView()) its constructor calls the delegateEvents() function (you don't see this in your code, it's in the backbone.js) enabling the events you declare in your view :
events: {
"click #btn-signin" : "submit"
},
I don't know about your HTML mockup, my best guess is that you are catching the incorrect event here. If you are submitting a form, you should catch submit form event not click #some-button. Because even if you catch click event of button inside a form and return false, the form will be still submitted because those are 2 different events