jQuery function to check if background page fully loaded? - javascript

I was wondering if it's possible to use the $().ready function to test if another page is fully loaded.
Here I'm talking about a newsfeed updater, where the function will send a POST request to a background php page to update the database, and then, using ajax, the newsfeed will reload to grab new data.
function send_data(){
var head = $("#headline").val();
var news = $("#news").val();
var info = '&headline='+head+'&news='+news; //update string
$.ajax({
url: 'recieve_update.php', //updating php file
type: 'POST',
data: info //data string
});
$().ready(function() {
$("#newsfeed").load("load_news.php"); //reload the newsfeed viewer
});
}

Use the callback function of $.ajax():
$.ajax({
url: 'recieve_update.php', //updating php file
type: 'POST',
data: info, //data string
success: function(){
$("#newsfeed").load("load_news.php"); //reload the newsfeed viewer
}
});

I believe something alone these lines would be what you're looking for. Straight from the jQuery source. http://api.jquery.com/jQuery.ajax/
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
$(this).addClass("done");
});

Related

URL jQuery ajax

I would want to post data to my "mail.py" script. But I don't know the URL to that file.
My jQuery AJAX code and this javascript file is placed in
RKProjects/scripts_js/contactform.js
My python script is placed in
RKProjects/scripts_js/mail.py
Here is my jQuery ajax code (without the URL)
var toPost = {
voornaamPost: document.getElementById('fnameInput').value,
achternaamPost: document.getElementById('lnameInput').value,
gsmPost: document.getElementById('gsmInput').value,
mailPost: document.getElementById('emailInput').value,
berichtPost: document.getElementById('berichtInput').value
};
var jsonToPost = JSON.stringify(toPost);
$.ajax({
type: 'POST',
url:'',
data: toPost,
success: function(){
alert('succes')
},
error: function (){
alert('error')
}
})
You have to specify the URL where to send the request to, otherwise it will point to the URL of the page you are on.
You have the following options:
$.ajax({
url: 'http://example.com/path/mail.py', // absolute
});
$.ajax({
url: '/path/mail.py', // relative to root
});
If you add the URL without the first "/" it will just append whatever you have to the URL of the page you are on.

Refresh page after delete photo

Hi I have function in javascript where I delete photos from database and from server. It work fine, I delete photo but this photo is still in my browser. I have question. How can I refresh only on javascript side?
container.addEventListener("click", function(e){
if(e.target.tagName == 'BUTTON'){
var id = e.target.dataset.type;
var r = confirm("Are You sure to delete?");
if (r == true) {
$.ajax({
type: 'POST',
url: 'index.php?r=gallery/deletep&name='+id,
dataType: 'html'
});
}
}
});
Now I treid to add
location.reload();
after ajax but I don't want to refresh all page. How Can i delete dynamically from browser?
OK in this type of situation you have two options. Either you load contents using AJAX request or remove the element from DOM either using class or id of that element.
So what happens is if you have loaded content using AJAX you can load all those contents again after successful deletion of image.
$.ajax({
type: 'POST',
url: 'index.php?r=gallery/deletep&name='+id,
dataType: 'html',
success: function(response) {
$(e.target).remove();
}
});
OR,
$.ajax({
type: 'POST',
url: 'index.php?r=gallery/deletep&name='+id,
dataType: 'html',
success: function(response) {
// use next ajax query to load content on DOM
}
});
you don't need to reload the whole page to remove the image. Use remove() API from jQuery in the success callback in AJAX call.
$.ajax({
type: 'POST',
url: 'index.php?r=gallery/deletep&name='+id,
dataType: 'html',
success: function(response){
$('img#id').remove();
}
});

Updating div content after form submit without page reload

alright, I have a popup which displays some notes added about a customer. The content (notes) are shown via ajax (getting data via ajax). I also have a add new button to add a new note. The note is added with ajax as well. Now, the question arises, after the note is added into the database.
How do I refresh the div which is displaying the notes?
I have read multiple questions but couldn't get an answer.
My Code to get data.
<script type="text/javascript">
var cid = $('#cid').val();
$(document).ready(function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "ajax.php?requestid=1&cid="+cid,
dataType: "html", //expect html to be returned
success: function(response){
$("#notes").html(response);
//alert(response);
}
});
});
</script>
DIV
<div id="notes">
</div>
My code to submit the form (adding new note).
<script type="text/javascript">
$("#submit").click(function() {
var note = $("#note").val();
var cid = $("#cid").val();
$.ajax({
type: "POST",
url: "ajax.php?requestid=2",
data: { note: note, cid: cid }
}).done(function( msg ) {
alert(msg);
$("#make_new_note").hide();
$("#add").show();
$("#cancel").hide();
//$("#notes").load();
});
});
</script>
I tried load, but it doesn't work.
Please guide me in the correct direction.
Create a function to call the ajax and get the data from ajax.php then just call the function whenever you need to update the div:
<script type="text/javascript">
$(document).ready(function() {
// create a function to call the ajax and get the response
function getResponse() {
var cid = $('#cid').val();
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "ajax.php?requestid=1&cid=" + cid,
dataType: "html", //expect html to be returned
success: function(response) {
$("#notes").html(response);
//alert(response);
}
});
}
getResponse(); // call the function on load
$("#submit").click(function() {
var note = $("#note").val();
var cid = $("#cid").val();
$.ajax({
type: "POST",
url: "ajax.php?requestid=2",
data: {
note: note,
cid: cid
}
}).done(function(msg) {
alert(msg);
$("#make_new_note").hide();
$("#add").show();
$("#cancel").hide();}
getResponse(); // call the function to reload the div
});
});
});
</script>
You need to provide a URL to jQuery load() function to tell where you get the content.
So to load the note you could try this:
$("#notes").load("ajax.php?requestid=1&cid="+cid);

