Cannot get .ajax to call my php script - php

for the life of me I cannot get my PHP file to be called using the ajax function. Here is my relevant HTML:
$(document).ready( function(){
$("#generate").click(function(){
alert("Been clicked");
$.ajax({
url: "filterScriptForMe.php",
success: function(data){
alert("response");
}
});
});
});
Here is my PHP file, which I can run by calling separately, and will print to the error log/echo/create the necessary image no problem when run on it's own:
error_log("script has been called");
$hello = imagecreatefrompng("./images/stock.png");
$hello = imagecreatefrompng("./images/stock.png");
imagealphablending($hello,false);
imagesavealpha($hello,true);
$x=imagecolorallocatealpha($hello,0,0,0,127);
$color = imagecolorat($hello,350,500);
for($y=0;$y<512;$y++)
for($z=0;$z<597;$z++)
{
if($color!=imagecolorat($hello,$y,$z))
{
imagesetpixel($hello,$y,$z,$x);
}
}
imagepng($hello,"done.png");
echo "done";
I am beginning to wonder if there is a problem on my server at this point. When run it will print the first alert saying "been clicked" but it does not seem to be running the php script as I get no output to my log files when clicking the button from the html file, as opposed to visiting the php directly in the broswer. Both the html and php are in the same directory, and I have double checked the names to make sure they are correct.
I know other jQuery functions are working on the page as well, as I've been successful in getting some jQueryUI elements to display and respond to manipulation using jQuery alone. Added to that the first alert seems to be firing, so I'm fairly sure the library/code is in there. I've tried going through with firebug, but it's a little beyond me when it starts getting deep into the library and I lose track of what's being done and why.
Any help that you can provide would be much appreciated, at least to get the PHP file called from the html page. Thanks!

Related

AJAX/PHP – callback after finished loading data

