I am trying to get data from controller and send it in ajax.
The script is in app.blade.php.
Controller
public function show()
{
$number=Order::where('user_id',Auth::user()->id)->count();
return $number;
}
Route
Route::get('product_number', 'OrderController#show')->name('product_number');
JS
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "GET",
url: "product_number",
success: function (data) {
console.log(data);
},
error: function () {
console.log('Error');
}
});
});
</script>
In console it shows me the html view.
try this so you can get the error
public function show()
{
try {
$number=Order::where('user_id',Auth::user()->id)->count();
} catch (\Exception $e) {
echo $e->getMessage(); die;
}
return $number;
}
$(document).ready(function(){
$.ajax({
type: "GET",
url: "{{url('product_number')}}",
success: function (data) {
console.log(data);
},
error: function () {
console.log('Error');
}
});
});
Related
I am using chrome popup extension but no data is sent to the php file named api.php.I have searched on stackoverflow and found ajax related content but nothing is working.here is my popover.js file which uses ajax.I used $_POST['data'] to grab the data in api.php file
var api_url = "https://localhost/psol/api.php";
window.onload = function () {
$("#checkout_btn").click(function () {
chrome.runtime.sendMessage({
'btnClicked': true
}, function () {});
});
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
console.log(request);
if (request.message === "show-loading") {
$(".psol-button").addClass('hide');
$(".psol-loader").removeClass("hide");
}
if (request.message === "hide-loading") {
$(".psol-button").removeClass('hide');
$(".psol-loader").addClass("hide");
}
if (request.message === "post-cart") {
console.log(request.data);
alert(JSON.stringify(request.data));
chrome.runtime.sendMessage({
'postCartDone': true,
'redirectTo': api_url
}, function () {});
$.ajax({
url: api_url,
type: "POST",
data: request.data,
// data:{name:'uzair'},
success: function (result) {
// alert("all done");
console.log(1, result);
}
}).done(function (result) {
console.log(2, result);
if (result.cartCount === 0) {
alert('There are no items in cart to checkout');
}else {
alert("this is also redirect");
}
});
}
});
};
How do i get my code so that if the 401 error appears with my AJAX button click code, then it either throws an error message when the button is clicked and says "you need to log in" or it redirects the user to login? at the moment it just throws the error in the dev console so a user has no idea on why the button isnt working.
Ajax js:
$('.visit').on('click', function (event) {
event.preventDefault();
// Make the button a variable here
var buttonToChange = $(this);
$.ajax({
method: 'POST',
url: urlVisit,
data: {
place_id: $(event.target).data("id"),
_token: token
},
success: function(){
// Change the button here
if(buttonToChange.hasClass('btn-visited')){
buttonToChange.addClass('btn-not-visited');
buttonToChange.removeClass('btn-visited');
buttonToChange.html('Not Visited');
//Count will go down
}
else{
// Do the opposite
buttonToChange.addClass('btn-visited');
buttonToChange.removeClass('btn-not-visited');
buttonToChange.html('Visited');
//count will go up
}
},
});
You could try the statusCode part of jQuery AJAX.
$('.visit').on('click', function (event) {
event.preventDefault();
// Make the button a variable here
var buttonToChange = $(this);
$.ajax({
method: 'POST',
url: urlVisit,
data: {
place_id: $(event.target).data("id"),
_token: token
},
statusCode: {
401: function() {
alert( "Not authenticated" );
}
}
success: function(){
// Change the button here
if(buttonToChange.hasClass('btn-visited')){
buttonToChange.addClass('btn-not-visited');
buttonToChange.removeClass('btn-visited');
buttonToChange.html('Not Visited');
//Count will go down
}
else{
// Do the opposite
buttonToChange.addClass('btn-visited');
buttonToChange.removeClass('btn-not-visited');
buttonToChange.html('Visited');
//count will go up
}
},
});
simple example
you can test this code by inspect in browser:
welcome.blade.php :
<script>
var urlVisit="{{route('route_test')}}"
var token = "{{csrf_token()}}"
$.ajax({
method: 'POST',
url: urlVisit,
data: {
place_id: 1,
_token: token
},
success: function (response) {
alert('ok')
},
error: function (xhr, ajaxOptions, thrownError) {
if (xhr.status == 419)
{
alert(xhr.responseText) // text of error
// do something
}
else if(xhr.status == 401)
{
// do something
}
}
});
</script>
web.php (route) :
use Illuminate\Http\Request;
Route::get('/', function () {
return view('welcome');
});
Route::post('test', function (Request $request) {
$place_id= $request->get('place_id');
return ('yes');
})->name('route_test');
I'm using ajax to implement infinite scroll pagination in laravel but I cannot access the url while I can with the enter the url in the adress bar or via the default pagination page list.
I get GET http://localhost:8888/gest/items?page=2 500 (Internal Server Error)
Scripts
<script type="text/javascript">
var page = 1;
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() >= $(document).height()) {
page++;
loadMoreData(page);
}
});
function loadMoreData(page){
$.ajax(
{
url: '?page=' + page,
type: "get",
beforeSend: function()
{
$('.ajax-load').show();
}
})
.done(function(data)
{
if(data.html == " "){
$('.ajax-load').html("No more records found");
return;
}
$('.ajax-load').hide();
$(".row-items").append(data.html);
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('server not responding...');
});
}
</script>
And the controller
public function index(Request $request, $submenu = null){
$items = Item::paginate(5);
if ($request->ajax()) {
$view = view('data',compact('items'))->render();
return response()->json(['html'=>$view]);
}
return view('layouts.gest', compact('items'), ['submenu' => $submenu]);
}
EDIT
I also tested to add
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
The error was that laravel couldn't find the view data
I'm beginner in asp.net mvc ,and want to fetch simple json from controller to ajax variable,for that purpose in view page write this ajax function:
<script>
var OutPut;
OutPut = "behzad";
function CallService() {
$.ajax({
url: '#Url.Action("callService", "myPassword")',
type: 'GET',
dataType: 'json',
cache: false,
data: { 'id': 2 },
success: function (color) {
OutPut= color;
},
error: function () {
alert('Error occured');
}
});
alert("I think is ok!"+":"+OutPut);
}
</script>
and this controller:
[HttpGet]
public JsonResult callService(int id)
{
string JSON = "behzad";
return Json(JSON,JsonRequestBehavior.AllowGet);
}
that ajax function call with this html code in view page:
<button type="button" class="btn btn-success" onclick="CallService()">Success</button>
but this line in ajax function:
alert("I think is ok!"+":"+OutPut);
Output is undefined,what happen?is controller return null?or why i get undefined alert?thanks.
Since the AJAX call is asynchronous, you should place the alert inside the success callback:
<script>
function CallService() {
$.ajax({
url: '#Url.Action("callService", "myPassword")',
type: 'GET',
cache: false,
data: { 'id': 2 },
success: function (color) {
alert("I think is ok!" + ":" + color);
},
error: function () {
alert('Error occurred');
}
});
}
</script>
public function index($id)
{
$project = Project::findOrFail($id);
if(Request::ajax())
{
$html = View::make('Milestones.indexpartial', $project)->render();
return Response::json(array('html' => $html));
}
return View::make('milestones.index')->with('project', $project)
->with('title','Milestones');
}
$(".ajaxul a").click(function()
{
var url = $(this).attr('href');
$.ajax(
{
url: url,
type: "get",
datatype: "html",
beforeSend: function()
{
$('#ajaxloading').show();
}
})
.done(function(data)
{
$('#ajaxloading').hide();
$(".refresh").empty().html(data.html);
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('No response from server');
});
return false;
});
Please help me make this work.
I'm new to AJAX and laravel.
my problem was this line here:
$html = View::make('Milestones.indexpartial', $project)->render();
it gives an error. then i changed it to
$html = View::make('Milestones.indexpartial',array('project' => $project))->render();
the request is a success but the html is empty.
Please help me. Thank you.