Onload Page load extern page - javascript

i use this AJAX script to load an extern page (mpt_planningen_overzicht.php) into a div op the mainpage (mainpage.php) when people select or unselect a checkbox.
But i also want to load the data from the extern page in the div when mainpage.php is opened.
How can i do this?
Script:
<script type="text/javascript">
$(document).ready(function(){
$('input[type="checkbox"]').on('click', function(){
var formData = $(":input,:hidden").serialize();
$.ajax({
type: "POST",
url: "mpt_planningen_overzicht.update.php",
data: formData,
success: function(result){ /* GET THE TO BE RETURNED DATA */
$("#resultaat").html(result); /* THE RETURNED DATA WILL BE SHOWN IN THIS DIV */
}
});
});
});
</script>
I thought something like this:
function onLoadSubmit() {
document.nameofForm.submit();
}
But the Ajax script that checks if a selectbox is checked/unchecked is already on mainpage.php, so when i add the script above, it will continue reloading.

If I understood the question correctly, you can try something like this:
<script type="text/javascript">
//separationg the function that loads the page in order to use it multiple times
var loadSepratePage = function(){
var formData = $(":input,:hidden").serialize();
$.ajax({
type: "POST",
url: "mpt_planningen_overzicht.update.php",
data: formData,
success: function(result){ /* GET THE TO BE RETURNED DATA */
$("#resultaat").html(result); /* THE RETURNED DATA WILL BE SHOWN IN THIS DIV */
}
});
}
$(document).ready(function(){
$('input[type="checkbox"]').on('click', loadSepratePage); // without paranthesis () to pass the function as a parameter
loadSepratePage() // with paranthesis () to actually call the function
});
</script>
If this is not what you mean feel free to leave comment

Related

How to make an AJAX call to an html element?

What I want to do is pretty simple. I want to make an AJAX call to a specific html class, so that whenever the html page is loaded, jquery will make an AJAX call to that specific html div class.
For example:
<div class="targeted"></div>
In jquery:
$('.targeted')
I know that the syntax to make an AJAX call is:
$.ajax({
type: "GET",
url: "/api/something",
success: function(data) {
console.log(data);
}
});
But how do I implement this AJAX call to the $('.targeted') whenever the page is loaded?
Thanks
If you mean you want to display the result of the ajax call in the element, you update the element from within the success callback:
$.ajax({
type: "GET",
url: "/api/something",
success: function(data) {
$('.targeted').html(data);
}
});
That example assumes
You want to replace the content of the element (rather than adding to it); more options in the jQuery API.
data will be HTML. If it's plain text, use .text(data), not .html(data). If it's structured data, then of course you'll need to do more work to put the information in the desired form.
window.onload = function() {
yourFunction();
};
function yourFunction(){
$.ajax({
type: "GET",
url: "/api/something",
success: function(data) {
$('.targeted').html(data);
}
});
}
OR Drectly you can pass that method in document ready it will execute automatically
$(document).ready(function(){
//This will execute onload oof your web page what you required
yourFunction();
})
function yourFunction(){
$.ajax({
type: "GET",
url: "/api/something",
success: function(data) {
$('.targeted').html(data);
}
});
}
For when the page is loaded, you use:
$( document ).ready(function() {
console.log( "ready!" );
});
Inside the document ready, you put your AJAX call. If the result you get is in JSON format, you need to include the dataType as well like this:
$.ajax({
method: "GET",
url: "/api/something",
dataType: "json"
})
.done(function( data ) {
$('.targeted').append(JSON.stringify(data));
});
If the result is not JSON, then you can just append the data.
Also note:
The jqXHR.success(), jqXHR.error() and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail() and jqXHR.always() instead.
Please look at the jQuery documentation.
you can use jquery load like this:
$(".targeted").load('/api/something');
if you want to wait untill after the page is loaded, wrap it with window load like so:
$(window).load(function () {
$(".targeted").load('/api/something');
});
P.S. $(window).load(..) and $(".class").load(url) are two different functions
You can do:
$(function() {
$.ajax({
type: "GET",
url: "/api/something",
})
.done(function(data) {
$('.targeted').text(data);
});
});

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 content in page via jQuery - codeigniter

I have two views main.php and details.php. In main.php there are numerous content and under each content there is a "view more" button. If somebody clicks view more an ajax call will dynamically load rest of the content from details.php which will fetch the data from database w.r.t the ID of the content. And it's a list style view in details.php.
In the header of main.php my main script file contains this code snippet to fetch data from details.php -
$('.view_more').click(function(e) {
$.ajax({
type: 'POST',
url: '/path/to/my/controller/method',
dataType: 'html',
success: function (html) {
$('#details_container').html(html);
}
});
});
Data is loading perfectly. But the problem is there is a add content button in details.php along with each content which has been loaded dynamically is not working. The content adding script is in my main.js added in main.php. But I have to add this particular jquery code snippet of adding the content in details.php, otherwise it's not working. So, whenever view more is being clicked it is returning html data along with a ....code for adding the content.... stick with it. Which is not at all desired.
How to solve this issue? Please help. Thanks in advance.
Here is the code of adding the content.
<script type="text/javascript">
$('.add_this').click(function(){
var t = jQuery(this);
var id_add = t.attr("id");
var content_category_id = t.attr("rel");
var add_content_id = id_add.substring(id_add.indexOf('_')+1);
var content_creator_id = t.attr("data-clip-id");
$.ajax({
type: "POST",
url: "/path/to/my/controller/method",
data: add_content_id,
cache: false,
success: function(response){
if(response)
{
$("#"+id_clip).text("Clipped");
}
}
});
});
</script>
I want to add again I am able to add the contents but to do so I have to embed this code snippet in details.php that I dont want to do. I need torun from my main script file.
This should work:
$(document).on('click','.add_this',function(){
var t = jQuery(this);
var id_add = t.attr("id");
var content_category_id = t.attr("rel");
var add_content_id = id_add.substring(id_add.indexOf('_')+1);
var content_creator_id = t.attr("data-clip-id");
$.ajax({
type: "POST",
url: "/path/to/my/controller/method",
data: add_content_id,
cache: false,
success: function(response){
if(response)
{
$("#"+id_clip).text("Clipped");
}
}
});
});

