Recently, I tried to build my own Laravel system, but I met a huge problem.
I'm using FullCalendar on the page 1 and I want to pass the "date data" to page 2.
However, I can get the "date data" on page 1 which is using jQuery (the variable name is 'selectedDate').
I even tried to use AJAX to pass data to controller
The following is my AJAX code on page1.blade.php
$.ajax({
url: 'step1getdate',
type: "get",
data: {date: selectedDate},
success: function(data){
console.log(data);
},
error: function (xhr, b, c) {
console.log("xhr=" + xhr + " b=" + b + " c=" + c);
}
});
web.php code is as following
Route::get('campustour/step1getdate', 'CampusTourStep1Controller#showDate');
CampusTourStep2Controller code is as following
public function showDate(Request $request){
$date = $request->input( 'date' );
return view('campusTour.step2', compact('date'));
}
but I still stuck on the same page and get the Step2 full html code on the console log window. When I checked the $date parameter on the console.log, it's passing data correctly. But what I want to do is return the whole page (step2) not just in the console.log.
Can anyone give me some guidance or keywords and let me keep moving?
Thanks a lot.
Related
I´ve searching but with no luck, i´ve tried implementing many things but nothing lead to success, so this is my scenario:
At certain point the user is in a view where after filling some fields, he has the ability to save or save and create.
The first one it is working ok, i´m posting with ajax to my controller method and returning a json response, but the user stays normally in the same view.
The second one(when he saves and create) i´m sending a variable to say exactly that, and because of that choice, the user must be directed to another view to "create" BUT i need the data that was previously saved to automatically fill some fields on the new form that is suppose to be created...so my code is:
my ajax:
$.ajax({
method: 'POST',
url: '/Cliente/insertEditCliente',
dataType: "json",
data: {"_token": "{{ csrf_token()}}", "mainId":$('#mainId').val(),values,"btnId":this.text},
success: function(response){
if(response.titulo != "Erro!"){
let dados = response['dados'];
window.location = '{{ route("formAngariacao",[null]) }}'+'/?dados='+dados;
}
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
// console.log(JSON.stringify(jqXHR));
// console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
in my controller method, i have that if statment to detect if it was just save or save and create:
if($request->post('btnId') == "Guardar"){
return response()->json(["titulo"=>"Ok!","mensagem"=>"Cliente Alterado com sucesso!","tipo"=>"success"]);
}
else{
return response()->json(["titulo"=>"Ok!","mensagem"=>"Cliente Alterado com sucesso!","tipo"=>"success","dados"=>$request]);
}
But now, in my blade view, i need to read that array "dados" which corresponds to the $request variable and has all the data i need.
How do i do that? and is this the best practice?
thanks for your time reagards.
I'm using the following code to call a partial view:
$('#btnGetMilestones').click(function () {
$.ajax({
url: "GetMilestones",
type: "get",
success: function (result) {
$('#milestonesContainer').html(result);
},
error: function (xhr, status, error) {
var msg = "Response failed with status: " + status + "</br>"
+ " Error: " + error;
$('#milestonesContainer').html(msg);
},
complete: function (xhr, status) {
var doneMsg = "Operation complete with status: " + status;
alert(doneMsg);
}
});
});
for this ActionResult:
public PartialViewResult GetMilestones()
{
return PartialView("_GetMilestones");
}
The partial view has the milestones for a project (milestones and project are models). When I call the partial view like this:
<div id="milestonesContainer">
#Html.Partial("_GetMilestones")
</div>
it works fine, it gets all the milestones for the project.
But when I try to call the partial view via ajax, the error gets called: Response failed with status: error
Error: Bad Request
I'm in the details view of a projects so the url is like this http://localhost:55623/Projects/Details/2002
I'm new in ajax and javascript, so please if possible, explain me like you do to a beginner.
UPDATE:
After getting some answer and playing around to find a solution, I understand why the error appears.
I'm inside the details view, so the url is like this: http://localhost:55623/Projects/Details/2002 see there is an ID parameter.
When I make the ajax call, the url is like this http://localhost:55623/Projects/Details without the id parameter. So in return I get a 400 error code
To build on my comment:
Sorry, I was being ambiguous with the term url. Here's what I meant:
Unless your currentl url in the browser is http://<hostname>/<Controller that contains GetMilestones>, your AJAX url is incorrect. The AJAX url needs to be /<Controller>/GetMilestones.
The beginning / takes you to the root of the project, then the rest is taken care of by your route config (typically /Controller/Method/Id). That's why the AJAX url usually needs to be /Controller/Method. However, if you are at the Index view, your url is typically http://<hostname>/Controller. So, if this is the case and your AJAX url is just Method, it will take you to http://<hostname>/Controller/Method since you didn't prepend your AJAX url with a /.
Instead of url: "GetMilestones", try using url: "#Url.Action("GetMilestones")" which will render the actual relative path of the action i.e. /{Controller}/GetMilestones.
Also ensure that you are referring to the correct file name in your controller, as in your view you refer to "_GetMilestone" and you say that works, but in your controller you reference "_GetMilestones" which would not resolve if your filename is indeed "_GetMilestone"
If you're getting a 500 error, that means it's likely that you're hitting the action and an exception is occurring before or while it renders the partial view. Try navigating directly to the partial view's action in your browser by typing localhost:port/Projects/GetMilestones and see if an exception page appears. Make sure you do something like this in the Configure method of your Startup class:
public void Configure (IApplicationBuilder app)
{
app.UseDeveloperExceptionPage();
}
You should consider taking advantage of the helper methods like Url.Action to generate the correct relative path to the action method you want to call via ajax. If you are js code is inside the view, you can simply call the method like
url: "#Url.Action("GetMilestones","Project")",
If it is in an external js file, you can still use the helper method to generate the path and set it to a variable which your external js file. Make sure to do javascript namespacing when you do so to avoid possible overwriting of js global variables.
so in your view/layout you can do this
<script>
var myApp = myApp || {};
myApp.Urls = myApp.Urls || {};
myApp.Urls.mileStoneUrl= '#Url.Action("GetMilestones","Project")';
</script>
<script src="~/Scripts/PageSpecificExternalJsFile.js"></script>
And in your PageSpecificExternalJsFile.js file, you can read it like
$(function(){
$('#btnGetMilestones').click(function () {
$.ajax({
url: myApp.Urls.mileStoneUrl,
//Your existing code goes here
})
});
});
You need to change first url to something that match the route:
'/<Controller>/GetMilestones/'
switch from PartialViewResult to ActionResult
go for ajax like:
url: "GetMilestones",
type: "get",
contentType: 'application/html; charset=utf-8',
dataType : 'html'
Thanks to all for answering. I got an answer for my problem, maybe it's kinda not expected. Her it is:
change the ajax method:
$('#btnGetMilestones').click(function () {
$.ajax({
url: '/Projects/GetMilestones/' + "?id=" + window.location.href.split('/').pop(),
type: "GET",
success: function (data) {
$('#milestonesContainer').html(data);
},
error: function (xhr, status, error) {
var msg = "Response failed with status: " + status + "</br>"
+ " Error: " + error;
$('#milestonesContainer').html(msg);
},
complete: function (xhr, status) {
var doneMsg = "Operation complete with status: " + status;
alert(doneMsg);
}
});
});
and the action result:
public ActionResult GetMilestones(int? id)
{
var forProject = db.Projects.Where(x => x.ID == id).SingleOrDefault();
return PartialView("_GetMilestones",forProject);
}
Or same action result but the ajax request slightly dirrent:
$('#btnGetMilestones').click(function () {
var id;
id = #Model.ID;
$.ajax({
url: '/Projects/GetMilestones',
type: "GET",
data: "id="+id,
success: function (data) {
$('#milestonesContainer').html(data);
},
error: function (xhr, status, error) {
var msg = "Response failed with status: " + status + "</br>"
+ " Error: " + error;
$('#milestonesContainer').html(msg);
},
complete: function (xhr, status) {
var doneMsg = "Operation complete with status: " + status;
alert(doneMsg);
}
});
});
I am working on jquery ajax. I am using the code as follow :
var url = baseurl +"/index.php/users/ajaxwixusers";
var dataStringfirst = 'wixuserid='+ instanceId;
$.ajax({
//dataType : 'html',
type: 'GET',
url : url,
data : dataStringfirst,
complete : function() { },
success: function(data)
{
alert(data);
window.location.href="http://localhost:81/customers/index.php/acappointments/appointuseroverlay/user_id/203";
}
});
In PHP file I am getting the value as :
echo $user_id = $wixuser->id;
I want to return ths value on success. When I am trying to alert the output of ajax.
It is returning the complete HTML of the file. How can I return only value instead of complete HTML?
It returned complete HTML because your app kept running and rendering the rest of the request after your echo command. You should add one line exit instead.
exit();
Ajax response always gives complete data as output from requested page and If you don't want to use HTML then why you are placing it there? If you want to get any specific value then Print that value only don't use HTML on that page.
I am trying to post value using javascript in form_dropdown('') but it is not posting data on form.
Jquery library is loaded. On alert it display record of dep_selected
JQUERY On view page
function get_subdepartment() {
var dep_selected = $('select[name=txtDept]').val();
$.ajax({
data: {
dep_selected: dep_selected,
},
type: 'POST',
url: 'addVacancy/getSubDept',
success: function(data){ //alert(dep_selected);
console.log(data);
$('.subdepartment').html(data);
}
})
}
Controller Page:
function getSubDept(){
if($this->input->post('txtDept')){
echo "getSubDept > Dept: ".$this->input->post('txtDept');
}
else{
echo "getSubDept > No Return";
}
}
It display "getSubDept > No Return" Please help.
Well it's obvious, that in your controller you are requesting a post value by the key txtDept, but you don't have that when you send data with AJAX. What you have now is:
var dep_selected = $('select[name=txtLocation]').val();
and
data: {
dep_selected: dep_selected,
},
So you should simply change the first line in your controller method to
if($this->input->post('dep_selected')) {
I suggest you to do some reading about POSTing values with AJAX and how to work with JSON.
I am trying to use jQuery ajax to get some values from the database and then return them in an array.
I have used the same code several times before but this time, no response is being returned. Although the post values are the correct values that I would expect. Here is the javascript code that I am using:
$.ajax({ url: '/BlogArchive.asmx/ChangePost'
, type: 'POST'
, contentType: 'application/json; charset=utf-8'
, data: '{FileName:"' + FileName + '"}'
, dataType: 'json'
, success: function (data)
{
var arrayList = data.d;
var BlogPostTitle = $(".BlogPostTitle")[0];
var BlogPostDate = $(".BlogPostDate")[0];
var BlogPostContent = $(".BlogPostContent")[0];
$(BlogPostTitle).html(arrayList[0]);
$(BlogPostDate).html(arrayList[1]);
$(BlogPostContent).html(arrayList[2]);
}
// , error: function (XMLHttpRequest, textStatus, errorThrown)
// {
// //There was an error
// alert('dfd');
// }
});
The only javascript error that I am receiving is that data is null, which I would expect as the response is blank.
It seems that the name of the web method that I am calling from my javascript is not even being read, because if I changed 'ChangePost' to 'ChangePost1' for example, it still returns a blank response, although I would expect an error message saying that the web method can't be found.
It seems that it does recognise that the BlogArchive.asmx web service exists because if I put something that would create an error in the VB code, the error appears as the response.
I am sure this must be something simple that I am doing wrong. Any help would be appreciated.
, data: '{FileName:"' + FileName + '"}'
Seems odd. You probably meant:
, data: {FileName: FileName}
(or 'FileName=' + FileName)
Furthermore, did you inspect the request (and response) via FireBug or similar?
You should try using jQuery getJSON with the minimal arguments.
Another thing, when you are using JSON with jQuery, if the answer data are not wellformed
(like a space before / after the starting JSON string) could lead to a blank answer from
jQuery.
Be sure using traditionnal AJAX with jQuery that your answered data are correct.