loading url to bootstrap modal using ajax in Laravel not working - php

In Laravel -Controller name is ProductController, method is showproductinmodal .
I tried this, javascript code it worked.
Web Route:
Route::get('admin/product/show/{id}', 'Admin\ProductController#showproductinmodal');
JS:
<script>
$('.showinfo').click(function(){
var productid = $(this).data('id');
// AJAX request
$(".modal-body").load("{{URL::to('admin/product/show/')}}"+"/"+productid);
});
</script>
Url loaded and returned some text to modal.
But this Javascript code not worked, i want to use code below:
$(document).ready(function(){
$('.showinfo').click(function(){
var productid = $(this).data('id');
// AJAX request
$.ajax({
url: '{{route('admin.showproductinmodal')}}',
type: 'post',
data: {id: productid},
success: function(response){
// Add response in Modal body
$('.modal-body').html(response);
}
});
});
});
My web route code
Route::post('admin/product/show/', 'Admin\ProductController#showproductinmodal')->name('admin.showproductinmodal');
My Controller code:
public function showproductinmodal(Request $id)
{
return "Your test id:" . $id;
}
My a tag
Any ID test
Modal works normal, pops up when I use first javascript code everything works ok data loading, but second javascript code is necessary for me. I inserted alert also in $.ajax request but it didn't work.

Might be you are missing crsf token in you case:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Set csrf token for ajax call once then call N number of ajax:
$(document).ready(function () {
$('.showinfo').click(function () {
var productid = $(this).data('id');
let url = "{!! route('admin.showproductinmodal') !!}"
// AJAX request
$.ajax({
url: url,
type: 'post',
data: {
id: productid
},
success: function (response) {
// Add response in Modal body
$('.modal-body').html(response);
}
});
});
});
And it will me more better, if you will use bootstrap model event, and use base url with javascript global variable.

Related

"Like" system using Laravel, Ajax and jQuery

