Say I wanted to invoke the following url that returns Json through an Ajax call:
http://open.mapquestapi.com/nominatim/v1/search?format=json&json_callback=renderBasicSearchNarrative&q=westminster+abbey"
How does on go about doing this?
I tried using the AjaxOptions.Url like this:
<span id="status">No Status</span>
<div>
#Ajax.ActionLink("Test", null, null,
new AjaxOptions
{
UpdateTargetId = "status",
Url = "http://open.mapquestapi.com/nominatim/v1/search?format=json&json_callback=renderBasicSearchNarrative&q=westminster+abbey"
})
</div>
but the url does not get invoked when i click on "Test" link.
I also tried:
<div>
<button value="get closest POI" onclick="testNominatim()"></button>
</div>
<script type="text/javascript">
function testNominatim() {
alert("called");
$.ajax(
{
type: "GET",
url: "http://open.mapquestapi.com/nominatim/v1/search?format=json&json_callback=onGetNominator&q=westminster+abbey",
contentType: "application/json; charset=utf-8",
dataType: "json",
failure: function (msg) {
alert(msg);
},
success: function (msg) {
alert(msg);
} });
function onGetNominator(msg) {
alert(msg);
}
</script>
When I click on button, message box shows but webservice does not get invoked.
I am probably missing something trivial but what is it?
TIA.
Edit 1 Changes to reflect actual script.
Using the second form would be my proposed solution. Note that the service requires a parameter named json_callback instead of the standard callback parameter for the callback function. This requires a bit of extra set up in the AJAX call.
Try the following. Note that I've changed the handler to apply it using code rather than in the markup. That's a better practice. I'm also using jQuery 1.7+. JSFiddle can be found at: http://jsfiddle.net/xVBBN/
<div>
<button>get closest POI</button>
</div>
<script type="text/javascript">
$(function() {
$('button').on('click',function() {
alert('called');
$.ajax({
type: 'GET',
url: 'http://open.mapquestapi.com/nominatim/v1/search?format=json&q=windsor+[castle]&addressdetails=1&limit=3&viewbox=-1.99%2C52.02%2C0.78%2C50.94&exclude_place_ids=41697',
dataType: 'jsonp',
jsonp: 'json_callback',
success: function(data) {
alert(data[0].place_id);
}
});
});
});
</script>
Try the following:
<div>
<button onclick="testNominatim()">get closest POI</button>
</div>
<script type="text/javascript">
function testNominatim() {
$.ajax({
type: "GET",
url: "http://open.mapquestapi.com/nominatim/v1/search?format=json&json_callback=onGetNominator&q=westminster+abbey",
dataType: "jsonp"
});
}
function onGetNominator(msg) {
alert(msg[0].place_id);
}
</script>
Things to notice (compared to your original code):
dataType: "jsonp"
you don't need a success callback because the success callback is your onGetNominator function
you don't need contentType: 'applicatin/json' because you are not sending a JSON request
or if you wanted to use an anonymous success callback:
<div>
<button onclick="testNominatim()">get closest POI</button>
</div>
<script type="text/javascript">
function testNominatim() {
$.ajax({
type: "GET",
url: "http://open.mapquestapi.com/nominatim/v1/search?format=json&json_callback=?&q=westminster+abbey",
dataType: "jsonp",
success: function (msg) {
alert(msg[0].place_id);
}
});
}
</script>
Things to notice (compared to your original code):
json_callback=? in the query string which will be replaced by jQuery with a random name allowing to invoke the anonymous success callback
you no longer need the onGetNominator function because we use the anonymous success callback
you don't need contentType: 'applicatin/json' because you are not sending a JSON request
And as far as the Ajax.ActionLink helper is concerned, I don't think that it support JSONP.
Related
I want to update my partial View with Ajax, but for some reason, it doesn't work. If I use load method (and comment ajax code), it works. this is my code:
this is my main View:
#model IEnumerable<WebApplicationMVC.Models.Test>
#{
ViewData["Title"] = "Testing";
}
<div id="partial">
#await Html.PartialAsync("Question", Model.ToList()[0])
</div>
<input type="button" id="b" value="next" class="btn btn-default" />
<script>
$("#b").click(function () {
//this code doesn't work
$.ajax({
url: 'Test/Question',
type: 'GET',
contentType: "application/json; charset=utf-8",
data: { id: '#Model.ToList()[1].ID' },
dataType: "json",
success: function (result) {
$("#partial").html(result);
}
});
//this code works
#*$("#partial").load('#Url.Action("Question","Test",new { id=Model.ToList()[1].ID })');*#
});
this is my question action method int Test controller:
public IActionResult Question(int id)
{
return View(Methods.GetTestById(id));
}
what mistake do I have?
You have specified dataType: "json", but your method returns a view (html), not JsonResult so an exception is being thrown.
Either omit the dataType option (the function will work it out based on the response) or change it to dataType: 'html'
In addition, your can delete the contentType option. You are making a GET which has no body so its ignored (and if it was a POST, your method would also fail because you have not stringified the data).
Your url should also be /Test/Question (leading forward slash), and you should always use the #Url.Action() method to generate the url
Your function should be
$.ajax({
url: '#Url.Action("Question","Test")',
type: 'GET',
data: { id: '#Model.ToList()[1].ID' },
success: function (result) {
$("#partial").html(result);
}
});
Please let me know the equivalent of below prototype code in Jquery.
var myAjax = new Ajax.Updater('abc', '/billing/add_bill_detail', {
method: 'get',
parameters: pars,
insertion: Insertion.Bottom
});
I want to perform the same action using Jquery.
Thanks in Advance.
In jQuery the Ajax will use as following:
$.ajax({
url: "/billing/add_bill_detail",
type: "get",
dataType: "html",
data: {"pars" : "abc"},
success: function(returnData){
$("#abc").html(returnData);
},
error: function(e){
alert(e);
}
});
Use #abc if abc is the id of the div or use .abc if abc is a class.
You can place the returnData iin your HTML where you want,
There are some ways using ajax like jQuery.ajax({...}) or $.ajax({...}) other than this there are some simplified versions of these too like:
$.get() or jQuery.get()
$.post() or jQuery.post()
$.getJSON() or jQuery.getJSON()
$.getScript() or jQuery.getScript()
$ = jQuery both are same.
As you are using method : 'get', so i recommend you to use $.ajax({...}) or $.get() but remember to include jQuery above this script otherwise ajax function wont work Try to enclose the script in the $(function(){}) doc ready handler.
'abc' if you could explain it
Try adding this with $.ajax():
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(function(){
$.ajax({
type: "GET",
url: "/billing/add_bill_detail",
data: pars,
dataType: 'html'
success: function(data){
$('#abc').html(data); //<---this replaces content.
},
error: function(err){
console.log(err);
}
});
});
</script>
or with $.get():
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(function(){
$.get("/billing/add_bill_detail", {data: pars}, function(data) {
$('#abc').html(data); //<---this replaces content.
}, "html");
});
</script>
or more simply use the .load() method:
$('#abc').load('/billing/add_bill_detail');
You can use .load() method
Load data from the server and place the returned HTML into the matched
element.
Read docs: http://api.jquery.com/load/
$(function(){
$.ajax({
type: "GET",
url: "abc/billing/add_bill_detail",
data: data,
success: function(data){
alert(data);
}
});
});
I call function from this code :
<div id="header-button-news" class="header-button-info">
<div class="new">2</div>
</div>
My function is
function showNews()
{
//other js which show block
jQuery("#loader").show();
//ajax which load content to block
jQuery.ajax({
type: "GET",
url: link,
dataType: "html",
success: function(data) {
jQuery('#top-info-news').html(data);
},
complete: function(){
jQuery('#loader').hide();
},
});
}
How can I make only once ajax call? so when content is loaded and page was not refresed not to load ajax? I tried to do boolean variables but nothing, I suppouse it is because I call everytime function. Please give me an idea how to do.
thank you
When you want to do something on that event.
Identify when you have already loaded your data.
var loaded = false;
function showNews() {
//other js which show block
jQuery("#loader").show();
if(loaded) return;
//ajax which load content to block
jQuery.ajax({
type: "GET",
url: link,
dataType: "html",
success: function(data) {
jQuery('#top-info-news').html(data);
},
complete: function(){
jQuery('#loader').hide();
},
});
loaded = true;
}
Or use one. when you want to call it once.
jQuery('.showNews').one('click', function() {
// your code
});
"Attach a handler to an event for the elements. The handler is executed at most once per element."
reference
Use the .one() function :
Attach a handler to an event for the elements. The handler is executed at most once per element.
I have added an id attribute to the anchor to allow an easier bind, but you could use $("#header-button-news a").one
$(document).ready(function () {
$('#shownews').one('click', function (evt) {
evt.preventDefault(); // prevent default click action
jQuery("#loader").show();
//ajax which load content to block
jQuery.ajax({
type: "GET",
url: link,
dataType: "html",
success: function (data) {
jQuery('#top-info-news').html(data);
},
complete: function () {
jQuery('#loader').hide();
},
});
});
});
Also used event.preventDefault() to prevent the default action on the anchor from being followed
<div id="header-button-news" class="header-button-info">
<a id="a_news" title="Новости"></a>
<div class="new">2</div>
</div>
In JS:
$(function(){
$('a#a_news').one('click',showNews);
})
The following code is alerting 'undefined' and not appending the html from the response data as I expected. Does anyone know why?
JavaScript:
$(function() {
$('.document').on('click', '.ajax', function(e) {
e.preventDefault();
// ajax request
$.ajax({
async: true,
cache: false,
type: 'post',
url: '/echo/html/',
data: {
html: '<p>This is echoed the response in HTML format</p>',
delay: 1
},
dataType: 'html',
beforeSend: function() {
console.log('Fired prior to the request');
},
success: function(data) {
console.log('Fired when the request is successfull');
$('.document').append(data);
},
complete: function() {
console.log('Fired when the request is complete');
}
});
});
});
HTML:
<div class="document">
<a class="ajax" href="#">Fire an AJAX request</a>
</div>
Example jsFiddle: http://jsfiddle.net/L6bJ2/3/
The HTTP method is specified with by type rather than method, so you should be using;
type: 'post',
Because you've specified the response type as HTML, you get a String passed in the data parameter of the success callback; but it looks like you're expecting JSON as you're trying to use data.html. Instead, use data directly;
success: function(data) {
console.log('Fired when the request is successfull');
$('.document').append(data);
},
With these changes, you'll find it works: http://jsfiddle.net/L6bJ2/6/
Live Example is here
https://stackoverflow.com/a/34940340/5361795
use beforeSend or complete callback functions in ajax call,
Source ShoutingCode
I have been learning AJAX for the best part of 2 hours, trying to get my head around how to get this to work, it seems it is calling the function as if I put an alert in, it all works fine.
I tried using another method and it seemed to call the function on it's own and it would load what the .php page is echoing.
What am I doing wrong in order for it to not work at all?
<script type="text/javascript">
$('a.fire').click(call_ajax);
function call_ajax() {
$.ajax({
type: "GET",
url: "http://127.0.0.1/onlineshop/admin/scripts/test.php",
dataType: "html",
success: function(html){
$("#holder").append(html);
}
});
}
</script>
Edit: I have also just tried
$('a.fire').click(function() {
$.ajax({
type: "GET",
url: "http://127.0.0.1/onlineshop/admin/scripts/test.php",
dataType: "html",
success: function(html){
$("#holder").append(html);
}
});
});
Which also does not work.
EDIT: I have now got code that GET's the php file I wanted, but for some reason does it on it's own
<script type="text/javascript">
function call_ajax() {
$.ajax({
type: "GET",
url: "http://127.0.0.1/onlineshop/admin/scripts/test.php",
dataType: "html",
success: function(html){
$("#holder").append(html);
}
});
}
<script type="text/javascript">
$(function() {
$(document).ready(function() {
$('a.fire').click(call_ajax());
});
});
The issue with this code is that it fires on it's own
EDIT: Now have new code, that is attempting to fire according to Firebug console but I get the alert ERROR: error, so I don't have a clue what is happening in order for it to fail, I have also tried many different URL's with no working solution
$('a.fire').click(function () {
$.ajax({
type: "GET",
url: "/onlineshop/admin/scripts/test.php",
dataType: "html",
success: function(html){
$("#holder").append(html);
},
error:function(xhr, text, error){
alert("Error: " + text);
}
});
});
SOLVED: I have now got it to work! For some reason my anchor had a href of "", which would cause it to reload the page and removing my GET from the page
ajax will only work if it's the same domain. This means that if you execute jQuery from domain x to domain y, it won't work. This is for safety-reasons to prevent websites from loading from another website. Does your jQuery-ajax call work if you remove the 127.0.0.1 from your url?
Furthermore I guess you should add the click-function inside your $(document).ready(); function, like this:
$(document).ready(function(){
$('a.fire').click(function() {
$.ajax({
type: "GET",
url: "onlineshop/admin/scripts/test.php",
dataType: "html",
success: function(html){
$("#holder").append(html);
}
});
});
});
for testing purposes, you can also use the complete function inside your ajax and alert your data. firebug can be helpful too to find your problem :)