I want to use Sweetalert2 to confirm wether you want to delete a record or not. If you press "DELETE" and there's an error, show another sweetalert popup. If there's no error, redirect to homepage.
All I did was prevent the default submission of the form and make an ajax request when "delete" is pressed (so result.isConfirmed is true). I've been trying to pass the CSRF token in data and headers too but I get this error all the time:
Uncaught (in promise) ReferenceError: bkF3gnRCrqiVjvKKLnP2kih90lYssXIINjIpLK8v is not defined
I'm not sure if that's doable and if so, how, but I would like to ask for some help. This is what I have so far:
*..prevent default and first sweetalert popup..*
.then((result) => {
if (result.isConfirmed) {
$.ajax({
type:'GET',
url:'{{ route("site.destroy", $record->id) }}',
headers: ('X-CSRF-Token', {{ csrf_token() }}),
error: ()=>{
Swal.fire(
'Something went wrong!',
'record was not deleted.',
'error')
}
*..end..*
Here is the solution,
you have syntax error (try to use header as key-value pair).
Try this way.
JavaScript code
$.ajax({
type: 'GET',
url: '{{ route("site.destroy", $record->id) }}',
headers: {
'X-CSRF-Token': '{{ csrf_token() }}'
},
error: () => {
Swal.fire(
'Something went wrong!',
'record was not deleted.',
'error'
);
}
});
Hope you will fix the issue :)
Related
Im using JaxaScript(Jquery with Ajax) and my HTML Page all in the same file, but when I tried to code my JS and HTML in different files, I get an error when trying to ajax with Django.
JS:
$(document).on('click', '#add-button', function (e) {
e.preventDefault();
value = $(this).data("forloopcounter");
value = value - 1
let variation_id = document.getElementsByClassName("select-variations")[value].attributes[2].nodeValue
console.log(variation_id)
$.ajax({
type: "POST",
url: '{% url "cart:add" %}',
data: {
variationid: variation_id,
productquantity: 1,
csrfmiddlewaretoken: "{{csrf_token}}",
action: 'post'
},
success: function (json) {
document.getElementById("cart-quantity").innerHTML = json.quantity
},
error: function (xhr, errmsg, err) {
console.log(xhr)
}
});
})
Note: I have a guess it's because of this url: '{% url "cart:add" %}', but I don't know how to fix.
Note: when I ajax with all in the same page it works.
Note it's not an importation error, when i execute console.log it
works
Error I get in the web:
`jquery.min.js:4 POST http://127.0.0.1:8000/%7B%%20url%20%22cart:add%22%20%%7D 404 (Not Found)
HTML:
{% for variation in product.variation_set.all%}
{%if forloop.first%}
<!--pra fazer ajax passando id da variação selecionado(não aparece pra usuário)-->
<small id="select-variations1" class="small select-variations"
value="{{variation.id}}"></small>
{%endif%}
{%endfor%}`
A part of the django view which is executed is as follows:
def traxio_advice(request):
.......
.......
elif calculation['statusCode'] == 400:
response = JsonResponse({'message': 'The calculation is not available! Please try another mileage.'}, status=500)
return response
And in django template I have ajax call as follows :
$.ajax({
type: 'POST',
url: '{% url 'traxio_advice' %}',
data: {
firstname: $('input[name=firstname]').val(),
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success: function (data) {
......
},
error: function (data) {
var message = $.parseJSON(data.responseText).message;
$('#calculation-error').removeClass('hidden').html(message)
},
beforeSend: function () {
$('#result-content').html('<div class="loader"></div>');
}
})
The problem is in the error function. I get what I want, thus, the data is correct.
message = "The calculation is not available! Please try another mileage."
But the message isn't showing in the div with the id calculation-error.
Instead I see the loader from the beforeSend function on the screen and in the console I get
POST http://127.0.0.1:8000/master/traxio_advice/ 400 (Bad Request)
What am I missing?
Just for the info, If anyone else would have a similar problem.
Actually the problem was in the beforeSend function and the template .
The div with id #calculation-error (where I wanted to show the error) was inside the div with id #result-content.
But in the beforeSend function I replaced the content of the div with the id #result-content.
Thus in the template like this :
<div id="result-content">
<div class="loader"></div>
</div>
I tried to show error in the div with the id #calculation-error. It couldn't be shown because that div doesn't exist.
I have a problem. My jquery submit function, tries to do a GET request, while I set it up as a POST request.
my submit function
function authenticate() {
var form = $('#form-login');
form.submit(function(evt) {
evt.preventDefault();
console.log('submitting!');
console.log(form.serialize());
$.ajax({
type: 'POST',
url: 'http://website.dev/loginz',
data: form.serialize(),
dataType: 'json',
success: function(data) { log_error(data.error); }
});
});
}
routes.php
Route::post('loginz', 'User\LoginController#authenticate');
What my chrome browser says
GET http://website.dev/loginz/ 405 (Method Not Allowed)
/Loginz
/* POST */
function authenticate(Request $request) {
$username = $request->input('username');
$password = $request->input('password');
if(Auth::attempt(['username' => $username, 'password' => $password])) {
redirect()->route('home'); /* should redirect to player */
}
return response()->json(['error' => trans('errors.user_password_combination').' => '.$username.' & '.$password]);
}
Maybe I am just stupid and hit a wall, I have stared myself to death and I just can't see the error :P
What version of laravel are you using?
Remind csrf token must be given for post requests.
you can disable the csrf verification also in \App\Http\Middleware\VerifyCsrfToken::class,
But would be better if you set in on the client side.
Meaning from laravel you should in the blade template add something like:
$( document ).ready(function() {
$.ajaxSetup({ headers: { 'X-CSRF-TOKEN': '{{ csrf_token() }}' } });
});
But first, in Chrome (example) inspector -> network -> header: what is the request method?
The fault was an 301 redirect. The problem was created by myself. I added a redirect from non slash to slash (ex. /page to /page/) so the POST was redirected to a GET request.
.Hello y'all. I'm trying to learn ajax and am currently trying to have an input in a form be sent via a route to a controller and then echoed in a div.
For some reason I am getting a NotFoundHttpException error when I press the submit button for the form and am having trouble seeing what is wrong with my route.
If anyone can point out where I'm going wrong it would be greatly appreciated! Thank you!
View:
<form id="edit_price_form" method="POST" action="">
<input name="new_price" id="new_price"/>
<input type='submit' class='button tiny radius' id='edit_price_button'/>
</form>
Ajax request:
$(document).ready(function(){
$("#edit_price_form").submit(function(e) {
e.preventDefault();
//form_data
var form_data = $('#edit_price_form').serializeArray();
$.ajax({
url: 'edit_prices',
type: "POST",
dataType: "html",
data: form_data,
success: function(data){
$("#edit_results").html(data);
$("#edit_results").addClass('panel callout radius');
},
error: function(xhr, status, error){
console.log(xhr);
console.log(status);
console.log(error);
}
});
});
});
Route:
/*Ajax Edit Price on Price Page*/
Route::post('edit_prices', array(
'as' => 'edit_prices',
'uses' => 'PriceController#edit_prices'
));
Controller:
public function edit_prices(){
$new_price = Input::get('new_price');
echo $new_price;
}
Thanks again!
The problem lies in your HTTP method. You're AJAX request looks like this:
$.ajax({
url: 'edit_prices',
type: "PUT",
...
But your route looks like this:
Route::post('edit_prices', array(
'as' => 'edit_prices',
'uses' => 'PriceController#edit_prices'
));
In short, you'll need to change your AJAX request from PUT to POST - Laravel is rejecting the PUT request because it's expecting POST.
I use this code for a basic anthentification of REST API. Unfortunately, when the user/pass is wrong Google Chrome displays a popup. Firefox does not do that.
$.ajax({
type: "GET",
url: "/ad",
dataType: 'json',
async: false,
username: 'username',
password: 'password',
success: function (){
alert('success');
return false;
},
error: function(){
alert('error');
return false;
}
});
Edit 1 :
I use Laravel Framework
If you don't have server control, there is no (at least not known to me) way to prevent that. If you DO have server control you can do two things:
Change the response status code from standard 401 to something else. However, this is commonly not known as best practice since the status code does then not state the actual issue (authentication error).
Change the response header WWW-Authenticate: Basic realm="your_realm" to a custom value like WWW-Authenticate: x-Basic realm="your_realm" (Note the x-there!).
That should prevent any default login handling.
Update 1
As for using Laravel this would be an example of setting the correct response header WWW-Authenticate (changed Basic to x-Basic):
Route::filter('auth', function()
{
$credentials = ['email' => Request::getUser(), 'password' => Request::getPassword()];
if (!Auth::once($credentials)) {
$response = ['error' => true, 'message' => 'Unauthorized request'];
$code = 401;
$headers = ['WWW-Authenticate' => 'x-Basic'];
return Response::json($response, $code, $headers);
}
});
I think you can pass the username and password in the URL instead for HTTP authentication.
Give this a shot:
$.ajax({
type: "GET",
url: "http://username:password#whatever.com/ad",
dataType: 'json',
async: false,
success: function (){
alert('success');
return false;
},
error: function(){
alert('error');
return false;
}
});