Javascript/JQuery - Running Code Dynamically Some Time After Page Load - php

I am having trouble with running some javascript code, the code is:
<script type="text/javascript">
function hidesolutions()
{
$('.optiondiv').hide();
}
hidesolutions()
</script>
The flow is:
HTML page loads
User clicks a button
Javascript function runs & Calls a PHP script that outputs data to the page
Javascript function finishes
PHP script finishes
The PHP script outputs a div with class "optiondiv" that I want to hide as soon as the PHP is done. I cannot hide it in the javascript that runs when the button is clicked as this finishes before the PHP is done.
Essentially I'm trying to insert the above script into the HTML at some random point in time, but obviously this means it does not run, so I've tried echoing it out in the PHP - does not work and I've tried putting it in the javascript, but unfortunately the javascript finishes before the PHP does and does not find anything to hide.
EDITED to make clearer as per comments.

I'm assuming you're using ajax to pull in your data from the php file. You'll need to call this function in the success callback of your ajax request.

Related

jQuery AJAX vs PHP in HTML attribute

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.

Trigger jquery function after php form submitted (not ajax)

I have a form submit via php and after submitted which mean data inserted to the db and
I want to trigger a jquery function automatically and the function contain the inserted data.
Problem I facing is during the page load, the jquery.js file has not load yet and I can't call
the jquery function.
Another problem, If after the page loaded, how can I automatic trigger the jquery function?
Add the script tag that includes the jQuery in head before your use jQuery and put your javascript just before ending body tag. Putting the code in document.ready will ensure the availability of DOM elements to your script and trigger the javascript as the page is ready after being accessed.
$(document).ready(function(){
//your code here
})
try this
this will trigger on form submit
$('.formclass').on('submit',function(){
// this will redirect to the page you want
window.location = "http://www.yoururl.com";
});
but if you want to trigger a function when the form is submitted and the new page is loaded then #Adil suggestion is what you need ..
but you have to be sure that this page only shows after the form submit if for example after submitting the form you redirect to the home page and you used the document.ready then this will run when the page is loaded regardless of the form submit-ion , so every time i go to the main page it will fire ...

about combine ajax ,php and javascript

I have a main html file and I am using ajax to call another php file in same directory.
Inside that php file, I call some external Javascript functions. But my javascripts functions are not working. Is it not possible?
I see generated source in my web browser and it is normal. If i call those functions with using php file (without using ajax), then my functions are working and the generated source same as the previous case. Please help me.
In my html file I am using ajax as follows:
xmlhttp.open("GET","end_location_drop_down.php?q="+str,true);
xmlhttp.send();
in my php file functions as follow,
<?php
echo '<script type="text/javascript" src="../js/pointing.js"></script>'; //external script
$btn8="'btn8'";
$q=$_GET["q"];
echo '<script type="text/javascript">
nextpoint('.$at_id.'); //$at_id mean a variable,nextpoint() is my java script function
</script>';
?>
in my JavaScript function have some image swapping functions.they can call by nextpoint(). But it didn't work.
Javascript functions are executed only when you load the page directly in a browser, as your browser is the one who interprets and executes the javascript code. However when the javascript code is in a different page and that page is being called through AJAX, there is no browser to execute the javascript code before the ajax response is sent back to you. SO it won't work.
Javascript must be executed in browser, so you must insert that script in DOM to current document. Try to insert result of ajax call to DOM.

Php - run another page and go

i've a question, in a php script I've to do some things, and I need to be really fust, but in the script I've to do some database controlls, too, so, I would know if it's possible run an external php page, that do something, but without wait for its results.
Thanks
(P.S.: sorry for my english)
You'll want to look at using Javascript and Ajax. This allows you to run a php script from within a page asynchronously.
If you use a javascript library, such as jQuery then you can use something similar to this:
$.get('my_script.php', function(response) {
// This code is ran when the page has been loaded
// `response` is the content you get back from script
});
For more information have a look at the jQuery documentation on the $.get function.
You can use Ajax to do that, it let another script run in background.
Yes, you can use Ajax for this. Using Ajax you can run php code in the background, however if user navigates to another page, the execution of that php code will be terminated. The simplest way to get started with Ajax is to use a library like jQuery. See http://www.devirtuoso.com/2009/07/beginners-guide-to-using-ajax-with-jquery/
Hope this helps
--EDIT--
This how you can achieve calling exec(php script.php) using Ajax and PHP
home.php (here you are using Ajax to run exec.php)
<!--include the jQuery library -->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.js"></script>
<script type="text/javascript">
function runInBackground(){
$.get('exec.php', function(data) {
});
}
</script>
exec.php
<?php
exec(php script.php);
?>

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