I'm getting error 404 while making ajax calls to my MVC controller
Here is the scenario:
I have 2 controllers:(PartnerControler,GettingSartedController)
While on the getting started page:http://mysite/GettingStarted/ I make the following ajax call:
$scope.SubmitRegistration = function() {
return $http({
url: '/partner/register',
method: 'POST',
data: $scope.UserAccount,
headers: {
'Content-Type': 'application/json'
I get a 404 on the call to the controller.
when I add the exact register method to the gettingstarted controller and change the ajax URL to the following it works:
url: '/gettingstarted/register',
When on web a page that uses a specific controller can you make calls to another controller?
How can this be achieved modifying the above script?
If you have separate js files, you can use workaround like below
<input type="hidden" id="registerurl" data-register-url="#Url.Action("register", "partner")"/>
and use this element's attribute as url to be used in your http call
var urlRegisterPartner = $('#registerurl').data('register-url');
I found another very good answer here in
https://stackoverflow.com/a/57274117/14181068 for
Ajax call to a different controller
This is the summary i got from the answer.
url on ajax
result
your/path
http://example.com/Home/your/path
~/your/path
http://example.com/Home/~/your/path or http://example.com/your/path
.../your/path
http://example.com/Home/.../your/path
../your/path
go up one directory level, resulting in http://example.com/your/path.
/your/path
http://example.com/your/path
sample
$.ajax({
type: 'Get',
url: "YourUrlHere",
data: { id: $('#inputId').val() },
})
.done(function (response) {
if (response.length > 0) {
}
})
.fail(function (error) {
alert(error.StatusText);
});
Related
I need a way to generate a new unique id for a user when a person focuses out of a textbox. I am using MVC 5 for this application. Here is my controller, everything in the controller has been unit tested and it does return the string value that I need.
Controller. I was able to visit that URL, and I did download a JSON file with the correct data.
public ActionResult GetNewId()
{
string newId = utils.newEmployeeId();
return Json(new {eId = newId}, JsonRequestBehavior.AllowGet);
}
Javascript, JQuery call to that controller. I do not know how to properly reference the ActionResult. I keep getting undefined errors on eId.
$(function () {
$('#employeeId').focusout(function () {
if($("#employeeId").val() === "NP")
$.ajax({
type: 'GET',
url: '#Html.ActionLink("GetNewId", "Employees")',
data: { 'eId': eId },
dataType: 'json',
success: function (response) {
$("#employeeId").val(eId);
},
error: function (response) {
alert(response);
}
});
});
});
The problem is with yout ajax request:
1.you need to change the url in the reuqest but it like this
{{yourcontroller}/GetNewId}
2.remove the "data: { 'eId': eId }" you dont need it, youre not posting anything to the server.
change your $("#employeeId").val(eId); to
$("#employeeId").val(response.eId);
this will 100% work
Hello StackOverflow family. This is my very first question and I hope to get help.
I'm new to laravel framework and am using version 5.2 in my project.
Am trying to pass data using the post method from my ajax function to a particular controller method but no data is passed to the controller.
I followed the steps in this forum https://laracasts.com/discuss/channels/laravel/process-data-in-controller-using-ajax-in-laravel but can't get it to work. Here is what I've done so far.
My JavaScript (post_script.js):
$.ajax({
method: 'POST',
url: './home',
data: {
userID: 76,
userName: 'Jimmy'
},
});
Note that this file is saved in assets/js directory in the laravel structure. Here is what I have in my route file (routes.php):
Route::get('/', "MyController#home");
Route::get('home', "MyController#home");
Here is the function I have in MyController.php file:
function home(Request $request) {
$userID = $request['userID'];
$userName = $request['userName'];
return view('home', [
'userID'=> $userID,
'userName' => $userName
]);
}
In my view, I tried to access it like this:
<p>User ID: {{$userID}}</p>
<p>User Name: {{$username}}</p>
Nothing is displayed! Please what am I doing wrong? I need your help. Forgive me if my question is not proper but I hope you get what I mean. Thank you
Your AJAX is POSTing, but you have no POST route set, only GET. Add a POST route, like so:
Route::post('home', "MyController#home");
First check with your developer/network tool (eg. firebug) wether your ajax call reaches the desired controller/functions and that the parameters are forwarded correctly.
A safe way to specify Url in the ajax call in the Laravel environment is using the URL facade like this:
url: "{{ URL::to('home'); }}",
In order to do it like this however you must store your js as a myscript.blade.php (!!) file and #include it into your view accordingly.
For receiving your posted parameters in the controller function there is no need to declare function arguments, you can simply use the Input::Get() function eg. like this:
public function home()
{
$userID = Input::Get('userID');
$userName = Input::Get('userName');
return view('home', [ 'userID'=> $userID, 'userName' => $userName ]);
}
If you try to do POST request you may need to have X-CSRF-Token.
Add this to meta:
<meta name="csrf-token" content="{{ csrf_token() }}">
And setup your AJAX:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
In Laravel docs: https://laravel.com/docs/5.2/routing#csrf-x-csrf-token
First you need set up dataType for ajax request like this (if you using jQuery)
$.ajax({
method: 'POST',
url: './home',
dataType: 'json'
data: {
userID: 76,
userName: 'Jimmy'
},
})
then try use into your controller as follow
Request::json()
and see result
Also you may use Input::get() :
Request::get('userID')
you can use route name to pass your data to the controller
$.ajaxSetup({
headers:{'X-CSRF-TOKEN': $("meta[name='csrf-token']").attr('content')}
});
$.ajax({
type:'POST',
url: '{{route("route_name_with_post_method")}}',
data:{
'id': data
},
success:function(r){
},error:function(r) {
}
});
Im trying to post a api using for my registration page and i have used $HTTP request to post data
it('login page to patient dashboard with existing email and password', function() {
console.log('entering login page')
browser.get('http://localhost:9000/login.html');
browser.executeScript(function(callback) {
var $http;
$http = angular.injector(["ng"]).get("$http");
console.log('http request')
return $http({
url: "http://int.eclinic247.com/reg/create-patient",
method: "post",
data: {"firstName":"jya","lastName":"raq"},
dataType: "json"
}).success(function() {
return callback([true]);
console.log('done')
}).error(function(data, status) {
return callback([false, data, status]);
console.log('oops not done!!!!')
});
})
element(by.model(Objects.locators.passwordBox)).sendKeys(Objects.login.password);
I see that the executeScript block doesnot run and there are no errors too...and the test case passes
Is this the way to post a http request using protractor...Please suggest me the proper to post a data to back-end directly
Any help is much appreciated...Thanks in advance
When an POST is made to the controller, the controller responds with exactly what I want the browser to render. But the browser does not render the response. I've verified the response is good in Fiddler.
The code below shows what I think is relavent code. The controller action method that returns the response, part of the template that has the mvc helper code, javascript/jquery code that fires the ajax call with the form inputs.
I want to use the FormCollection. Why doesn't the browser render the response and what can I do to fix it?
BoMController
public ActionResult GetBillOfMaterialsView(FormCollection frmColl){
// snipped out model interaction
return PartialView("~/Views/Project/Index.cshtml", project);
}
Index.cshtml
#using (Html.BeginForm("GetBillOfMaterialsView", "BoM", FormMethod.Post, new {id = "frmGetBom"})) {
// selProj input select code removed for brevity
}
function submitGetBoM() {
var frmGetBom = $('#frmGetBom');
$.ajax({
type: 'POST',
url: frmGetBom.attr('action'),
data: frmGetBom.serialize()
});
}
$(document).ready(function() {
$('#selProj').selectmenu( {
select: function(){submitGetBoM()}
}).addClass("overflow");
});
Invoking $.ajax alone doesn't append the response from the server to the document, you have to use the success callback to manually fetch the response and append it.
For example:
$.ajax({
type: 'POST',
url: frmGetBom.attr('action'),
data: frmGetBom.serialize(),
success: function(response) {
$('#someContainerId').html(response);
}
});
Alternatively, use load() that is a shorthand to the above:
$('#someContainerId').load(frmGetBom.attr('action'), frmGetBom.serializeArray());
See Documentation
Your client code doesn't do anything with the returned values from the server:
function submitGetBoM() {
var frmGetBom = $('#frmGetBom');
$.ajax({
type: 'POST',
url: frmGetBom.attr('action'),
data: frmGetBom.serialize(),
success: function() { alert('ok'); }
});
}
This would popup an alert on success.
I have a list containing news articles in the backend of a site which is then displayed on a homepage. I'd like the homepage to always display the most recent news.
I've never used AJAX before but in pseudo it would need to do the following:
call the homepage using an AJAX-get
Compare the article div with the same div from the AJAX-get.
If the AJAX-get has different content inside the div, display that
Can I do this with Jquery load, or do I need to go into AJAX for this functionality. and if so, could anyone give me a hand with the AJAX itself
trying to use AJAX, i have started using the following code, to no avail
$.ajax({
url: ctx.HttpRoot,
data: { "id": $("newsSliderWrapper").attr("id") },
success: function (data) {
data = $(data).find('div#newsSliderWrapper')
alert(data)
},
error: function () {
// your error logic
alert("AJAX failed");
}
})
AJAX in your case will do the following:
Ajax call will send the recent article ID to the server.
The server will compare the article ID. If the article ID is different, then the server will return the new article content. If the id is same, return different status message.
Ajax call will simply render the content
So
$.ajax({
url : "backendurl",
data : {"id" : $("recentarticleDivId").attr("id")},
// id must be the article ID which you need to match
success : function(data) {
$("#articleDivId").html(data);
},
error : function() {
// your error logic
}
})
$.ajax({
url: "homepage.php",
type: "GET",
data: { id : article_id },
success:function(data){
console.log(data);
// your logic
},
error:function(){
}
});