jquery ajax without refersh data get laravel - ajax

my blade
jQuery('.tbody').trigger('click').click(function(e){
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
jQuery.ajax({
url: "{{ route('artist_genre_page_ajax') }}",
dataType: 'json',
cache: false,
method: 'GET',
success: function(result){
$.each(result.genre,function(key,iteam){
$('tbody').append(
'<tr>\
<td>'+ iteam.id +'</td>\
<td>'+ iteam.genre_name +'</td>\
<td><div class="table-actions d-flex align-items-center gap-3 fs-6"><i class="bi bi-pencil-fill"></i><i class="bi bi-trash-fill"></i></div></td>\
</tr>'
);
});
console.log(result.genre);
}});
});
here i am save data using Ajax and i wont o without refresh page show data on same page how to fix this

Related

how to make successfull ajax success

Button code
this is my button code with id 123
<button type="submit" class="addto" id="123">Add to cart</button>
ajax code
This is my ajax code
$(document).ready(function(){
$('.addto').click(function (event) {
event.preventDefault();
$id=this.id;
//alert($id);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '/test', //route url
dataType:"json",
type:"POST",
data:{id:this.id},
success: function(result){ //success function
alert("success"); //test alert
}});
});
});
Route code
this is my route code
Route::match(['get','post'],'/test','ajaxcontrol#test'); //route url
Controller code:
How to solve this, i have included all the imports
class ajaxcontrol extends Controller
{
public function test(Request $request){
$valu=$request->id;
echo json_encode($valu);
}
}
Try to change your ajax like this:
$(document).ready(function(){
$('.addto').click(function (event) {
event.preventDefault();
id=this.id;
//console.log(id);
$.ajax({
url: "{{ url('/test') }}", //route url
dataType:"json",
type:"POST",
data:{
id:id,
"_token": "{{ csrf_token() }}",
},
success: function(result){ //success function
alert("success"); //test alert
}});
});
});

Laravel Ajax Store Update data issue

i have Form in which i want to update data or store data, right now it is updating data, when i click on update/add button.
<meta name="csrf-token" content="{{ csrf_token() }}">
<form id="update-form" enctype="multipart/form-data" >
#method('PUT')
//text fields
<button type="submit" class="btn btn-secondary btn-lg shadow-lg rounded" name="" value="" id="store-data" > <span class="fa fa-user-add "> </span> ADD</button>
<button type="submit" class="btn btn-secondary btn-lg shadow-lg rounded" name="id" value="{{#$teacher->id}}" id="update-data" > <span class="fa fa-user-edit "> </span> UPDATE</button>
</form>
ajax code for store:
jQuery(document).ready(function($) {
//Ajax store
$('#store-data').on('submit', function(e) {
e.preventDefault(e);
$.ajax({
type: "POST",
url: "teachers/store",
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: new FormData(this),
success: function (data) {
alert("Added");
},
});
});
});
ajax code for update:
jQuery(document).ready(function($) {
$('#update-form').on('submit', function(e) {
e.preventDefault(e);
$.ajax({
type: "POST",
url: "teachers/" + $('#update-data').attr("value"),
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: new FormData(this),
processData: false,
contentType: false,
beforeSend: function() {
},
success: function (data) {
alert("updated");
},
});
});
});
web.php:
Route::get('teachers/store', 'TeachersController#store')->name('add');
Route::resource('teachers', 'TeachersController');
required:
when i click on add button it should add data, and when i click on update it should update.

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".

Form validation in codeigniter when ajax used to form submit

Form submit is not happened in this scenario..
$.ajax({
type: "POST",
async: false,
url: base_url+"register/registration_val",
data: "register_first_name="+first_name,
success: function(data){
$('#inferiz').html(data);
},
error: function(){
alert('error');
}
In your view you can add this:
<script type="text/javascript">
var base_url = "<?php print base_url(); ?>";
</script>
Plus try to alert and see the value of final url in ajax i.e alert(url);
Try adding a id to the firstname input
<script type="text/javascript">
$(document).on('submit','#form-reg',function(){ // #form-reg is id on form open tag
$.ajax({
url: "<?php echo base_url('register/registration_val');?>",
type: 'POST',
data: {
firstname: $('#firstname').val(),
},
dataType: 'html', // I perfer to use json
success: function(data){
$('#inferiz').html(data);
},
error: function(){
alert('error');
}
}
});
});
</script>
I would use dataType: json much easier that way to get data from controller
You used data: "register_first_name="+first_name, it's not correct. Correction is data: {register_first_name:first_name},
base_url like this var base_url = <?php echo base_url(); ?>
So, Bellow final code :
<script type="text/javascript">
jQuery(document).ready(function ($) {
var base_url = <?php echo base_url(); ?>
$.ajax({
url: base_url+"register/registration_val", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: {register_first_name:first_name}, // Data sent to server, a set of key/value pairs representing form fields and values
contentType: false, // The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
}).done(function (data) {
$('#inferiz').html(data);
}).fail(function (data) {
console.log('failed');
});
}(jQuery));
</script>
Please verify your view part that whether you provided id same as in ajax function.
view part:
<form id="form-reg">
<input name="firstname" id="firstname" type="text" required placeholder="Enter firstname " >
<span id="name_validation" class="text-danger"></span>
<button name="submit" id="submit_button" onClick="myFunction();" >submit</button>
</form>
Then correct the base url path which has to be given inside php tag.
function myFunction() {
$.ajax({
url: "<?php echo base_url();?>register/registration_val",
type: "POST",
data:'firstname='+$("#firstname").val(),
success: function(msg)
{
alert('done..!');
}
});
}

403 forbidden error during send JSON data with ajax

these are code snippet for sending json data with ajax.
you can show same code in the last postings.
I'm just follow the code.
But I got 403 error
jsonpost.html
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#mySelect").change(function(){
selected = $("#mySelect option:selected").text()
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
url: '/test/jsontest/',
data: {
'fruit': selected,
'csrfmiddlewaretoken': '{{ csrf_token }}'
},
success: function(result) {
document.write(result)
}
});
});
});
</script>
</head>
<body>
<form>
{% csrf_token %}
{{ data }}
<br>
Select your favorite fruit:
<select id="mySelect">
<option value="apple" selected >Select fruit</option>
<option value="apple">Apple</option>
<option value="orange">Orange</option>
<option value="pineapple">Pineapple</option>
<option value="banana">Banana</option>
</select>
</form>
</body>
</html>
urls.py
urlpatterns = patterns('',
url(r'^jsontest/$', views.JsonRead.as_view(), name='userTest'),
)
views.py
class JsonRead(View):
def get(self,request):
return render(request, 'MW_Etc/jsonpost.html')
def post(self,request):
print(request.body)
data = request.body
return HttpResponse(json.dumps(data))
After change the fruit value, I got the error.
How can I resolve this?
Any others good ways is good as well.
If you are using post method you have to send csrf token in the form,same has to be done in the case of ajax
$(document).ready(function(){
$("#mySelect").change(function(){
selected = $("#mySelect option:selected").text()
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
url: '/test/jsontest/',
data: {
'fruit': selected,
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success: function(result) {
document.write(result)
}
});
});
});
try like this,this worked for me.

Resources