I am trying to get some data using ajax in laravel project.
i have https domain but when the ajax request is made it is made over http.
So the ajax request gives a mixed content error and also a https request for same is showed cancelled.
i have already added to app service provider
if(config('app.env') === 'production') {
\URL::forceScheme('https');
}
main ajax setup with url formation
let url = '/opportunities/?' + $('#opportunity_search_form').serialize();
if(window.location.search && !this.initialLoaded){
url = url + '&' +window.location.search.substring(1);
}
url = url + '&page=' + self.pageCtr
$.ajax({
url: url,
type: "get",
beforeSend: function(xhr, type) {
if (!type.crossDomain) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
}
}
})
in the above image first request that shows cancelled goes over https ... and the other goes over http with mixed content error..i don't know how it is being sent .
Also i tried creating url using
let url = window.location.protocol + '//' + window.location.hostname + '/opportunties/' + other parameters
Thankyou.
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 have an interesting problem here. Here is the form where I want to use ajax to execute a post request on to the server.
replyPrefix = "<div id='addCommentContainer'><form class='addCommentForm' name='addcomment' id='addCommentForm'>" +
"<div class='input-group'>" +
"<input class='form-control' class='commentContent' type='text' placeholder='Comment!' name='commentContent'>" +
"<input class='form-control' class='commentParent' type='hidden' name='parent' value='";
replySuffix = "'>" +
"<span class='input-group-btn'>" +
"<button class='btn btn-danger' type='submit' class='submitButton'>submit</button>" +
"</span>" +
"</div></form></div>";
(The value for the reply is inserted inbetween this form's prefix/suffix. Note that this form and code was executing post requests fine before I tried moving to ajax)
Here is the jquery where I execute the ajax post request
$('.addCommentForm').submit(function() {
$.ajax({
type: "POST",
url: "/addcomment",
data: $(this).serialize(),
success: function(data) {
console.log("success:");
//alert(data);
},
error: function(e) {
console.log("error:");
}
});
});
And here is the nodejs express code.
// handle add comment call
router.post('/addcomment', function(req, res) {
//var obj = {};
console.log('body: ' + JSON.stringify(req.body));
//res.send(req.body);
//return;
var db = req.db;
var collection = db.get('comments');
// grab parent id if available
var parent = req.body.parent;
var content = req.body.commentContent;
console.log("parent: " + parent);
console.log("content: " + content);
// if no parent available, add new bubble
if (!parent || parent == "") {
console.log("Adding a bubble...");
addBubble(db, collection, content);
}
// otherwise, add comment to tree
else {
console.log("Adding a comment...");
addComment(db, collection, content, parent);
}
// DEBUG
//console.log(parent);
//console.log(req.body.commentContent);
//res.redirect('/');
});
The post request via ajax is being executed properly, and the reply gets added to the database and everything, however the page is constantly being reloaded when the post request is executed because of this get request that gets sent right before it everytime the form is submitted.
body: {"commentContent":"asdf","parent":"55f778aab671e4b41d05c6a7"}
parent: 55f778aab671e4b41d05c6a7
content: asdf
Adding a comment...
GET /?commentContent=asdf&parent=55f778aab671e4b41d05c6a7 200 65.626 ms - 53620
POST /addcomment - - ms - -
(Above is the console output, the question I have is why this get request with the data I submitted is being executed? How do I prevent that from happening?)
Thanks for the help.
It looks like you are submitting the form and the ajax request. Try adding the following to prevent the default submit action (GET).
.submit(function(e) {
e.preventDefault();
//ajax code
}
I'm trying to do a simple ajax GET that returns the html from google.com but with the following I keep hitting my onFailure. And when I hit status i get a 0, yet when I attempt to output the responseText I get nothing.
Anyone done a simple request like this in mootools 1.2.1?
function addSomeAction() {
el.onclick = function() {
var uri = "http://www.google.com";
var myRequest = new Request({
url: uri,
method: 'get',
onRequest: function(){
alert("loading...");
},
onSuccess: function(responseText){
alert("hi");
},
onFailure: function(responseFail){
alert("fail: " + responseFail.responseText);
}
});
myRequest.send();
}
}
Regardless of the framework used, you cannot do cross-domain AJAX requests. This is to prevent Cross-Site Request Forgery (CSRF) attacks and is a limitation imposed by the web browser.
Therefore, you can only fetch the HTML source of a page which on the same domain as the originating request.
There are specifications allowing for the asynchronous transfer of JSON data residing on another domain (JSONP), but they will not help you in this case.
I have this $.ajax (using jquery) code, it originally was the $.get that is now commented but for some reason I'm always getting the error and I can't find anything wrong with it =/, am I overlooking something?
$.fn.randomContent = function(options){
var contentArray = new Array();
var dType = "html";
var defaults = {
xmlPath: "../xml/client-quotes.xml",
nodeName: "quote"
};
var options = $.extend(defaults, options);
alert(options);
$.ajax({
type: "GET",
url: "../xml/client-quotes.xml",
dataType: "html",
success: function(){
$(defaults.nodeName).each(function(i){
contentArray.push($(this).text());
});
$(this).each(function(){
$(this).append(getRandom());
});
},
error: function(){
alert("Something Went wrong");
}
});
/*$.get(defaults.xmlPath, function(){
alert("get");
$(defaults.nodeName).each(function(i){
contentArray.push($(this).text());
});
$(this).each(function(){
$(this).append(getRandom());
});
}, type);//$.get*/
};
Here's the getRandom() function:
function getRandom() {
var num = contentArray.length
var randNum = Math.floor(Math.random()*num)
var content = "";
for(x in contentArray){
if(x==randNum){
content = contentArray[x];
}
};
alert(content);
return content;
}
It could be that the browser is caching your GET requests. In this case, either:
ensure the server is controlling your cache options (using cache-control settings of private or no-cache)
change the method of your AJAX call to POST instead of GET
differentiate your GET request by adding querystring parameters that change with each request
I prefer option #1, specifically because POST operations are intended to change something on the server, and so we should use that method when our actions do in fact modify server state. GET requests on the other hand, are requests that do nothing more than read data.
I feel a GET request is more appropriate for this task, and so in my own code I would prevent the caching of the response.
Does that url have to be absolute? I've never tried doing ajax requests with a "../" in it. Do you have FireBug installed? You could examine the response header from the sever.