While working on a website I had a content area division whose content I wanted to update according to the image I click on. Now, I had a customized scrollbar which I used in the content area. Now at first I wrote the following snippet for onclick script function :
function xyz(){
$("#content-area").load("abc.php");
$("#content-area").mCustomScrollbar({scrollButtons:{enable:true}});
}
But the second line of the script wasn't responding i.e, I wasnt getting the scrollbar. Instead when I used this piece of code snippet it worked :
$.post("abc.php", function(data){
$("#content-area").html(data);
$("#content-area").mCustomScrollbar({scrollButtons:{enable:true}});
});
I am wondering the function of the $.post() and why the first snippet didnt work while the second snippet worked?
In the first case that mCustomScrollbar will be executed right after the AJAX request is sent: remember, first A in AJAX is for asynchronous. But it obviously has nothing to work on yet, as response from server is not here yet.
In the second snippet mCustomScrollbar widget creation happens right after the AJAX request's response is received (as this line is part of $.post success handler now) and that #content-area is filled with necessary structure (with .html()) call. So now it works correctly.
You can use the fact that $.load method can be supplied with custom callback function that will be executed when the request completes, as described here. For example:
$("#content-area").load("abc.php", function() {
$(this).mCustomScrollbar({scrollButtons:{enable:true}});
});
Note $(this) usage: as this is set to each DOM element in turn inside that callback function, you don't need to walk over the DOM looking for that content-area yet again; it's enough just to wrap that element into jQuery object.
You need to use callback function which is executed when request is complete:
$("#content-area").load("abc.php", function(){
$(this).mCustomScrollbar({scrollButtons:{enable:true}});
});
I suppose that in the first example the second statement was being executed before the completion of the .load() function. In the second you are correctly using the success function, which is only executed after the completion of the POST request.
Related
If I want to do some PHP on an event(e.g. onchange) should I use jQuery ajax like:
$("#elm").on("change", function(){
//ajax code
}
, should I use the PHP in the HTML attribute like:
<element onchange="<?php //stuff to do ?>"></element>
You seem to be conflating two different issues.
JS bound events vs intrinsic event attributes.
Bind your event handlers with JS.
Follow the principles of Progressive Enhancement and Unobtrusive JavaScript.
Ajax vs Putting PHP in a JS function
If you put PHP in a JS function then it will run when the PHP outputs the JS function to the browser, not when the JS function is called.
If you want to run PHP in response to an event, then you have to make an HTTP request to the server to run the PHP.
If you want to insert content from the load of page and leave it static, you should use only PHP.
If you want to insert content dynamically (changing with users interactions) you should use AJAX.
I can't found out what are you trying to achieve with your example, so not very sure what you should do there.
taking your code it would give this :
$("#elm").on("change", function(){
//ajax code
$.get('url', {data:'tosend'}, function(data){
// here you have the response of the php script in the data object
// it can be json for exemple
});
}
You must realise two things, your php code will be render when the page is loaded in the
browser so the second code you gave us
means that your "onchange" event is already present in your page.
If you want to request something (data, html, etc) to server from a loaded page, then do an ajax.
In that case below code is correct.
$("#elm").on("change", function(){
//ajax code
}
You cannot execute a piece of php code from client side. But you can assign values from php to javascript and then do operations on client side.
(Not sure if I missed an already similar answered question…)
On click of a button, I'm loading various images from a database via PHP/MySQL and appending it to the body (the actual images are of course not stored in the database, the correct selection of the images is based on a posted variable).
My goal is to display a loading indicator after pressing the button and hiding the indicator after all the image data has completely loaded and displayed. This may be an easy to solve callback issue but I'm just getting started with AJAX. :)
The following is the code I currently managed to come up with. I'm guessing the load() function is not really the right one here?
Thanks for your help!
$("#somebutton").click(function(){
alert("fetching…");
$.post('loadmore.php', {
somevariable: somevariable
},
function(data){
$("body").append(data);
$(window).load(function(){
alert("finished loading…");
});
});
});
The function you have with the finished loading... alert is a success callback, so it gets executed once the AJAX call has finished. This means you don't need to use $(window).load.
Also, you can use the html method on an element to change its contents and display a message.
Something like this would work fine:
$("#somebutton").click(function(){
$('#divID').html('Loading...');
$.post('loadmore.php', {
somevariable: somevariable
},
function(data){
$("body").append(data);
$('#divID').html('');
});
});
Read the docs http://api.jquery.com/jQuery.ajax/
Use the success callback to append the body and then the complete and error callbacks to clear things up correctly.
$("#somebutton").click(function(){
alert("fetching…");
$.post('loadmore.php', {
somevariable: somevariable
})
.success(function(data){$("body").append(data)})
.error(function(){alert("oh dear")})
.complete(function(){alert("finished loading…")});
});
Remember to always have a fallback for removing the loader - nothing worse than just having a loader and no way to remove it from the page and continue using the application / web site.
I managed to solve my problem by reading and tweaking the code in the following article.
The function load() with the equation containing the self-explanatory variables [imagesLoaded >= imageCount] did the trick.
Know when images are done loading in AJAX response
I would like to be able to execute a php script on a onclick state, but each page could hace multiple buttons each with a different action to send. I want the script to be executed, but i don't want the page tobe changed.
This is to execute a UDP client to change setting in a remote box.each button send a different action to different board, in fact i need to send 2 arguments to the script.
something like this i need to send: set_states.php?ip=xxx.xx.xxx.xx&cmd=CR1
Thanx for the help!
It doesn't really matter what the URL is. The important things is what HTML verb you are using (get, post, delete, put) and your returned content type. The URL can be anything. I'd just use some js library like jquery. Check out their $.get, $.post, $.ajax functions.
If you don't use a js library then you need to account for all the differences in various browsers. Typically though it goes something like this: http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first
In your case, I would use jquery (since it'll get you started extremely quickly). Since your variables are in the url and you aren't sending any other data you would use get. Typically for mutators you should use post. I don't think it matters in your case. Drop the following script on to your webpage (make changes as needed):
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script>
$(function(){
$('#the-id-of-your-button').live('click',function(){
$.get('set_states.php?ip=xxx.xx.xxx.xx&cmd=CR1',function(return){
alert('success');
});
});
});
</script>
The first part: $('#the-id-of-your-button').live('click' watches the browser in a sense to see if any elements that match appear and binds a click event to them. Live actively awaits for dom changes in a sense. Click is the handler, and $('#the-id-of-your-button') is the selector. The next part:
function(){
$.get('set_states.php?ip=xxx.xx.xxx.xx&cmd=CR1',function(return){
alert('success');
});
});
is what happens when the click event occurs. We call this an anonymous function. It can be rewritten as:
function onButtonClick(){
$.get('set_states.php?ip=xxx.xx.xxx.xx&cmd=CR1',function(return){
alert('success');
});
});
$('#the-id-of-your-button').live('click',onButtonClick());
or something like that, but thats just just to help you understand what is going on.
The next part:
$.get('set_states.php?ip=xxx.xx.xxx.xx&cmd=CR1',function(return){
alert('success');
});
is the ajax request and the function to execute if it successfully returns. In this case it will simply just alert us.
Oh also: $(function(){}); that wraps everything up, tells us to run the script when the page is ready. Soooo once the page is ready we will turn on the live command to watch for buttons. You may not need it (I know there are some cases, where it isn't important, but I put it there just in case).
You may need to tweak it a bit :).
I have some experience in PHP but not in JQuery that much.
My admin.php page has a div which has id named "table1" where content gets loaded via ajax:
document.getElementById("table1").innerHTML=xmlhttp.responseText;
xmlhttp gets data from sorgula1.php page which has some JQuery effects like highlighting table rows. When I'm trying to run the sorgula1.php alone, the highlighting works but when it is loaded via ajax to admin.php, highlighting and other JQuery effects are not working. I've tried everything to make it work but, I always failed.
For those of you who will ask me to remove the $(document).ready(function() statement, I'm informing you that it doesn't work.
Here is the sorgula.php code: sorgula1.php
please be specific about the answers guys.Thanx for all answers.
Maybe when you use innerHTML property, the javascript doesn't work. I think you can solve this problem by using jQuery load() function.
The problem is most likely that the elements loaded via ajax do not have the effects applied to them - have you tried calling the $("#myTable").tablesorter(); javascript (again) after the ajax response has been received and injected into the DOM?
Edit sorry it should probably be this code that you call:
$("tr").not(':first').hover(
function () {
$(this).css("background","yellow");
},
function () {
$(this).css("background","");
}
);
or use .live()
Try to rewrite your events to Live(). I would say that it doesn't work, because elements are loaded after the jQuery functions are registered. So try
$("tr").not(':first').live('hover',function(){ // CODE });
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.