In my navigation bar, I have Search
<li>Search </li>
I am making Ajax call, to go to different projects controller
$(".callSearch").click(function (e) {
e.preventDefault();
var url = '#Url.Action("Search", "Search")';
$.ajax(
{
type: "GET",
url: 'Search/Search',
//dataType: "json",
success: function () {
window.location = "https://localhost:xxx/Search/Search";
},
error: function () {
alert("Error");
}
});
});
Controller
[HttpGet]
public ActionResult Search()
{
return PartialView("~/Views/Search/_Search.cshtml");
}
With this code I posted the partial view is opening in new page. Search controller is in different project and layout file that has navigation and js is in different project.
I want to return the modal on the same page ....But right now its going to different page and navigation is gone on that page.
Any ideas on how to do that? I tried using Render a partial view inside a Jquery modal popup on top of a parent view but didnt work for me.
The window.location command causes your browser to navigate to a new location, as specified by the given URL.
Instead choose some existing element on your page where you wish to inject the contents of the partial, and set the innerHTML property of that element to be the contents of the response. e.g. let's say you have an existing div somewhere like this:
<div id="results"></div>
Then, in your JavaScript you can do this:
$(".callSearch").click(function (e) {
e.preventDefault();
var url = '#Url.Action("Search", "Search")';
$.ajax(
{
type: "GET",
url: 'Search/Search',
dataType: "html",
success: function (response) {
$("#results").html(response); //set the HTML content of the "results" div to be the response from the server, which contains the HTML generated by execution of the partial view
},
error: function () {
alert("Error");
}
});
});
N.B. Note that if you are making an ajax call to another project at a different URL and/or port you may have to setup the other project to accept CORS requests.
Related
Similar questions have already been asked for example this one How do I return a view from a spring controller using an ajax request?
however the answers do not give me any solution to my problem.
I also want to add that i am new to frontend development.
My problem is that i am calling a controller method with an ajax-script and after the call i want the user to be redirected to another view from the controller. However the returned view does not display in the browser, instead the browser remain in the view from which the script is triggered.
Although it seems that the return statement in the controller works in some way because in the browsers console i can see the html that is supposed to be displayed in the browsers window.
Another odd thing is that when i call other controllers in my project with parameters via thymeleaf the returned views are displayed as they are supposed to.
How can i direct the view "recipesOverviewPage" from the controller to be displayed in the browser instead of being displayed as html-tags in the console.
My script:
const sendArray = function() {
var ingredientNames = [];
$('#insertedFoodsList li').each(function(index) {
ingredientNames.push($(this).text());
});
ingredientNames = JSON.stringify({
'ingredientNames': ingredientNames
});
$.ajax({
url: "/foo",
type: 'POST',
data: ingredientNames,
dataType: "html",
contentType: 'application/json',
mimeType: 'application/json',
success: function(data) {
console.log(data);
return false;
}
});
};
The button that triggers the event:
<div class="btn" value="Submit" onclick="sendArray();" style="margin-left: 9em">Generate recipe</div>
The controller:
#RequestMapping(value = "/foo", method=RequestMethod.POST)
public String getSearchedRecipesFromIngredientInputField(#RequestBody RecipeSearchObject recipeSearchObject, Model model) {
model.addAttribute("recipeList",recipeService.getRecipesByIngredientList(recipeSearchObject.getIngredientNames()));
return "recipesOverviewPage";
}
I have a div element in my index.cshtml with id #myresults and i am trying to load data through jquery.load method by calling a mvc controller method. But i am not able to get the right syntax.
I am passing a custom object as a parameter as well.
var mycustomObject = {
obj1:value1,
obj2:value2,
..
}
The following does not work...(an i have tried other combinations as well..i get server not found error)
$("#myresults").load ('#Url.Action("MyActionMethod","Home")',mycustomObject);
while the following works
$("#myresults").load('/Home/MyActionMethod', mycustomObject);
While the last statement works, it works only on localhost.
Whats the right syntax to use for jquery load with Url.Action ?
#Url.Action() will always generate the correct url, so if your getting a 404, it means this code is in an external script file. Razor code is not executed in external scripts so your url would literally be the text "#Url.Action("MyActionMethod","Home")".
Options to solve this include
moving the code into the view or its layout
declaring a global variable in the view - var url =
'#Url.Action("MyActionMethod","Home")'; an in the external file use
$("#myresults").load(url, mycustomObject);
assign the url to an element as a data-* attribute, for example
<button type="button" id="loadSomething" data-url="#Url.Action("MyActionMethod","Home")">...</button>,and in
the external file
$('#loadSomething').click(function() {
var url = $(this).data('url');
$("#myresults").load(url, mycustomObject);
});
Define the div element as:
<div id="myresults" onload="loadMyData();"></div>
And make the ajax call in your method:
<script type="text/javascript">
function loadMyData() {
$.ajax({
cache: false,
url: '#Html.Raw(Url.Action(MyActionMethod","Home"))',
data: { obj1:value1, obj2:value2 },
dataType: "json",
type: 'post',
success: function (result) {
if (result.success) {
$('#myresults').html(result.data);
}
else {
alert("Failed to load data!");
}
}
});
}
</script>
I have this javascript functions,
This View function is a simple function that lets me go to my view page.
function View(URLPath) {
$.ajax({
url: URLPath,
type: "get",
dataType: "text"
}).done(function(data) {
$('#viewcontainer').html(data);
});
}
The other one is a simple function that let me add.
function Add(URLPath) {
var data = $("#Form").serialize();
$.ajax({
type: "post",
data: data,
url: URLPath,
complete: function(responseData){
View(ROOT_URL + '/view');
}
});
}
After I add data I want it to return to my view page. This will show that the data has been added.
So in the complete part of the Add function, I call the View function.
complete: function(responseData){
View(URL + '/view');
}
The problem is it will not load. It will return me to my home page.
I think it is because the add function is in another page and when I call the View function in the complete part, It will not find the id = #viewcontainer.
The view page will look like this
<div id="viewcontainer">
HERE IS THE VIEW
</div>
add will look like this
<p>THIS IS ADD</p>
EDIT
The files are already included.
If your viewcontainer is in view.html and you are trying setting $('#viewcontainer').html(data); which is in your home.html page; then it will not work as its not in the scope and unknown to the context.
You should include View function where it is called. If this a script file include or simple copy/paste function in same page where call.
Javascript required function on same page when finally render on browser.
If View(ULR) function not found you will received an error on console like function not defined
If you function exist on same page and div id not found you will also receive an error on console.
I want to know the content type of a given url input by the user inside my Javascript code. Actually, I have a drop-down list (html,csv,xls etc.) and I want to make it so when the user inputs an url, I want to detect the type of the content of the url and based on this type I want to set the value of my drop-down list (html,csv,xls etc.). I know, I can get the content type using Ruby like this :
require 'open-uri'
str = open('http://example.com')
str.content_type #=> "text/html"
or, also, I could use curl to get the content and then parse it to know the content type. But, I need to do this inside my Javascript code because of my need explained above. Any thought ?
EDIT_1 :
I tried this code in my javascript :
$("#wiki_form_url").change(function(){
$.ajax({
type: "GET",
url: "content.rb",
data: {
// input_url: $("#wiki_form_url").val()
},
dataType: "html"
}).done(function (data) {
// `data` contains the content-type
alert('Success !!!');
}).fail(function () {
alert("failed AJAX call");
});
});
I have a ruby script content.rb inside which I do :
require 'open-uri'
str = open('http://www.ofdp.org/benchmark_indices/25')
str.content_type
But, it does not seem to work. I am getting Ajax failure. May be it's because of url path of the script content.rb ? How should I specify a script path here ? (Relative or absolute)
The same origin policy prevents you from using client side JavaScript to directly discover information about arbitrary URIs (URIs you control are a different story).
You'll need to get that information with another technology, such as your server side Ruby.
You could do this by simply submitting a form to the server and returning a new webpage to the browser.
If you don't want to leave the page, then you can pass the data using Ajax. There are no shortage of Ajax tutorials out there, here is a good one from MDN.
Here's an example of an AJAX call:
$(document).ready(function () {
$("#button_check").on("click", function () {
$.ajax({
type: "GET",
url: "Your URL",
data: {
input_url: $("#textbox_id").val()
},
dataType: "html"
}).done(function (data) {
// `data` contains the content-type
alert(data);
}).fail(function () {
alert("failed AJAX call");
});
});
});
Where your HTML is something like:
<input type="text" id="textbox_id" />
<input type="button" id="button_check" value="Submit" />
And your Ruby code would be something like:
require 'open-uri'
class TestController < ApplicationController
def index
req = open(params[:input_url])
render :text => req.content_type
end
end
I have never used RoR before, so I have no idea if this is right or works in the slightest. But it's what I could quickly conjure up when scrambling through several tutorials. It's simply the concept you seem to be looking for. You'll need to figure out how to map a URL to this method, and then update the AJAX option url to use that.
So in the Javascript code - in the done method, that means the whole AJAX request was successful and the data variable should contain the result from the Ruby code req.content_type.
Atlast I could figure out the whole thing with the great help of #Ian. Here is my completed code : In javascript file :
$("#wiki_form_url").change(function () {
$.ajax({
type: "GET",
url: "/wiki_forms/content",
data: {
input_url: $("#wiki_form_url").val()
},
dataType: "text"
}).done(function (data) {
// `data` contains the content-type
alert('Success');
console.log(data);
// alert(data);
}).fail(function () {
alert("failed AJAX call");
});
});
Inside my wiki_forms controller I created a new method named content :
def content
req = open(params[:input_url])
render :text => req.content_type
end
Then added a new route in routes.rb file :
get "/wiki_forms/content" => 'wiki_forms#content'
and used /wiki_forms/content as the ajax request url. And, everything is working nicely now.
I have a page with cascad downloaded areas (select something in first area -> downloaded specific data to second area).
And I need to hide some content depending on data from the first area.
I need something like this (in javascript):
var result = getDataFromController(controllerName:"Quotes",
actionName:"IsQuoteOrdered",
param: quoteId);
Consider using jquery to simplify the ajax calls.
If you go that route the following would allow you to replace the dd2 element portion of the page with the result of a controller action call upon change of selection in dd1 :
$(document).ready(function() {
$('#dd1').change(function() {
$.ajax({
type: "POST",
cache: false,
data: 'firstDropdownSelectedValue=' + $('#dd1').val(),
url: 'YourControllerName/YourActionName',
success: function (data) {
$('#dynamicDivPortionOfThePageReturnedByYourView').replaceWith(data);
}
});
});
});