I've got a problem since I've migrated from jQuery 1.11 to jQuery 3.0. I'm running a jQuery POST request and before the migration it first finished the html(data.responseText) and then moved on with the code that follows. Like this:
$.ajax({
type: "POST",
url: "/files/" + url,
data: $("#entryForm").serialize() + '&journal_id=' + journalId,
complete: function(data) {
$('#saveResults').html(data.responseText);
alert("function done");
}
});
In the data.responseText there is an alert which runs first and after complete the function html() the other alert("function done") was running.
After the migration the alert("function done") is running first so it appears the function html() is not finished at this point because the alert from the responseText is coming after the alert("function done"). So I tried this:
$.ajax({
type: "POST",
url: "/files/" + url,
data: $("#entryForm").serialize() + '&journal_id=' + journalId,
complete: function(data) {
$('#saveResults').html(data.responseText).promise().done(function() {
alert("function done");
});
}
});
Unfortunately this didn't fix my problem. Anyone an idea how to fix it?
Try this.
.html is set when response is back and when success is completed, complete is ran
success: function(data){
$('#saveResults').html(data.responseText);
},
complete: function(data)
{
alert("function done");
}
Related
im sure this is something obvious but I cant figure it out
onclick of button retrieveScoreButton my button is simply not doing anything
any help is appreciated, im attempting to append the data to a table but cant even get it to register the clicking of the button so I cant test the function showsccore
<button id="addScoreButton">Add score</button>
<button id="retrieveScoreButton">Retrieve all scores</button>
<br>
<div id="Scores">
<ul id="scoresList">
</ul>
</div>
<script>
$(document).ready(function () {
$("#addScoreButton").click(function () {
$.ajax({
type: 'POST',
data: $('form').serialize(),
url: '/addScore',
success: added,
error: showError
}
);
}
);
});
$(document).ready(function () {
$("#retrieveScoreButton").click(function () {
console.log(id);
$.ajax({
type: 'GET',
dataType: "json",
url: "/allScores",
success: alert("success"),
error: showError
}
);
}
);
});
function showScores(responseData) {
$.each(responseData.matches, function (scores) {
$("#scoresList").append("<li type='square'>" +
"Home Team " + matches.Home_Team +
"Away Team: " + matches.Away_Team +
"Home: " + scores.Home_Score +
"Away: " + scores.Away_Score
);
}
);
}
function showError() {
alert("failure");
}
</script>
</body>
</html>
There are a couple things wrong here:
console.log(id);
$.ajax({
type: 'GET',
dataType: "json",
url: "/allScores",
success: alert("success"),
error: showError
});
First, you never defined id. (After some comments on the question it turns out your browser console is telling you that.) What are you trying to log? You may as well just remove that line entirely.
Second, what are you expecting here?: success: alert("success") What's going to happen here is the alert() is going to execute immediately (before the AJAX call is even sent) and then the result of the alert (which is undefined) is going to be your success handler. You need a handler function to be invoked after the AJAX response, and that function can contain the alert.
Something like this:
$.ajax({
type: 'GET',
dataType: "json",
url: "/allScores",
success: function() { alert("success"); },
error: showError
});
(To illustrate the difference, compare your current success handler with your current error handler. One of them invokes the function with parentheses, the other does not. You don't want to invoke a handler function right away, you want to set it as the handler to be invoked later if/when that event occurs.)
I am trying to write a .ajax request through a form to log in. When I submit my form, nothing happens with either the success or error functions. I notice that if I put an alert box after the .ajax call it does not work either. I would expect, that if I am just incorrectly putting the data, I would at least expect the error alert box to show up? Here is my code:
var clientType = "clienttype";
$(document).ready(function(){
$("#login-form").submit(function(e){
$.ajax({
type: "POST",
url: "myurl",
data: $(this).serialize() + "&client_type=" + clienttype,
success: function(data) {
alert("sent" + data);
},
error: function(){
alert("Did not work");
}
});
e.preventDefault();
});
});
I noticed you're already using JQuery. So perhaps use the built in post function. Example below:
Also side note: You've got a slight type in your variable: data: $(this).serialize() + "&client_type=" + clienttype, clienttype was declared with a capital T: clientType
var clientType = "clienttype";
$(document).ready(function(){
$("#login-form").submit(function(e){
e.preventDefault();
$.post("myurl",{data:$(this).serialize(),client_type:clientType},function(data){
console.log("Date returned from request:",data);
// Returns JSON Data. So data.clientType.
},'json');
});
});
If you add in a trigger to cancel the page from being submitted, it should work (return false;), take a look below.
var clientType = "clienttype";
$(document).ready(function(){
$("#login-form").submit(function(){
$.ajax({
type: "POST",
url: "myurl",
data: $(this).serialize() + "&client_type=" + clienttype,
success: function(data) {
alert("sent" + data);
},
error: function(){
alert("Did not work");
}
});
return false;
});
});
What I'm tring to do is to load information from different pages, without having to refresh the whole main page...
Could you tell me how to adapt this code for loading files with different names (like about.html and project.html?
Note: this code is made just for loading 'page_.html' files.
var default_content="";
$(document).ready(function(){
checkURL();
$('ul li a').click(function (e){
checkURL(this.hash);
});
default_content = $('#pageContent').html();
setInterval("checkURL()",250);
});
var lasturl="";
function checkURL(hash)
{
if(!hash) hash=window.location.hash;
if(hash != lasturl)
{
lasturl=hash;
if(hash=="")
$('#pageContent').html(default_content);
else
loadPage(hash);
}
}
function loadPage(url)
{
url=url.replace('#page','');
$('#loading').css('visibility','visible');
$.ajax({
type: "POST",
url: "load_page.php",
data: 'page='+url,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
$('#pageContent').html(msg);
$('#loading').css('visibility','hidden');
}
}
});
}
Here is the php file:
if(!$_POST['page']) die("0");
$page = (int)$_POST['page'];
if(file_exists('pages/page_'.$page.'.html'))
echo file_get_contents('pages/page_'.$page.'.html');
else echo 'There is no such page!';
You can make multiple ajax requests this is the jquery load method:
$( "#result" ).load( "ajax/test.html", function() {
alert( "Load was performed." );
});
do that 2x and your well off!
Keep in mind for this to work you'll need the jquery library.
I was doing a similar thing on my site here is my code:
window.setInterval("check()",60000);
//request information notice is inside a function called check() (it's not required to put inside function I only do this if I will be making the same request multiple time throughout the program)
function check() {
var request = $.ajax({
url: "file.php",
type: "POST",
dataType: "html"
});
request.done(function(msg) {
//when request is done:
$(".wheretoputnewdata").html(msg);
});
request.fail(function(jqXHR, textStatus) {
//if request failed do this:
alert( "Request failed: " + textStatus );
});
}
Replace this line
if(file_exists('pages/page_'.$page.'.html'))
with this
if(file_exists('pages/'.$page.'.html'))
I have some JavaScript that runs after a successful AJAX call:
$.ajax({
type: "POST",
url: "CalendarServices.aspx/UpdateFilter",
data: 'id=' + this.value + '&checked=' + $(this).is(':checked'),
success: function (data) {
$('#calendar').fullCalendar('refetchResources');
$('#calendar').fullCalendar('refetchEvents');
}
,
error: function () {
}
});
I do not want the user to visually see the changes of $('#calendar').fullCalendar('refetchResources');until $('#calendar').fullCalendar('refetchEvents'); has been called... is that possible?
This is because I inject some html in a callback for $('#calendar').fullCalendar('refetchEvents'); that gets destroyed when resources are fetched, so there is a small flicker.
Is there some way to do this?
I have the following code, intended to log the event when a user closes a chat window:
$(window).unload( function() {
test();
});
function test()
{
alert("Hi");
$.ajax({
type: "POST",
url: baseUrl + 'Index/test',
data: "user_id=" + "Nisanth" + "& chat_id=" + 2,
success: function(msg){
alert(msg);
}
});
alert('Success');
}
Both the "Hi" and "Success" messages alert fine but the alert in the AJAX callback doesn't... The operation I intend to trigger via the AJAX request is also not happening (I'm developing a chat application, and intend to log an entry in the database when the user closes the window).
Because the ajax is asynchronous, the page is unloading before the response is properly sent, effectively terminating the connection. Try setting async:false;, although this will delay unloading the page until after the response is received, which isn't great for user experience if your server is running slow.
$(window).unload( function () {
test();
});
function test()
{
alert("Hi");
$.ajax({
async: false,
type: "POST",
url: baseUrl + 'Index/test',
data: "user_id=" + "Nisanth" + "& chat_id=" + 2,
success: function(msg){
alert(msg);
}
});
alert('Success');
}
the problem is the format of your data. It is converted to a query string, it must be Key/Value pairs something like:
"user_id:value"