Ajax Example with Laravel and Jquery
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(".btn-submit").click(function(e){
e.preventDefault();
var name = $("input[name=name]").val();
var password = $("input[name=password]").val();
var email = $("input[name=email]").val();
$.ajax({
type:'POST',
url:'/ajaxRequest',
data:{name:name, password:password, email:email},
success:function(data){
alert(data.success);
}
});
});
0
0
$(document).ready(function () {
const post_id = $("#post-detail").attr("data-post-id");
getCommentsOfPosts(post_id)
$("#comment-submit-form").submit(function(e){
e.preventDefault();
const formData = $(this);
const submitButton = $("#comment-submit-button");
const post_id = $("#post-id-comment").val();
submitButton.html('Saving....<i class="fa fa-spin fa-spinner" aria-hidden="true"></i>');
$.ajax({
method: "POST",
url: "/api/comments/" + post_id,
data: formData.serialize(),
success: (result) => {
submitButton.html('Save');
$("#comment-errors-data").html('');
$("#comment-input").val('');
$("#successMessage").removeClass('visually-hidden');
getCommentsOfPosts(post_id);
},
error: (error) => {
if(error.status === 422) { // "Unprocessable Entity" - Form data invalid
$("#successMessage").addClass('visually-hidden');
var message = error.responseJSON.errors ? error.responseJSON.errors.comment ? error.responseJSON.errors.comment[0] : '' : '';
$("#comment-errors-data").html(message);
submitButton.html('Save');
}
}
});
});
});
/**
* Get comments of a post
*/
function getCommentsOfPosts(post_id) {
if( typeof post_id !== 'undefined' && post_id !== '' && !isNaN(post_id)) {
$.ajax({
method: "GET",
url: "/api/comments/" + post_id,
success: (result) => {
$("#post-comments").html(result);
},
error: (error) => {
alert('Something went wrong to fetch datas...');
}
});
}
}
Thank you!
0
0
Are there any code examples left?
New code examples in category Javascript
-
Javascript 2023-04-21 22:52:36
-
Javascript 2022-03-27 22:25:20 javascript download string as file
-
Javascript 2022-03-27 21:40:22 sort numbers in array javascript
-
Javascript 2022-03-27 21:20:04 compare two arrays and return the difference javascript
-
Javascript 2022-03-27 21:15:02 javascript regex french phone number
-
Javascript 2022-03-27 21:05:03 cypress custom error message
-
Javascript 2022-03-27 21:00:05 create element javascript with id
-
Javascript 2022-03-27 20:40:57 feather icons react
-
Javascript 2022-03-27 20:20:01 how to make graphql request in axios
-
Javascript 2022-03-27 20:15:07 bootstrap validator password and confirm password