Using ajax to update the currently page with Laravel - ajax

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);
}
}

Related

AJAX form redirecting on submit when using CKeditor

I am trying to submit an AJAX form with Laravel using the code shown below. After I submit the form, all the data is saved in the database as expected apart from the following field which is displayed as NULL in the database.
<textarea name="content" id="editor"></textarea>
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(".btn-submit-add-video").each(function(){
$(this).on("click",function(e){
e.preventDefault();
let form = $(this).closest('form');
$.ajax({
type:'POST',
url: form.attr('action'),
data: form.serialize(),
success:function(data){
alert(data.successful);
}
});
})
});
</script>
public function addVideo(Request $request)
{
$addVideo = new cms_videos;
$addVideo->VideoStatus = $request->VideoStatus;
$addVideo->VideoTitle = $request->VideoTitle;
$addVideo->VideoStrapline = $request->VideoStrapline;
$addVideo->VideoURL = $request->VideoURL;
$addVideo->VideoDescription = $request->content;
$addVideo->VideoTags = $request->VideoTags;
$addVideo->MetaActName = $request->MetaActName;
$addVideo->MetaRegion = $request->MetaRegion;
$addVideo->MetaGenre = $request->MetaGenre;
$addVideo->MetaVenue = $request->MetaVenue;
$addVideo->VideoCoverPhoto = $request->VideoCoverPhoto;
$addVideo->save();
return response()->json(['successful'=>'Video successfully added']);
}
After doing some research I was told to add the following code to the top of the code shown above:
CKEDITOR.instances.SurveyBody.updateElement();
Now all the data is submitted to the database as expected. However when I now submit the form instead of an alert popping up saying "Successful" I am now redirected to the form action URL where it displays "Successful". How can I stop this redirection and display the alert on the page the form was submitted?
I'm not sure but I think the issue is here when you do e.preventDefault() because it works for the button click not for form submission. Try this out and hope it will help you.
Notice: you have to add upload_video class to your forms
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
// If the button is type of submit you can remove this part of code
$(".btn-submit-add-video").each(function(){
$(this).on("click",function(e){
e.preventDefault();
let form = $(this).closest('form.upload_video');
form.submit();
})
});
//
$("form.upload_video").on('submit',function(e){
e.preventDefault();
let form = $(this),data=form.serialize();
//
let content=FCKeditorAPI.GetInstance('content').getData();
data['content']=content;
//
$.ajax({
type:'POST',
url: form.attr('action'),
data: data,
success:function(data){
alert(data.successful);
}
});
});
</script>
This part
let content=FCKeditorAPI.GetInstance('content').getData();
May not be true because I don't work with CKEDITOR right now and i can't test it but you can console.log() it before you send the ajax request and make sure the content exists in the variable as you expected.

Sharepoint Dropdown Choices Filter

I have a dropdown on a form. I have it set as unique entry for the list. That works fine, when a user selects an option that was already selected in a previous list entry they are notified when the save or submit the form. However I would rather remove the choice from the dropdown list if that selection was already made and exists in the list, that way they can't select something already selected.
Thanks for your help
We can use REST API to get all the exists dropdown items and then remove the downdown options in the new/edit form page. The following code for your reference.
<script src="//code.jquery.com/jquery-3.3.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
removeDuplicateDropDowm("FilterDropDown");
});
function removeDuplicateDropDowm(fieldName){
var listId = _spPageContextInfo.pageListId.replace("{","").replace("}","");
var fieldHTML="";
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists(guid'"+listId+"')/items?$select="+fieldName;
$.ajax({
url: url,
method: "GET",
async:false,
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
var items = data.d.results;
$("select[title='"+fieldName+"'] option").each(function(){
for(var i=0;i<items.length;i++){
if(items[i][fieldName]==$(this).val()){
$(this).remove();
}
}
});
},
error: function (error) {
console.log(JSON.stringify(error));
}
});
return fieldHTML;
}
</script>

Using ajax with laravel

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.

How to pass div's html to #Url.Action in Ajax post

