Using ajax with laravel - ajax

I'd like to know if it's possible to use Ajax with Laravel without writing the code inside a .js file.
Script.js
$('#selectSemestres').change(function(obj){
var anoSemestre = $(this).val();
$.ajax({
type: 'GET',
url: '',
data: ...
});
})
I don't know how to get the URL that I want (which is my currently page,
I just want to change the < select> value then reload the data that's already shown on the page).
Do I have to write the ajax inside my .php files? Is this a 'good practice'?
I'm asking this because I already have another script inside that same .php file.
Update
Following the answer posted by #ohgodwhy
Now nothing happens when the ajax executes.
It hits the success code but nothing happens, the URL does not change. Is it because I'm redirecting to the same page am at?
file.php
<script type="text/javascript">
$('#selectSemestres').change(function(obj){
var anoSemestre = $(this).val();
$.ajax({
type: 'GET',
url: '{{ route('professor') }}',
data: { anoSemestre: anoSemestre },
success: function(){
console.log('HELLO WORLD');
}
});
})
</script>
MyController:
public function getProfessorList()
{
$professor = Professor::all();
if( Request::ajax() )
{
echo 'yolo';
}
$semestres = Horario::distinct()->select('ano_semestre')->get()->toArray();
return View::make('professor', compact('professor', 'semestres'));
}

What I usually do is add a #yield('scripts') section to my layout that I extend.
Then in the child templates that require specific JS, I'll add that in there.
#section('scripts')
<script>
//your javascript here.
</script>
#endsection
There is 1 caveat however. If you use an #include from within a child template, and that included file has it's own javascript, it must invoke the parent first, like this:
#section('scripts')
#parent
<script>
</script>
#endsection.

Related

why ajax in an external js file is not working in codeigniter framework