(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

php ajax within ajax

I have some ajax that loads php script output into a div. I would like the user then to be able to click on links in the output and rewrite the div without reloading the whole page. Is this possible in principle? Imagine code would look like:
html
<div id="displayhere"></div>
php1 output
echo 'ChangeToNew';
JS
function reLoad(par1,par2,par3) {
...
document.getElementById("displayhere").innerHTML=xmlhttp.responseText;
xmlhttp.open("GET","php2.php?par1="+par1 etc.,true);
xmlhttp.send();
php2
$par1 = $_get['par1'];
change database
echo ''.$par1.'';
Could this in principle work or is the approach flawed?
Thanks.
What you describe is standard, everyday AJAX. The PHP is irrelevant to the equation; the JS will simply receive whatever the server sends it. It just happens that, in your case, the server response is being handled by PHP. The JS and PHP do not - cannot - have a direct relationship, however.
So the principle is fine. What you actually do with it, though, will of course impact on how well it works.
Things to consider:
what will the PHP be doing? This may affect the load times
what about caching responses, if this is applicable, so the PHP doesn't have to compute something it's previously generated?
the UI - will the user be made aware that content is being fetched?
Etc.
I'm used to using jQuery so will give examples using it.
If you create your links as
Click Me
You could then write your code as
<script>
$("#do_this").live('click', function(){
var link_url = $(this).attr('href');
$.ajax({
url: link_url,
success: function(data) {
$('#displayhere').html(data);
}
return false;
};
</script>
If you use jQuery, make sure you use the .live('click', function(){}) method versus the .click(function(){}) method, otherwise it won't recognize dynamically created elements. Also make sure you do a return false.

jQuery.get() - How do I use the entire result?

I read this question, and I'm pretty sure it's 90% of what I need, but I'm after something more than just this, and my success formulating my query in Google has been less than stellar.
What I'd like to do
I have a form on a site that, when submitted, needs to connect with a database, and then the user needs to be apprised of the result. I'm trying to get the result page to load in a modal jQuery dialog instead of forcing a full page reload. At present, I'm just trying to create a jQuery dialog that replaces the contents of a <div> with the product of a PHP file. I know I will get the PHP file's execution result this way. That's what I'm after, but it currently is not working.
My code currently looks like this:
$(document).ready(function() {
$("#dialog").get('include.php', function(data) {
$("div#dialog").html(data);
});
});
And include.php is simply:
<?
echo "<h1>Loaded</h1>";
?>
When I load the page, the original contents of #dialog are still there. I have a strong suspicion that what I'm failing to grasp isn't major, but I've had bad luck finding the fix. I'm a web dev newbie. How do I wwebsite as on the internet?
You are calling get on a jQuery result. That'a a different method than $.get, the one you should be using:
$(document).ready(function() {
$.get('include.php', function(data) {
$("div#dialog").html(data);
});
});
i have been using Ajax call for the same purpose. So try this :
$(document).ready(function() {
$.ajax('include.php',
success : function(data) {
$("#dialog").html(data);
});
});
If you want to replace the entire contents of the #dialog DOM object with the HTML you load, then you probably want to use .load():
$(document).ready(function() {
$("#dialog").load('include.php', function(data) {
// no need to set the html here as .load() already does that
});
});

Jquery Ajax + PHP

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.

Why doesn't my <script> tag work from php file? (jQuery involved here too)

Here is what I am trying to accomplish. I have a form that uses jQuery to make an AJAX call to a PHP file. The PHP file interacts with a database, and then creates the page content to return as the AJAX response; i.e. this page content is written to a new window in the success function for the $.ajax call. As part of the page content returned by the PHP file, I have a straightforward HTML script tag that has a JavaScript file. Specifically:
<script type="text/javascript" src="pageControl.js"></script>
This is not echoed in the php (although I have tried that), it is just html. The pageControl.js is in the same directory as my php file that generates the content.
No matter what I try, I can't seem to get the pageControl.js file included or working in the resulting new window created in response to success in the AJAX call. I end up with errors like "Object expected" or variable not defined, leading me to believe the file is not getting included. If I copy the JavaScript directly into the PHPfile, rather than using the script tag with src, I can get it working.
Is there something I am missing here about scope resolution between calling file, php, and the jQuery AJAX? I am going to want to include javascript files this way in the future and would like to understand what I am doing wrong.
Hello again:
I have worked away at this issue, and still no luck. I am going to try and clarify what I am doing, and maybe that will bring something to mind. I am including some code as requested to help clarify things a bit.
Here is the sequence:
User selects some options, and clicks submit button on form.
The form button click is handled by jQuery code that looks like this:
$(document).ready(function() {
$("#runReport").click(function() {
var report = $("#report").val();
var program = $("#program").val();
var session = $("#session").val();
var students = $("#students").val();
var dataString = 'report=' +report+
'&program=' +program+
'&session=' +session+
'&students=' +students;
$.ajax({
type: "POST",
url: "process_report_request.php",
cache: false,
data: dataString,
success: function(pageContent) {
if (pageContent) {
$("#result_msg").addClass("successMsg")
.text("Report created.");
var windowFeatures = "width=800,menubar=yes,scrollbars=1,resizable=1,status=yes";
// open a new report window
var reportWindow = window.open("", "newReportWindow", windowFeatures);
// add the report data itself returned from the AJAX call
reportWindow.document.write(pageContent);
reportWindow.document.close();
}
else {
$("#result_msg").addClass("failedMsg")
.text("Report creation failed.");
}
}
}); // end ajax call
// return false from click function to prevent normal submit handling
return false;
}); // end click call
}); // end ready call
This code performs an AJAX call to a PHP file (process_report_request.php) that creates the page content for the new window. This content is taken from a database and HTML. In the PHP file I want to include another javascript file in the head with javascript used in the new window. I am trying to include it as follows
<script src="/folder1/folder2/folder3/pageControl.js" type="text/javascript"></script>
Changed path folder names to protect the innocent :)
The pageControl.js file is actually in the same folder as the jQuery code file and the php file, but I am trying the full path just to be safe. I am also able to access the js file using the URL in the browser, and I can successfully include it in a static html test page using the script src tag.
After the javascript file is included in the php file, I have a call to one of its functions as follows (echo from php):
echo '<script type="text/javascript" language="javascript">writePageControls();</script>';
So, once the php file sends all the page content back to the AJAX call, then the new window is opened, and the returned content is written to it by the jQuery code above.
The writePageControls line is where I get the error "Error: Object expected" when I run the page. However, since the JavaScript works fine in both the static HTML page and when included "inline" in the PHP file, it is leading me to think this is a path issue of some kind.
Again, no matter what I try, my calls to the functions in the pageControls.js file do not work. If I put the contents of the pageControl.js file in the php file between script tags and change nothing else, it works as expected.
Based on what some of you have already said, I am wondering if the path resolution to the newly opened window is not correct. But I don't understand why because I am using the full path. Also to confuse matters even more, my linked stylesheet works just fine from the PHP file.
Apologies for how long this is, but if anyone has the time to look at this further, I would greatly appreciate it. I am stumped. I am a novice when it comes to a lot of this, so if there is just a better way to do this and avoid this problem, I am all ears (or eyes I suppose...)
I have also had problems with a similar issue to this, and this was a real headache. The following approach may not be elegant, but it worked for me.
Make sure that your php file, just outputs what you want in your
body
Add jquery to the window head dynamically
Add any external script files to the window head dynamically
use jQuery html on the window's document to call html() with your loaded content on the body, so that scripts are evaluated.
For example, in your ajax success:
success: function(pageContent) {
var windowFeatures = "width=800,menubar=yes,scrollbars=1,resizable=1,status=yes";
var reportWindow = window.open("", "newReportWindow", windowFeatures);
// boilerplate
var boilerplate = "<html><head></head><body></body></html>";
reportWindow.document.write(boilerplate);
var head = reportWindow.document.getElementsByTagName("head")[0];
var jquery = reportWindow.document.createElement("script");
jquery.type = "text/javascript";
jquery.src = "http://code.jquery.com/jquery-1.7.min.js";
head.appendChild(jquery);
var js = reportWindow.document.createElement("script");
js.type = "text/javascript";
js.src = "/folder1/folder2/folder3/pageControl.js";
js.onload= function() {
reportWindow.$("body").html(pageContent);
};
head.appendChild(js);
reportWindow.document.close();
}
Good luck!
It probably isn't looking where you think it is looking to grab your javascript file.
Try a server-relative format like this:
<script src="/some/path/to/pageControl.js"></script>
If that still isn't working, verify that you can type the url to your script file into your browser and get it to download.
Make sure that you have that within either <head> or <body> of the HTML page. Also, I'd double check the path to the .js file. You could do that by pasting "pageControl.js" at the root of your web address.
Things to look for:
Use Firebug (NET tab) to check if the js file is loaded with status 200. Also check in the Console tab for any javascript errors.
Are you using HTML5 offline. If you do, maybe it serves a cached version that doesn't include your <script> tag.
View the page source and make sure it includes the script tag.
Change the source attribute to absolute path: <script src="http://www.example.com/js/pageControl.js" type="text/javascript"></script>
Visit http://www.example.com/js/pageControl.js and make sure it shows correctly.
Try to place the <script> right after the <head> so that it loads first.
This is all I could think of.
You can dynamically load script by creating the element and then append it to head or other element:
reportWindow.document.write(pageContent);
var script = document.createElement('script');
script.src = 'pageControl.js';
script.type = 'text/javascript';
reportWindow.document.getElementsByTagName('head')[0].appendChild(script);
reportWindow.document.close();
Have you tried using the jquery $("#target_div").load(...)
This also executes JS inside the output...
Read this doc to find out how to use it :
http://api.jquery.com/load/
To me it sounds like you're expecting an unloaded script to work.
Try taking a look here: http://ensure.codeplex.com/SourceControl/changeset/view/9070#201379
This is a bit of javascript that ensures that the script is loaded properly before access is attempted. You can use this either as lazy loading (loading javascript files only when required), or, as I interpret your problem, loading a script based on the result of ajax calls.
What's probably happening is, you're echoing a string via an ajax callback, not inserting an element. External scripts require a second GET call to load their contents, which isn't happening - only the first call happened. So, when the first call includes the inline code, the DOM doesn't have to make an additional GET request to fetch the contents. If the DOM doesn't see the script, the DOM won't execute it, which means it's just some random tag.
There's a very fast way to find out. In Chrome (or Firefox with the Firebug plugin installed), check the console > scripts dropdown to see all the loaded scripts. If it's not listed, it's not loaded and the script tag you see in the markup is otherwise inert.
Since it's probably just a string as far as PHP cares, you could create it as PHP DOM object and insert it properly (although this could be laborious). Instead, maybe place it at the very end of the page, just before the closing body tags. (This is the preferred position for js anyway - dead last, after all the other elements on the page have loaded and are available to the DOM.)
HTH :)

Categories