A. Where I am so far successfully:
I have 3 divs"
NewAction
NewController
NewArea
I have an $.Ajax post with the url currently as follows
'#Url.Action("CurrentAction", "CurrentController", new { area = "CurrentArea" })'
I have several pages that require this particular Ajax post so I put the Ajax post in a partial, and each main page that uses it, has a parameter in the partial call, eg:
#Html.Partial("_PartialPage", new [] { "NewAction", "NewController", "NewArea" })
The divs in #1 above are successfully populated dynamically with the string values in #3
B. Where my difficulty lies:
Despite many efforts & attempts, I cannot change the #Url.Action values in #2 to the values in the divs in #1.
I even tried to declare C# private variables and populate them with the foreach that populated the divs above and pass those values to the #Url.Action link, but I get a run error.
Does anyone know a way I can pass the parameter values in my partial call (#3) to the Url.Action method in the Ajax post in #2 above.
Thanks in Advance.
You could have a method that will extract the values that are passed to this strongly typed partial and build the url:
#model string[]
#functions {
public string GetUrl() {
if (Model != null && Model.Length > 2)
{
var values = new RouteValueDictionary();
values["controller"] = Model[0];
values["action"] = Model[1];
values["area"] = Model[2];
return Url.RouteUrl(values);
}
return Url.Action("CurrentAction", "CurrentController", new { area = "CurrentArea" });
}
}
<script type="text/javascript">
var url = #Html.Raw(Json.Encode(GetUrl()));
$.ajax({
url: url,
type: 'POST',
success: function(result) {
// ...
}
});
</script>
will render like this:
<script type="text/javascript">
var url = "/NewArea/NewAction/NewController";
$.ajax({
url: url,
type: 'POST',
success: function(result) {
// ...
}
});
</script>
But if you don't need those route values separately another possibility is to directly pass the entire url to the partial view:
#Html.Partial("_About", Url.Action("NewAction", "NewController", new { area = "NewArea" }))
and then inside the partial simply use it:
#model string
<script type="text/javascript">
var url = #Html.Raw(Json.Encode(Model));
$.ajax({
url: url,
type: 'POST',
success: function(result) {
// ...
}
});
</script>

How to associate an event to Html.ActionLink in MVC3

I have made an Ajax function but i am getting a big prolem in that.
I was displaying the contents on click of the link..
The links are fetched from the database and also the url of the links are fetched from the datbase.
I have wriiten ajax to call the contents dynamically on click of the link
<script type="text/javascript">
$(document).ready(function () {
$('a').click(function (e) {
e.preventDefault();
var filename = $(this).text();
var Hobbyurl = '#Url.Action("FetchUrlByHobbyName")';
$.ajax({
type: "POST",
url: Hobbyurl,
data: { data: filename },
success: function (returndata) {
$('iframe').attr('src', returndata);
}
});
});
});
</script>
Now FetchUrlByHobbyName is the function called from the Controller thart returns the url
//Ajax routine to fetch the hobbyinfo by hobbyname
[HttpPost]
public ActionResult FetchUrlByHobbyName(string data)
{
HobbyMasters hobbymaster = new HobbyHomeService().FetchHobbyMasterByHobbyName(data);
string url = hobbymaster.InformationUrl;
if (HttpContext.Request.IsAjaxRequest())
return Json(url);
return View();
}
And in my View i have written the link like this:
#foreach (var item in Model)
{
<li >#Html.ActionLink(item.HobbyName, "Hobbies")
</li>
}
i tried this :
#Html.ActionLink(item.HobbyName, "Hobbies", null, new { id = "alink" })
and then calling Ajax on click of 'alink' but with this my ajax function doesnot get called.
Now the problem is the ajax function is getting called on click of every link on the page..
I want to assign a unique Id to it but i am not understanding how to do that
please Help me...
For that specific link, assign an id. E.g
<a id="someID" href="url">Link</a>
and than bind the click only with that link.
$('#someID').click(function (e)) ....
If I understood you correctly this helps you
The text of the link
<script type="text/javascript">
function myAjaxFunction(){
e.preventDefault();
var filename = $(this).text();
var Hobbyurl = '#Url.Action("FetchUrlByHobbyName")';
$.ajax({
type: "POST",
url: Hobbyurl,
data: { data: filename },
success: function (returndata) {
$('iframe').attr('src', returndata);
}
});
</script>
Try to give a css class selector to you action link like this...
#Html.ActionLink("some link", "Create", "Some_Controller", new { }, new { #class = "test" })
then User jquery for it..
<script type="text/javascript">
$(document).ready(function () {
$('.test').click(function (e) {
e.preventDefault();
var filename = $(this).text();
var Hobbyurl = '#Url.Action("FetchUrlByHobbyName")';
$.ajax({
type: "POST",
url: Hobbyurl,
data: { data: filename },
success: function (returndata) {
$('iframe').attr('src', returndata);
}
});
});
});
</script>

Resources