I am created a external js file for plotting a graph in codeigniter. My controller is reached in js file. but the ajax in that file is not supported. here i am attaching the ajax code.`
$(document).ready(function () {
var baseurl = "<?php echo base_url(); ?>";
$.ajax({
url : baseurl + "Welcome/pidiagram",
type : "GET",
success : function (data) {
alert("data");
console.log(data);
}
)};
});
the control is reached inside the document ready function but not inside the ajax.
so please help me.....
most likely your js File won't get parsed by PHP since you outsourced it in an own file
the only thing i'd suggest here is, to add your base URL as an attribute to the html tag e.g.
<html data-base-url="<?php echo base_url(); ?>">
and after that its pretty simple
$(document).ready(function ()
{
var baseurl = $('html').attr('data-base-url');
$.ajax({
url : baseurl + "Welcome/pidiagram",
type : "GET",
success : function (data) {
alert("data");
console.log(data);
}
)};
});

Using ajax to update the currently page with Laravel

I have this ajax inside my file.php (It hits the success callback):
<script type="text/javascript">
$('#selectSemestres').change(function(obj){
var anoSemestre = $(this).val();
$.ajax({
type: 'GET',
url: '{{ route('professor') }}',
data: {anoSemestre: anoSemestre},
success: function(data){
console.log(data);
}
});
})
</script>
Now on my Controller:
public function getProfessorList()
{
$professor = Professor::all();
$ano_semestre = isset($_GET['anoSemestre']) ? $_GET['anoSemestre'] : Horario::first()->distinct()->pluck('ano_semestre');
$semestres = Horario::distinct()->select('ano_semestre')->get()->toArray();
return View::make('professor', compact('professor', 'semestres', 'ano_semestre'));
}
What I want to do:
I have a LIST with professor and their disciplines. What I need to do is:
Whenever I change the value of that select box, I just remake the function with the new parameter.
I'm trying to use ajax to remake that list but nothing change, not even the URL with the professor.php?anoSemestre=xx.
Also, when I try to use the $_GET['anoSemestre'] the page doesnt show any change or any ECHO.
But If I go to Chrome spector>NEtwork and click the ajax I just made, it shows me the page with the data I sent.
Cant find out what I'm doing wrong.
UPDATE
I did what was suggested me, now I'm working with the data I get from the success callback:
<script type="text/javascript">
$('#selectSemestres').change(function(obj){
var anoSemestre = $(this).val();
$.ajax({
type: 'GET',
url: '{{ route('professor') }}',
data: {anoSemestre: anoSemestre},
success: function(data){
var lista = $(data).find('#list-professores'); //Get only the new professor list and thier disciplines
$('#list-professores').remove(); //Remove old list
$('#professores').append(lista); //Append the new list where the old list was before.
}
});
})
</script>
The return of var lista = $(data).find('#list-professores'); is:
Accordion Effect
#list-professores li input[name='item']:checked ~ .prof-disciplinas {
height: auto;
display:block;
min-height:40px;
max-height:400px;
}
This list is an Accordion Menu (using a checkbox and changing it with js&css), so everytime I click on a professor < li>, it's suppose to open and show a sublist (disciplines of that professor I clicked). But it's not opening anymore and no errors on the console. No idea why.
The issue here is what you are returning in your controller and how you do it, you donĀ“t need to redirect or refresh the entire page. This could be achived using a single blade partial for the piece of code you may want/need to update over ajax. Assuming you have an exlusive view for that info, you could solve this with something like this:
in your view:
<div class="tableInfo">
<!--Here goes all data you may want to refresh/rebuild-->
</div>
In your javascript:
<script type="text/javascript">
$('#selectSemestres').change(function(obj){
var anoSemestre = $(this).val();
$.ajax({
type: 'GET',
url: '{{ route('professor') }}',
data: {anoSemestre: anoSemestre},
success: function(){
$('.tableInfo').html(data); //---------> look at here!
}
});
})
</script>
in your controller:
public function getProfessorList()
{
$professor = Professor::all();
$ano_semestre = isset($_GET['anoSemestre']) ? $_GET['anoSemestre'] : Horario::first()->distinct()->pluck('ano_semestre');
$semestres = Horario::distinct()->select('ano_semestre')->get()->toArray();
if (Request::ajax()) {
return response()->json(view('YourExclusiveDataPartialViewHere', ['with' => $SomeDataHereIfNeeded])->render()); //---------> This is the single partial which contains the updated info!
}else{
return View::make('professor', compact('professor', 'semestres', 'ano_semestre'));//---------> This view should include the partial for the initial state! (first load of the page);
}
}

Why is my attempt at a basic Ajax script not working?

I'm currently trying to learn the basics of Ajax through example. By following a basic tutorial, I've managed to create the following script:
<!DOCYTPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js">
$(function(){
$('#mybtn').on('click', function(e){
e.preventDefault();
$('#mybtn').fadeOut(300);
$.ajax({
url: 'ajax-script.php',
type: 'post',
}); // end ajax call
});
</script>
</head>
<body>
<a href='#' id='mybtn'>click me</a>
</body>
</html>
Combined with a simple php file named ajax-script.php which contains the following code:
<?php
if($_POST) {
echo "<p>ok</p>";
}
?>
Can anyone identify what I might have done wrong? How can I make this work?
You don't have a success function - that's where the echo'd PHP data will be received.
Also, you need to close the script tag that loads the jQuery library, and use a different script tag to delineate the javascript code.
Try this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(function(){
$('#mybtn').on('click', function(e){
e.preventDefault();
$('#mybtn').fadeOut(300);
$.ajax({
url: 'ajax-script.php',
type: 'post',
success: function(d){
alert(d);
}
}); // end ajax call
});
</script>
Also, your if ( $_POST ) could cause problems -- either remove that, or post some data:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(function(){
$('#mybtn').on('click', function(e){
e.preventDefault();
$('#mybtn').fadeOut(300);
$.ajax({
url: 'ajax-script.php',
type: 'post',
data: 'test=Hello',
success: function(d){
alert(d);
}
}); // end ajax call
});
</script>
Then, you could get your PHP to echo what you sent, thus:
<?php
if($_POST) {
$recd = $_POST['test'];
echo 'PHP side received: ' . $recd;
}
?>
To prevent the first answer from becoming too monolithic, I will respond to your comment in this new answer.
A few things to try:
(1) Location of your ajax.php file -- is it in the same folder as the page with the javascript code?
(2) Name of the ajax.php file -- note that in your code it is ajax-script.php
(3) I added an alert after the button click -- did that come up?
(4) I removed the IF condition -- the ajax.php file will echo something back to the javascript success function no matter what.
(5) To ensure that jQuery is working, I added jQuery code to colorize the background. If background not slightly orangish, jQuery is not loading.
Did this fix it?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(function(){
$('body').css('background','wheat');
$('#mybtn').on('click', function(e){
alert('Button clicked'); //<==========================
e.preventDefault();
$('#mybtn').fadeOut(300);
$.ajax({
url: 'ajax.php',
type: 'post',
data: 'test=Hello',
success: function(d){
alert(d);
}
}); // end ajax call
});
</script>
Then, you could get your PHP to echo what you sent, thus:
<?php
$recd = $_POST['test'];
echo 'PHP side received: ' . $recd;
?>

how do basic jquery ajax in typo3 flow?

I am trying to do some very basic ajax. I just want an onchange event on a select that will call an ajax function that will get the options for another select and fill it in. However I am not sure how to do this in a simple way in Typo3 Flow. My php code for the action just looks like this:
public function getProductsByCategoryAction( $category='' ) {
$postArguments = $this->request->getArguments();
echo __LINE__;
TYPO3\Flow\var_dump($postArguments); die;
}
and my ajax call looks like this:
jQuery('#get_category').change(function(event) {
event.preventDefault();
alert('get products');
var category = jQuery('#get_category').val();
alert(category);
jQuery.ajax({
url: "/admin/orders/getproductsbycategory.html",
data: {
'category': category
},
async: true,
dataType: 'html',
success: function(data) {
alert('hi mom');
...
}
});
});
when I try this url in the browser mysite-dot-com/admin/orders/getproductsbycategory.html?category=17ca6f3e-a9af-da7d-75cd-20f8d6a05ed0
on the page the var_dump just gives me array(empty). Why doesn't the request->getArguments() call work and give the category argument?
The getproductsbycategory.html is created in Neos and has the right plugin for the action call. So I know the right action gets run but it does not get any args. At this point the argument is just a string and not an _identity even though I should eventually do it that way, I'm trying to keep things simple for now for the sake of expediency.
Thanks
Update: as a temp workaround shameless hack I just did this to get the variable:
$categoryID = $_GET['category'];
which works but I'd like to know the proper way especially if it does not involve writing my own view helpers.
First define variable in your html file
<script>
var ajaxUrl = '<f:uri.action action="actionName" controller="(controllername)Ajax"/>';
</script>
Your Ajax code will look like :->
$.ajax({
data: '&lookup='+{somevalue},
type: 'POST',
url: ajaxUrl,
success: function(data) {
$('.lookup-id').append(data);
},
});
Your conroller action will look like :->
public function getLookupIdAction(){
// Get company detail for set logo of company
$companyDetail = $this->getUserCompany();
// Template Name
$templateName = 'GetLookupID.html';
$viewVariables = $this->lookupIdentifierRepository->findByCompany($companyDetail);
$templatepath = 'resource://WIND.Alertregistration/Private/Templates/LookupIdentifier/' . $templateName;
$this->standaloneView->setLayoutRootPath('resource://WIND.Alertregistration/Private/Layouts');
$this->standaloneView->setPartialRootPath('resource://WIND.Alertregistration/Private/Partials');
$this->standaloneView->setFormat('html');
$this->standaloneView->setTemplatePathAndFilename($templatepath);
$this->standaloneView->assignMultiple(array("lookUpValue" => $viewVariables));
$this->standaloneView->setControllerContext($this->getControllerContext());
return $this->standaloneView->render();
}
Your view file look like :->
<f:layout name="Lookup" />
<f:section name="Content">
<label for="lookupId" style="box-sizing: border-box;">Identifier</label>
<div class="select-box" style="box-sizing: border-box;">
// Your Code
</div>
</f:section>

How to call #Html.Action through Ajax in MVC (.NET)

I have a View which renders an action. For example:
<h1>Test View</h1>
#Html.Action("Intro", "Account", new { id = "5" })
However, this Action takes 10-20 seconds to load.
How can i wrap it in an ajax with a loader?
Thanks!
Just create a DIV to serve as a placeholder, then load the content on document load event into the DIV. You can also add a GIF image to show progress and hide it when the content is loaded, Here's an example of how to do it:
<h1>Test View</h1>
<div id="accountInfo"></div>
<script>
$(document).ready(function () {
$.ajax({
type: "GET",
url: '#Html.Url("Intro", "Account")',
dataType: "html",
data: { id : 5 },
success: function (content) {
$("#accountInfo").html(content);
},
error: function (e) { }
});
});
</script>
Please note I didn't test that and just wrote it from the top of my head so there might be some minor syntax errors but this gives you the main idea.
Hope it helps!

Resources