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
Related
I have made this ajax request to show the validation errors and prevent the page to reload
$(document).on('mousedown', ':submit', function() {
//alert('clicked submit');
var form = $("form");
$.ajax({
type: 'post',
url: '/events',
headers: { 'X-CSRF-TOKEN': "{{csrf_token()}}" },
data: form.serialize(),
dataType: 'json',
success: function(data){
},
error: function(data) {
for(errors in data.responseJSON){
swal({text:data.responseJSON[errors]});
}
}
});
});
All is fine with this code! The problem is that after successfull submit i have 2 inputs in DB...how can i prevent this?
Are you sure the form isn't actually submitting and saving the values once by post and once by ajax? Usually if you're capturing a submit event you listen for the forms submit even not the mousedown event of the submit button e.g.
$('form').on('submit', function(e) {
// Stop the forms default submit action
e.preventDefault();
//alert('clicked submit');
var form = $("form");
$.ajax({
type: 'post',
url: '/events',
headers: { 'X-CSRF-TOKEN': "{{csrf_token()}}" },
data: form.serialize(),
dataType: 'json',
success: function(data){
},
error: function(data) {
for(errors in data.responseJSON){
swal({text:data.responseJSON[errors]});
}
}
});
});
Also the e.preventDefault() will prevent the form from submitting itself along with your ajax action. Also you'd best off selecting your form by an ID or class name.
I am trying to use jsonp to access the data at:
https://github.com/users/jbranchaud/contributions_calendar_data
However, none of the solutions I have tried are resulting in either the callback or the success function getting invoked. When I use Chrome/Firefox inspection tools, I can look at the script and see that the response was 200 Ok and that the response text contains the data from the above URL. Nevertheless, neither the callback function nor the success function get called at any point. Any ideas about how to get this to work?
Here is my most recent attempt at getting this to run:
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
function parseResults(results) {
console.log('hello function callback.');
}
$.ajax({
url: 'https://github.com/users/jbranchaud/contributions_calendar_data',
type: 'post',
dataType: 'jsonp',
jsonp: true,
jsonpCallback: 'parseResults',
success: function(data, textStatus, jqXHR) {
console.log('success_function');
console.log(data);
},
error: function() {
console.log('error with jsonp request');
}
});
</script>
When I load the page, I see the 'error with jsonp request' in the console, so there is an error with the ajax request. Ideas of why this request isn't succeeding?
In the ajax request, try to set the attribute 'jsonp' to false (jsonp: false).
Basically, JQuery generate an automatic function callback name, like this : JQuery1223...34.
In your case, you ,already, explicitly set the jsonpCallback function name. so you have to put jsonp attribut to false.
your code should be like this :
$.ajax({
url: 'https://github.com/users/jbranchaud/contributions_calendar_data',
type: 'post',
dataType: 'jsonp',
jsonp: false,
jsonpCallback: 'parseResults',
success: function(data, textStatus, jqXHR) {
console.log('success_function');
console.log(data);
},
error: function() {
console.log('error with jsonp request');
}
});
I am trying to submit a form with the user's inserted data and get the html back from the page called (update.asp).
How do I get the html response and how do I write it to a div on the page? The response would be "success".
If my page throws a 500 or other type of error, how can I handle that?
$('input#btnUpdate').click( function() {
$.ajax({
url: 'update.asp',
type: 'post',
dataType: 'json',
data: $('form#myForm').serialize(),
success: function(data) {
// how do i catch the response? is this the right place?
},
error: function(data) {
// how do I catch the error code here?
}
});
The response from the server in both cases would be passed to the callback as the data variable in your example. Try using console.log(data) inside of your callbacks to see the result in your developer console.
$('input#btnUpdate').click( function() {
$.ajax({
url: 'update.asp',
type: 'post',
dataType: 'json',
data: $('#myForm').serialize(),
success: function(response) {
$("#yourDIV").html(response);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError); //output, 500
}
});
});
More on this: ajax()
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);
})
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.