I know this has been covered a few times, but I'm completely a noob when it comes to javascript so I have no idea what I'm doing. I am running a javascript that sends variables to a php file and that info is ajaxed into the current page using innerhtml. Here is that part of the code...
function givingHistory(dyear,did)
{
var divname="giving" + dyear;
$.ajax({
url: 'finance/givinghistory.php',
type: 'POST',
data: {
year: dyear,
id: did
},
success: function(givedata) {
document.getElementById(divname).innerHTML = givedata;
}
});
}
</script>
In the givedata function response from the php file there is a call to another javascript function that is already loaded in my common .js file (so both javascript functions are loaded when the page loads). How do I get the onClick that is added via innerhtml to work? Inside the php file, I check to see if id = a php session variable. If it does it spits out the text that includes the onClick.
If you use a specific id/class/identifier when the page loads in the $('*') function then the action will only bind to that. To get the action bind to anything ever try using $(document).on('click', **selector**, function() {});.
Previously there was bind/live that bound to elements as and when but on is the function now.
Also why are you mixing the $.ajax (jQuery) with document.getElementById(divname).innerHTML (regular javascript)? If you are already using jQuery you could just use $('#'+divname).html(blahbahblah);
Related
I've recently changed my searching page to a searchable datatable page due to my employer's request for easier data management. The problem is that it is taking too long to load.
I'm wondering it there is a way to only load like a portion of the table and finish loading the page first. Then finish off loading the rest of the table after that, e.g. while the user actually attempt to search for the data.
This was requested because the user might want to navigate to other parts of the page instead of using the datatable.
Extra info : The page is in .php and the data is loaded using php do-while loop. Maybe we can do a workaround using php functions?
Using the AJAX method recommended in the comments, the following is similar to how you could handle the page-load. You would need the jQuery library for the below.
Initial page
<script type="text/javascript">
// when the page is done loading,
// let's send a call to load more data
$(document).ready(function(){
myFunction();
});
// function to handle AJAX request to gather data
function myFunction(){
$.ajax({
type: "POST",
url: "./linkToMyPHP.php?loadData=1",
success: function(data){
// handle the data using the "data" variable
}
});
}
</script>
AJAX Page
<?php
if(isset($_GET["loadData"])){
// call query here and echo information
}
It may be recommended, to actually use a PHP function called json_encode() to echo back the information from your AJAX page in JSON form. This would allow you to transmit an array of information, instead of raw data. You would then need to update your AJAX request function similar to below.
$.ajax({
type: "POST",
url: "./linkToMyPHP.php?loadData=1",
dataType: "json",
success: function(data){
$("#myDivToChange").html(data);
}
});
You can read up on JSON at this highly rated question.
This question already has answers here:
using php include in jquery
(2 answers)
Closed 9 years ago.
My problem is that I need to include a PHP file inside a DIV when a button is pressed without the page reloading.
There is even more explanation in the 'Jsfiddle' file.
Below is an included Jsfiddle document.
http://jsfiddle.net/jjygp/5/
Thanks for your time. I am more than happy to provide any information upon request.
See here for your updated jsfiddle
You had marked the change button with a name of Change but were trying to select it with an id of change. Also, you had not told jsfiddle to include jQuery.
Try the following:
<button name="Change" id="Change">Change Div</button>
You are specifying a click function on an id, but no id is set on the button.
You can try with load() function in jquery
http://api.jquery.com/load/
PHP is a server-side script language, which will be executed before a JavaScript script did.
Therefore, you cannot use .load() to execute a PHP code, however, you may try .ajax() to create an AJAX request to the server which can implement the PHP code.
Please see http://api.jquery.com/jQuery.ajax/ if you have trouble on using .ajax().
Note: in .ajax() method, there is a setting called beforeSend, which "can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent". Hope this method helps you in any way.
Then, your JavaScript code will be like this:
$(document).ready(function(){
$("#Change").click(function(){
//doing AJAX request
$.ajax({
url:"include/start10.php",
beforeSend:function(){
$('#myDiv').fadeOut('slow');
},
success:function(data){
// do something with the return data if you have
// the return data could be a plain-text, or HTML, or JSON, or JSONP, depends on your needs, if you do ha
$('#myDiv').fadeIn('slow');
}
});
});
});
You cannot include PHP file with AJAX, but instead the response of the AJAX server-side script, which is the PHP (which has the same effect).
Loading...
The JS file (code):
function ajaxalizeDiv()
{
$.ajax({
type: "get",
url: "/path/to/the/php/you/want/to/include",
data: {
// Anything in json format you may want to include
id: myvarwithid, // descriptive example
action: "read" // descriptive example
},
dataType: "json",
success: onAjax
});
}
function onAjax(res)
{
if(!res || !res.text)
return;
$("#mydiv").html(res.text);
}
And here goes the PHP file:
<?php
$id = (int) #$_GET['id']; // same as in data part of ajax query request
$action = #$_GET['action']; // same as in data part of ajax query request
$text = 'click me';
// Note this is short example you may want to echo instead of die
// You may use not JSON, but raw text. However, JSON is more human-friendy (readable)
// and easy to maintain.
// Note also the array keys are used in the onAjax function form res (response).
die(json_encode(array('text' => $text /* and anything else you want */)));
?>
I am having problems with jQuery Ajax and PHP
I have my php file set up to echo the data I am gathering from a mysql database. I have verified that the database is returning something and that the string at the end of the function actually contains data.
What is happening though, is that it looks like the php echo is happening before the ajax call, causing the php data to be displayed at the top of the page, and not below in proper div.
I think it might have something to do with timing of the ajax and the php call, but I am not sure.
So, why is the data not getting caught by the .ajax and thrown into the div?
Thanks for the help!
jQuery
$(document).ready(function() {
$.ajax({
url: "../database_functions.php",
type: "GET",
data: "cat=jw&sub=pi&sort=no",
cache: false,
success: function (html) {
alert("Success!");
$('#product-list').html(html);
}
});
});
PHP
echo "Hello World";
Are you sure you didn't use an include or require in your page? Try doing the same
on a new empty dummy page. Also, try adding a thick red border to the div, so you are sure it is on the right position on the page, as there might be something wrong with your lay-out. Your code doesn't look wrong though.
If your JQuery code is in the same file as PHP code, it is given that PHP will be executed before JQuery code,.. since JavaScript is Client side, PHP is Server side, PHP file first get executed on the server, rendering static HTML from the dynamic PHP, and than when client browser render the page JavaScript get executed.
.ajax will be executed only once when whole page is loaded since you stated in JavaScript that you want that it get executed when document return event ready.
Why .ajax doesn't return value,.. It is not quite clear for the code you provided, problem could be in the file or path to the file ajax call trying to run.
I'm using Shadowbox a jquery overlay and I wanted to count how many people are actually using the overlay. Thus, I would need a function that would write a counter to a file or sending a query through a php api...
has to be a a php url api because I cant use php on the server where the overlay is.
So I need help with executing a javascript function on the overlay click, tips on how to make a counter query through GET method.
Thanks
<script type="text/javascript">
Shadowbox.init({
handleOversize: "resize",
overlayOpacity: 0.9
});
When you bind your click handler to open the shadownbox, add a binding for an ajax call, such as this:
$.ajax({
type: "GET",
url: "stats.js",
data: "name=urlOrNameOfItem"
});
Replace urlOrNameOfItem with something meaningful so you can track what has been clicked. I assume you know in php how to handle a query string.
See JQuery docs: http://api.jquery.com/jQuery.ajax/
Before you display your Shadowbox throw an Ajax query to a php script which would save the current request in a db (including $_SERVER info for better analysis).
This PHP script can fetch the current count of views for that image from the Db and update it accordingly.
I'm guessing the shadowbox function is called as a onclick event on your image so just add the Ajax call something like this:
$.ajax({
url: 'path-to-counter-script.php?i='+image-identifier,
success: function() {
//display shadowbox
}
});
I need to create a page that will load divs from an external page using Jquery and AJAX.
I have come across a few good tutorials, but they are all based on static content, my links and content are generated by PHP.
The main tutorial I am basing my code on is from:
http://yensdesign.com/2008/12/how-to-load-content-via-ajax-in-jquery/
The exact function i need is as follows:
Main page contains a permanent div listing some links containing a parameter.
Upon click, link passes parameter to external page.
External page filters recordset against parameter and populates div with results.
The new div contains a new set of links with new parameters.
The external div is loaded underneath the main pages first div.
Process can then be repeated creating a chain of divs under each other.
The last div in the chain will then direct to a new page collating all the previously used querystrings.
I can handle all of the PHP work with populating the divs on the main and external pages.
It's the JQuery and AJAX part i'm struggling with.
$(document).ready(function(){
var sections = $('a[id^=link_]'); // Link that passes parameter to external page
var content = $('div[id^=content_]'); // Where external div is loaded to
sections.click(function(){
//load selected section
switch(this.id){
case "div01":
content.load("external.php?param=1 #section_div01");
break;
case "div02":
content.load("external.php?param=2 #section_div02");
break;
}
});
The problem I am having is getting JQuery to pass the dynamically generated parameters to the external page and then retrieve the new div.
I can currently only do this with static links (As above).
I'm not sure if you've solved this already, but I'm surprised no one's mentioned to use the ajax() function.
This would allow you to define the request type as GET:
function loadContent(id) {
$.ajax({
type: "GET",
url: "external.php",
dataType: 'html',
data: {param: id},
success: function(html){
$("#container").html(html);
},
error: function(){
},
complete: function(){
}
});
}
Just call this function instead of using load. Obviously you'll have to tinker with the code (mainly what goes in the success function) a little, but this should give you a good starting point.
You can use the optional data argument to pass parameters to the GET request. Read the documentation. This is far better than building the URL yourself. You can of course add dynamic generated data to the parameters list.
function loadDiv(evt)
{
// these params will be accessible in php-script as $_POST['varname'];
var params = {name:'myDiv', var1:123, var2:'qwer'};
$.post('http://host/divscript.php', params, onLoadDiv);
}
function onLoadDiv(data)
{
$('#myContainer').html(data);
}
$(document).ready(function() {
$('#divButton').click(loadDiv);
});
In this example server-side script should return inner content of your div. Sure you can return XML-serialized data or JS to eval etc... it depends on task. The example is simplified, so extend it to fit your needs.
This tutorial on loading AJAX content is good:
http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/
Especially the part explaining how to read the results with Firebug.
Use this :
function GetDiv(id) {
$.ajax({
type: "GET",
url: "external.php"
dataType: 'html',
data:id,
success: function(html){
$("#container").append(html);
},
});
}
var params = {
param: 1,
otherParam: 2
};
content.load("external.php #section_div01", params);
will load "external.php?param=1&otherParam=2"