Print automatically on form close - laravel

I have a button that prints something and it works well.
I would like to print automatically when the form is closed.
At the moment the form sends an email to my customers with order details (it works very well) but now I would like to print automatically without requiring the user to push a button.
Please help me. I am a beginner here.
Relevant code:
<a
href="#!"
target="_blank"
id="save-and-print"
type="submit"
title="Speichern & Drucken">
<i class="fa fa-print"></i>
</a>
<script type="text/javascript" src="/js/summernote.js?v=0.72"></script>
<script>
$( function() {
$('#save-and-print').on('click', function (e) {
e.preventDefault();
var url = 'myOrders/replacement/' + '{{ $data->id }}';
}
});
$.ajax({
type: "PATCH",
url: '/myOrders/replacement/' + '{{ $data->id }}',
data: $("form").serialize(),
dataType: 'json',
success: function (data) {
window.location.reload();
location.href = '{{ route('print', [$data->id, 'option' => 'advance']) }}';
},
error: function (data) {
$('body').pgNotification({
style: 'flip',
message: 'Error',
position: 'top-right',
type: 'danger',
timeout: 4000
})
},
});
</script>

If you want the same action to take place on the submit event of your form as what happens when your id="save-and-print" button is being pressed, you could do something like this:
function printSomething(event) {
var url = 'myOrders/replacement/' + '{{ $data->id }}';
}
const form = document.getElementById('form');
form.addEventListener('submit', printSomething);

Related

How can I delete using ajax in laravel?

BLADE FILE
<td><button class="deleteuser" data-id="{{ $user->id }}" data-token="{{ csrf_token() }}" >DELETE</button>
</td>
AJAX
$(document).ready( function () {
$(".deleteuser").click(function(){
var id = $(this).data("id");
var token = $(this).data("token");
$.ajax(
{
url: "user/delete/"+id,
type: 'DELETE',
dataType: "JSON",
data: {
"id": id,
"_method": 'DELETE',
"_token": token,
},
success: function ()
{
console.log("it Work");
}
});
console.log("It failed");
});
});
CONTROLLER
public function destroyuser($id){
$this->authorize('Admin');
User::find($id)->delete($id);
return response()->json([
'success' => 'Record has been deleted successfully!'
]);
return view('viewuser');
}
If I click on delete button, there is no response. Any suggestion or correction will be appreciated. Thanks in advance
I don't know if the JS is in a different file but to check if the "$( document ).ready()" is working add a console.log() call at the beginning.
$(document).ready( function () {console.log("document is ready")
$(".deleteuser").click(function(){
Refresh the page and check if "document is ready" is logged to the console.
If it isn't then the javascript is not loading
Check if the route is properly defined
You can replace your url as this and check:
var id = data.id;
var url = "{{route('your_route',":id") }}";
url = url.replace(':id', id);
pass url in your ajax url param
Or make above changes:
BLADE FILE
<td>
<button style="background-color: red;" onclick="clickOffConfirmed" title="Delete" class="btn btn-sm btn-clean btn-icon btn-icon-md delete"><i class="la la-trash" style="color: white;"></i></button>
</td>
SCRIPT
<script>
$(document).ready(function() {
$(document).on('click', '.delete', function ()
{
var obj = $(this);
var id=$(this).closest('td').find(".delete_id").val();
var result = confirm("Are you sure want to delete?");
if(result)
{
$.ajax(
{
type: "POST",
url: "{{route('delete_method')}}",
data: {
'_token': $('input[name="_token"]').val(),
'id': id
},
cache: false,
success: function (data)
{
if (data.status === 'success')
{
window.location = "{{route('redirect_route')}}";
toastr["success"]("Deleted Successfully", "Success");
}
else if (data.status === 'error')
{
location.reload();
toastr["error"]("Something went wrong", "Opps");
}
}
});
}
});
});
</script>
Controller
public function delete_method(Request $request)
{
$del = ModelName::findOrFail($request->id)->delete();
if($del)
{
return response()->json(['status' => 'success']);
}
else{
return response()->json(['status' => 'error']);
}
}
Route
Route::post('/test/delete','TestController#delete_method')->name('delete_method');
In your ajax codes, change this:
url: "user/delete/"+id,
To:
url: "{{ url('user/delete') }}/" + id
If your ajax codes are inside of your blade file also you can use this way:
url: "{{ route('YOUR_ROUTE_NAME', $user->id) }}/"
You incorrectly define delete function!
change
User::find($id)->delete($id);
To
User::find($id)->delete();

On success, div is loading only once through AJAX

I am trying to reload the table on every successful quantity change and row deletion in add to cart using ajax. But the table is getting reloaded only once after that no change is being observed.
Here is the code:
<script type="text/javascript">
$(".update-cart").change(function (e) {
e.preventDefault();
var ele = $(this);
$.ajax({
url: '{{ route('update.cart') }}',
method: "patch",
data: {
_token: '{{ csrf_token() }}',
id: ele.parents("tr").attr("data-id"),
quantity: ele.parents("tr").find(".quantity").val()
},
success: function (response) {
$("#cart").load(" #cart");
//alert("This is working");
}
});
});
$(".remove-from-cart").click(function (e) {
e.preventDefault();
var ele = $(this);
if(confirm("Are you sure want to remove?")) {
$.ajax({
url: '{{ route('remove.from.cart') }}',
method: "DELETE",
data: {
_token: '{{ csrf_token() }}',
id: ele.parents("tr").attr("data-id")
},
success: function (response) {
$("#cart").load(" #cart");
}
});
}
});
Button id b1 can be clicked only once, id b2 can be live clicked.
function why(e) {
e.preventDefault();
alert("You clicked " + e.target.id);
$("#myDiv").html('<button id="b1" type="button">Click Me!</button><button id="b2" class="button" type="button">Click Me!</button>');
}
$("#b1").click(why);
$(document).on("click", ".button", why);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myDiv">
<button id="b1" type="button">Click Me!</button><button id="b2" class="button" type="button">Click Me!</button>
</div>

Ajax page is reloading after storing data

i am triyng to save data but my page is reloading with json message on next page, how can i stop reloading page.
Ajax Code:
jQuery(document).ready(function($) {
$("#add-data").submit(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "teachers",
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: $(this).serialize(),
success: function (data) {
alert("Added");
},
});
});
});
Submit Button:
<button type="submit" class="btn btn-secondary btn-lg shadow-lg rounded" value="ADD" id="add-data"> <span class=" fa fa-plus"> </span> ADD</button>
Store Controller:
after saving which is working fine:
return response()->json([
'status' => 'success',
'msg' => 'New esecond has been saved'
]);
It is because of you are trying to post the data to form .
If you use button type = "submit" it will redirect you to somewhere .
You should avoid using type = "submit" .
Instead use the type = "button"
<button type = "button" class="btn btn-secondary btn-lg shadow-lg rounded" value="ADD" id="add-data"> <span class=" fa fa-plus"> </span> ADD</button>
And achieve it by using click event of the button .
then get it in jquery .
$("#add-data").click(function (event) {
//Your code here
}
You can try this instead of prevent default. The reload happen, because you use form submit event.
$('#add-data').submit(false);
If you want to use prevent default, then use click event of the submit button to perform the action.
$("#add-data").click(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "teachers",
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: $(this).serialize(),
success: function (data) {
alert("Added");
},
});
}
Remove dataType: 'json' as you're already returning JSON otherwise your button seems perfect.
Try this
jQuery(document).ready(function($) {
$("#add-data").submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "teachers",
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: $(this).serialize(),
success: function (data) {
alert("Added");
},
});
});
});
Add "return false;" in the end of your submit callback..
As "add-data" is ID of your button, for your example it couldn't retrieve a submit event. That's because it submitted and didn't prevented.
So you can write something like this:
$("form").submit(function (event) {
event.preventDefault();
$.ajax({ ... });
return false; // <<< THE THING
});
Or just do that with binding an click event on button (not for submit event on button)
$("#add-data").click(function (event) {
event.preventDefault();
$.ajax({ ... });
});
With this you can leave button type, and don't need to change that to type="button".