I don't have the knowledge about Ajax in combination with Laravel. I'm trying to build a like system, its already set up. The problem is; when you click on the like button, the whole page refreshes. But I want it to be dynamic. To do this, I need to use Ajax and jQuery
I have tried building a jQuery function, but I don't know how to parse the {id}
Could you show me where I can learn more about this subject? Maybe a tutorial or could you please explain to me the part I'm missing.
$('.like').on('click', function(event) {
console.log("clicked the button");
$.ajax({
method: 'POST',
url: /{id}/addlike
})
});
This is the like button:
<form action="/{{$new->id}}/addlike" method="post">
#csrf
<button value="{{$new->likes}}" class='like' type="submit"><i class="fas fa-fire"></i></button>
</form>
This is the like route:
Route::post('/{id}/addlike', 'ImageController#like');```
This is the "like" controller
public function like($id)
{
$picture = ImageModel::find($id)->increment('likes');
return back();
}
Remove type='submit' It will redirect your page, just add type="button" and in .like function() ajax should be like this, always apply if and else condition in case you getting some error so it will reflect on your browser console.
$.ajax({
type: "POST",
url: Apiurl,
data: {
"_token": "{{ csrf_token() }}",
"id": id
}
success: function (data)
{
if(data.status == 'success' )
{
//apply your condition
}
else
{
console.log('error');
}
}
});
You can pass data in your ajax functions like data: {id: yourid, name: somename}, and also you can assign laravel variable values to js like this:
var testId = '{{$yourid}}'
So in your case you can make url like testId + '/addlike', also always make id or other dynamic thing go at the end like 'addlike/' + testId.
$('.like').on('click', function(event) {
console.log("clicked the button");
var id = '{{$yourId}}'
$.ajax({
method: 'POST',
url: id + '/addlike'
})
});
Hope it helps
Don't add
return back();
in your controller instead you can use
return response()->json(['success' => 'Liked']);
or anything you want to input there to pass the data in ajax. Don't put action in your post instead you can use hidden input to put your id there and call it (if you're using jquery)
$('input [name=nameofhidden]').val();
then in your ajax add success and what you want to do after updating the data.
var id = $('input[name=nameofhidden]').val();
$.ajax({
method: 'POST',
url: '/'+id+'/addlike',
success: function(ifyouhavedata){
//what you want to do
}
})
JavaScript logic you need to return false, so it'll stop redirecting. see below code.
$('.like').on('click', function(event) {
console.log("clicked the button");
var id = '{{$yourId}}'
$.ajax({
method: 'POST',
url: id + '/addlike'
});
return false;
});
Controller should be return like below
return response()->json(['success' => 'Liked'],200);

Ajax Delete Function in Laravel doesn't work

I tried to make an ajax delete functionality in Laravel.
I cant figure out why it isnt working... There is no error but nothing happens -
Thanks for any help!
My route:
Route::post('/deleteWithAjax', 'eventController#deleteWithAjax');
My delete Button:
<button value="{{$event->id}}" class="btn btn-danger btn-dell">Delete</button>
My javascript:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function(){
$('document').on('click', '.btn-dell', function() {
var id = $(this).val();
var el = $('#{{$event->id}}');
$.ajax({
type: 'post',
url: "deleteWithAjax",
data: {
'id': id
},
success:function(data){
el.remove();
}
})
})
});
My Controller Method:
public function deleteWithAjax(Request $r){
eventModel::find ( $r->id )->delete();
return response()->json();
}
The element i want to remove is a div:
<div id="{{$event->id}}">
EDIT**
I changed the event Handler
document.getElementById("btn-dell").onclick = function()
now it gets fired - but i get an error in the console and the backend is still not called at all:
POST http://wt-projekt.test/index.php/deleteWithAjax 419 (unknown status)
send # app.js:29
ajax # app.js:29
document.getElementById.onclick # home:50
I solved the problems:
I placed the token part in the document ready function
--> No error anymore, record deleted in the DB but still in the view
I added dataType: 'text' to the ajax call
--> error also deleted in the View
Nevertheless thanks for your comments!

Post variable before redirect?

I am currently building on a CMS. I want to send a page-id or site-id to the next page on redirect. I tried doing it using the jQuery POST function:
$(document).ready(function(){
$('.sender').on('click','a',function(){
var url = $(this).attr('href');
var n = url.indexOf('#')+1;
var siteid = url.substr(n,url.length);
$.ajax({
url: 'pages.php',
type: 'POST',
data: { siteid:siteid },
success: function(response){
console.log('check');
},
error: function(){
console.log('error');
}
});
});
});
But because the request is sent at the same time as the redirect, it does not seems to work.
Because I am using the apache rewrite_engine to redirect stuff, I cannot use GET.
Apart from session_variables, what are my options?
I want to keep it safe, so I don't want much info to be visible/available!
To achieve this you need to wait for the AJAX request to complete before the page is redirected. Try this:
$(document).ready(function(){
$('.sender').on('click', 'a', function(e){
e.preventDefault(); // stop the default redirect
var url = $(this).attr('href');
var n = url.indexOf('#') + 1;
var siteid = url.substr(n, url.length);
$.ajax({
url: 'pages.php',
type: 'POST',
data: {
siteid: siteid
},
success: function(response){
console.log('check');
window.location.assign(url); // redirect once the AJAX has successfully completed
},
error: function(){
console.log('error');
}
});
});
});
I'm not sure to clearly understand why you need but I think this can answer your problem.
If what you need is to transfert informations using a real POST method, just create an hidden form with method="POST" and fill it on click event.
<script type="text/javascript">
$(document).ready(function(){
$('.sender').on('click','a',function(event){
event.preventDefault();
var url = $(this).attr('href');
var n = url.indexOf('#')+1;
var siteid = url.substr(n,url.length);
$('input[name="siteid"]').val(siteid);
$('#redirectForm').submit();
});
});
</script>
<form id="redirectForm" action="pages.php" method="POST">
<input type="hidden" name="siteid" value=""/>
</form>

jQuery ajax request awkward issue

So I have this ajax request. When the user clicks an edit link, I fetch the ID of the entry and refresh the page with the data of that entry loaded into a form.
Here's my problem: This only works with the alert showing before the ajax call. When I leave out the alert, I get an ajax error (though the id is being posted) and the PHP page just reloads. Moreover, it only works when I put the newDoc stuff as a success callback. The exact same lines as a complete callback and the page reloads. Moreover, this occurs in Firefox only.
jQuery('a.edit').on('mousedown', function (e) {
e.preventDefault();
var id = jQuery(this).attr('data-title');
alert('test');
jQuery.ajax({
url: document.location,
data: {
id: id
},
success: function (data) {
var newDoc = document.open("text/html", "replace");
newDoc.write(data);
newDoc.close();
},
error: function () {
alert('error');
}
});
});
What can I do?
EDIT: This must be a timing issue. I just noticed that when I click and hold the edit link for a second or so, everything works fine. When I do a short click, it doesn't. So I tried wrapping the ajax in setTimeout(), but that didn't help. Any other ideas?
Try to use location.href in place of document.location,
jQuery.ajax({
url: location.href,
data: {
id: id
},
success: function (data) {
var newDoc = document.open("text/html", "replace");
newDoc.write(data);
newDoc.close();
},
error: function () {
alert('error');
}
});
location is a structured object, with properties corresponding to the parts of the URL. location.href is the whole URL in a single string.
Got it!
The problem is the way Firefox handles the mousedown event. It seems to abort the ajax call as soon as you relase the mouse button. I changed the event to click and everything is fine now.
jQuery('a.edit').on('click', function () {
var id = jQuery(this).attr('data-title');
jQuery.ajax({
url: document.location,
data: {
id: id
},
success: function (data) {
var newDoc = document.open("text/html", "replace");
newDoc.write(data);
newDoc.close();
}
});
});

Execute php script with JS [duplicate]

Is it possibe to simply load a php script with a url with js?
$(function() {
$('form').submit(function(e) {
e.preventDefault();
var title = $('#title:input').val();
var urlsStr = $("#links").val();
var urls = urlsStr.match(/\bhttps?:\/\/[^\s]+/gi);
var formData = {
"title": title,
"urls": urls
}
var jsonForm = JSON.stringify(formData);
$.ajax({
type: 'GET',
cache: false,
data: { jsonForm : jsonForm },
url: 'publishlinks/publish'
})
//load php script
});
});
Edit:
function index() {
$this->load->model('NewsFeed_model');
$data['queryMovies'] = $this->NewsFeed_model->getPublications();
$this->load->view('news_feed_view', $data);
}
simple
jQuery and:
<script>
$.get('myPHP.php', function(data) {});
</script>
Later edit:
for form use serialize:
<script>
$.post("myPHP.php", $("#myFormID").serialize());
</script>
like this ?
$.get('myPHP.php', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
There are various ways to execute a server side page using jQuery. Every method has its own configuration and at the minimum you have to specify the url which you want to request.
$.ajax
$.ajax({
type: "Get",//Since you just have to request the page
url:"test.php",
data: {},//In case you want to provide the data along with the request
success: function(data){},//If you want to do something after the request is successfull
failure: function(){}, //If you want to do something if the request fails
});
$.get
$.get("test.php");//Simplest one if you just dont care whether the call went through or not
$.post
var data = {};
$.post("test.php", data, function(data){});
You can get the form data as a json object as below
var data = $("formSelector").searialize();//This you can pass along with your request

Categories