submit a form with jQuery function

i have a html page, which contains a form and i want when the form is successfully submited, show the below div:
<div class="response" style="display: none;">
<p>you can download ithere</p>
</div>
i also have a jquery function:
<script type="text/javascript">
$(function() {
$('#sendButton').click(function(e) {
e.preventDefault();
var temp = $("#backupSubmit").serialize();
validateForm();
$.ajax({
type: "POST",
data: temp,
url: 'backup/',
success: function(data) {
$(".response").show();
}
});
});
});
</script>
and in my views.py (code behind) i create a link and pass it to html page. i have:
def backup(request):
if request.is_ajax():
if request.method=='POST':
//create a link that user can download a file from it. (link)
variables = RequestContext(request,{'link':link})
return render_to_response('backup.html',variables)
else:
return render_to_response('backup.html')
else:
return render_to_response("show.html", {
'str': "bad Request! :(",
}, context_instance=RequestContext(request))
backup = login_required(backup)
my problem: it seems that my view doesn't execute. it doesn't show me the link that i send to this page. it seems that only jQuery function is executed. i'm confused. how can i make both of them to execute(i mean jQuery function and then the url i set in this function which make my view to be executed.)
i don't know how to use serialize function. whenever i searched, they wrote that:
The .serialize() method creates a text string in standard URL-encoded notation and produces query string like "a=1&b=2&c=3&d=4&e=5.
i don't know when i have to use it, while i can access to my form field in request.Post["field name"]. and i don't know what should be the data which is in success: function(data) in my situation.
thank very much for your help.
You have to get and display the data from your ajax post function, where data is the response you render through your DJango server, for example:
t = Template("{{ link }}")
c = Context({"link": link})
t.render(c):
Your JS / jQuery should become something like this:
<script type="text/javascript">
$(function() {
$('#sendButton').click(function(e) {
e.preventDefault();
var temp = $("#backupSubmit").serialize();
validateForm();
$.ajax({
type: "POST",
data: temp,
url: 'backup/',
success: function(data) {
// 'data' is the response from your server
// (=the link you want to generate from the server)
// Append the resulting link 'data' to your DIV '.response'
$(".response").html('<p>you can download ithere</p>');
$(".response").show();
}
});
});
});
</script>
Hope this helps.

Search box in a jQuery ajax success page - issues in loop

Firstly, there have some tag links in my main page. click each one, post value to b.php with jquery.ajax and turn back value in div#result.
b.php have a search box. when search something in it. the result data will still show in the div#result.
my problem is: I know if I will do jQuery ajax in the b.php, I shall write the jQuery code in the first success part. but this only can control one time, when I continue search in the search box, the jQuery not work. I think I met a loop problem. How to solve it?
a.php
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.click').click(function(){
var value1 = $(this).text();
$.ajax({
url: "b.php",
dataType: "html",
type: 'POST',
data: "data=" + value1,
success: function(data){
$("#result").html(data);
$('#search').click(function(){
var value = $('#search1').val();
$.ajax({
url: "b.php",
dataType: "html",
type: 'POST',
data: "data=" + value,
success: function(data){
$("#result").html(data);
}
});
});
}
});
});
});
</script>
<a rel="aa" class="click">aa</a>
<a rel="aa" class="click">bb</a>
<div id="result"></div>
b.php
<?php
echo $_POST['data'];
?>
<form name="form">
<input type="text" value="" id="search1">
<a name="nfSearch" id="search">search</a>
</form>
When a new element is introduced to the page the jQuery .click() method becomes useless because it can only see elements that were part of the original DOM. What you need to use instead is the jQuery .live() method which allows you to bind events to elements that were created after the DOM was loaded. You can read more about how to use it at the below link.
.live() – jQuery API
$('#search').live('click', function(e) {
// Prevent the default action
e.preventDefault();
// Your code here....
});
First of all i think you should attach the ajax call to the click on the link: the way you are doing right now just execute an ajax call as soon as the page is loaded.
$(document).ready(function(){
//when you click a link call b.php
$('a.yourclass').click(function(){
$.ajax({
url: "b.php",
dataType: "html",
type: 'POST',
data: "data = something",
success: function(data){
$("#result").html(data);
var value = $('#search').val();
$.ajax({
url: "b.php",
dataType: "html",
type: 'POST',
data: "data =" + value,
success: function(data){
$("#result").html(data);
}
});
}
});
});
});
In this way, each time a link with the class of "yourclass" is clicked an ajax call to b.php is sent and if it succed, another call is made (always to b.php). I don't understand if this is what you are looking fo, if you post your html my answer can be better.
In b.php of course you need to echo some html that can be used in the callback
It's strange how your attempting to do two ajax requests like that, surely one is enough. If you need to support multiple text boxes then you just adjust your selectors.
Your whole code can be shortended down to something like this:
$(document).ready(function() {
$('#result').load('b.php', { data: $('#search').val() });
});
So if you wanted to search for the value when clicking on a link (for links within #container):
$('#container').delegate('a', 'click', function() {
// .text() will get what's inside the <a> tag
$('#result').load('b.php', { data: $(this).text() });
});

Categories