Getting textbox value from X-editable

How do you get the value of the textbox field and send as data inside of ajaxOptions? I tested my view and it prints out the test variable successfully from my Django views. I am using X-editable for Jquery. Heres what textbox input looks like:
http://jsfiddle.net/xBB5x/197/
views.py
def create_post(request):
print request.POST.get("test", "");
return HttpResponse(json,content_type="application/json")
HTML
<a id="other1" data-pk="First Name" data-name="test">First Name</a>
AJAX
$(document).ready(function() {
$('#other1').editable({
type: 'text',
pk: 1,
url: '/create_post/',
ajaxOptions: {
data: {
csrfmiddlewaretoken: '{{ csrf_token }}',
test: "hi",
},
},
placement: 'top',
title: 'New Expense',
success: function(response, newValue) {
if(response.status == 'error') return response.msg; //ms
},
});
});
Instead of ajaxOptions, use params. If I remember correctly, test and its value will be included in your POST request by x-editable. Try something like this:
Html
<a id="other1" data-pk="1" data-name="test">First Name</a>
AJAX
$(document).ready(function() {
$('#other1').editable({
type: 'text',
url: '/create_post/',
params : function(params) {
params.csrfmiddlewaretoken = '{{ csrf_token }}';
return params;
},
placement: 'top',
title: 'New Expense',
success: function(response, newValue) {
if(response.status == 'error') return response.msg; //ms
},
});
});

Issues posting comment with ajax through django

I am relatively new to this, but I'm working through things. I want to get solid understanding of how things work.
That being said, I have been attempting to get Django to post comments with an ajax hook.
I thought I was close to accomplishing this but, nothing so far. I was able to write a view that would save a posted comment then redirect me to my main page. I want to be able to use ajax so that the comment would post in a facebook style.
def add_comment(request, pk):
if request.method == 'POST' and request.is_ajax():
comment_form = CommentForm(request.POST)
if comment_form.is_valid():
comment = comment_form.save(commit=True)
comment.save()
json = simplejson.dumps(comment, ensure_ascii=False)
return HttpResponse(json, mimetype='application/json')
return render_to_response(simplejson.dumps('{{ post.id }}', {'comment': comment,}), context_instance=RequestContext(request), mimetype='application/json')
This view is pretty rough right now. I don't have any calls to json but, read this might be the way to go.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script></javascript>
<script type="text/javascript">
$(document).click(function()
{
$('#comment_form').submit(function()
{
var dataString = $('#comment_form').serialize();
$.ajax({
type: 'POST',
url: '{{ post.id }}',
data: dataString,
success: function(data){
$('{{ post.id }}').html(data);
},
});
return false;
});
});
</script>
<form action="" method="POST" id="comment_form">{% csrf_token %}
<div id="cform">
Name: {{ form.author }}
<p>{{ form.body|linebreaks }}</p>
</div>
<div id="submit"><input type="submit" value="Submit"></div>
</form>
Thanks for the response, next time I will definitely leave a more detailed post. My problem was in the jquery script. I was trying to pass dataString as form data to the view, when it was a DOM object not the actual form data. Here's the final working script.
$(document).ready(function() {
$('#comment_form').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '{% url art.views.post %}',
data: $('#comment_form').serialize(),
dataType: 'json',
success: function() {
location.reload();
$('#comment_form').get(0).reset();
},
});
return false;
});
});

Resources