loading gif with ajax request

$(".content-short").click(function() {
var ID = $(this).attr('data-id');
$('.loadingmessage').show();
$.ajax({
type: "post",
url: "collegeselect.php",
data: 'ID=' + ID,
dataType: "text",
success: function(response){
$(".content-full").html(response);
$('.loadingmessage').hide();
}
});
});
//collegeselect.php// is for loading data from database, //.loadingmessage// is for gif
when i am using this for the first time it displays gif,but the gif is not displayed after the 1st click as the data retrieved is already available in content-full from previous ajax request,
how to display it on every click on content short class?
That happens because you are replacing the actual content with loading GIF image with your response.
So, when you click first time it displayed and after the ajax call sucess as per the code you have replaced the content of .content-full and there is no GIF available then.
Solution : To resolve either send the same image tag with response or Move the loader image out side the .content-full.
Add beforeSend : function() before success in your request.
try
$(".content-short").live(function() {
var ID = $(this).attr('data-id');
$('.loadingmessage').show();
$.ajax({
type: "post",
url: "collegeselect.php",
data: 'ID=' + ID,
dataType: "text",
beforeSend : function()
{
$('.loadingmessage').show();
},
success: function(response){
$(".content-full").html(response);
$('.loadingmessage').hide();
}
});
});
From the comments, I gather that the img is within the .content-full container. The problem is that the img is removed when ajax succeeds since you're doing $(".content-full").html(). One way to fix it is to move the img out of the container. Another way is to store a reference to the img and add it back along with the response via .append() or .prepend() as below.
$(".content-short").click(function() {
var ID = $(this).attr('data-id');
$('.loadingmessage').show();
$.ajax({
type: "post",
url: "collegeselect.php",
data: 'ID=' + ID,
dataType: "text",
success: function(response) {
var $content = $(".content-full");
var $loaderImg = $content.find('.loadingmessage').hide();
$content.html(response).prepend($loaderImg);
}
});
});
Here is a demo mimicking the behaviour thru setTimeout.

How to redirect response from ajax request

I need to redirect to a page from response. I made a ajax call and can handle success. There is html page in response, but how to redirect it to that page.
Here's my code.
$("#launchId").live('click',function(){
var id= $("#id").val();
var data = 'id='+id;
$.ajax({
url: "xyz.json",
type: "post",
data: data,
dataType: 'json',
complete : function(response) {
window.location.href = response;
}
});
});
Not using ajax would make this easier:
<form type="POST" action="xyz.json">
<label for="id">Enter ID:</label><input id="id" name="id">
<button type="submit" id="launchId">Send</button>
</form>
If you really want to use ajax, you should generate a distinct server response, containing only the HTML parts you want to update in your page or actual JSON.
If you insist on using the response which you currently get, the appropriate way of dealing with it would be document.write:
$.ajax({
url: "xyz.json",
type: "post",
data: data,
dataType: 'html', // it's no JSON response!
success: function(response) {
document.write(response); // overwrite current document
},
error: function(err) {
alert(err+" did happen, please retry");
}
});
Please try this.
var newDoc = document.open("text/html", "replace");
newDoc.write(response.responseText);
newDoc.close();
Your response is an object containing the full HTML for a page in the responseText property.
You can probably do $(body).html(response.responseText); instead of window.location.href = ...; to overwrite the current page content with what you got a response.
...
complete : function(response) {
$(body).html(response.responseText);
}
But i suggest you don't and there could be style and other conflicts with whats already there on the page.
In your HTML add a div with id as 'content', something like this
<div id='content'/>
Since your response is html in your complete function append the content into the div like this -
complete : function(response) {
$('#content').append(response.responseText);
}
Let me know if you still face issues.
try this
$("#launchId").live('click',function(){
var id= $("#id").val();
var data = 'id='+id;
$.ajax({
url: "xyz.json",
type: "post",
data: data,
dataType: 'json',
complete : function(response) {
window.location.href = '/yourlocation?'+response;
}
});
});

Categories