I'm trying to load or better reload a DIV with content from an included php file. so the file is included in the webadmin.php from the location webadmin/pages.php. Then i alter some data in the DB through serializing.
Now I would like to reload the pages.php from the callback of the serialize POST with load();. This all works fine up until the moment the data is supposed to be displayed in the div - i believe its because the php file is loaded from a different location, so the include paths for the DB Connection etc are probably wrong...
Should I really write an extra PHP File for jquery or is there a way to tell jquery where to load it from?
Its the first time I'm doing this - so bear with me for a moment on this one... Thanks!
I guess it wont be much use, but heres the load code:
$("#right").load("webadmin/pages.php");
You can use Firebug, then open Net tab to see if there are response from the AJAX call.
I never use $.load(), instead I use $.get or $.post:
$.get("webadmin/pages.php",
{ nbRandom: Math.random() },
function(data){
$("#right").html(data);
});
nbRandom is just to prevent caching in IE. Choose a name that not used in the pages.php
Make sure no error in Firebug, and the page structure is a valid HTML/XHTML. Some bug is occurred because imbalanced tags in page.
Is the load() function returning anything?
The script is not location dependent in terms of the DB includes, etc. Those includes are only relative to the PHP script itself. The ajax function is running client side, so imagine that it's calling the URL relative to the same place as the original page. So if your page is:
http://example.com/stuff/page.php
and you are calling the script at:
webadmin/pages.php
Then the URL the ajax load method is using is:
http://example.com/stuff/webadmin/pages.php
This is the exact same as if you are putting in an href for a link or a src for an image. If the script actually is at:
http://example.com/webadmin/pages.php
Then you need to change the load URL accordingly (same as if an image were in a lower directory) like so:
$("#right").load("../webadmin/pages.php");
$.get("webadmin/pages.php",
{ nbRandom: Math.random() },
function(data) { $("#right").html(data); }
);
this code is including php file with using jquery
Related
;-) I have a hit a brick wall. Today I have met Ajax for the first time in my life. And I understand, that my question can seem very stupid. But I need your help.
I have a php file (for ex. index.php), it has an include (function.php). In the file function.php I have a function (for example function Jokes(){....}).
I want to use AJAX to load this function in my page. But I don't know how to do this... :-(
I have found some easy solutions (I use Jquery load function), but it's not what I want, because I have to use a separate file.
$('#jokes').load('jokes.php');
But I need something like:
$('#jokes').load('function.php','jokes()');
Any help or ideas? It will be appreciated.
P.S: Sorry for my bad English...))
What you can do is make one AJAX file, e.g. ajaxfunctions.php where you divide the functions.
$('#jokes').load("ajax.php", { 'function': 'jokes' } );
In your PHP file ajax.php you can do this:
<?php
include 'function.php';
if (isset ($_POST['function']) && $_POST['function'] == 'jokes')
{
echo jokes ();
}
?>
Does this help you?
The browser (and thus Ajax) can only make HTTP requests to the server.
It cannot execute specific functions.
You would have to write server side code that would recognise a particular URL (e.g. to a script that only calls that function, or a script that decides which function to run based on the query string) and execute a particular function in response to a request to it.
No, it's impossible to do it this way. You must make a request to a url. You can't just invoke a specific function from a php file.
Build a url wrapper for the function you need.
Don't do that.
Ajax is used to send or retrieve data, but what you are trying to do is to load a Javascript function defined in a PHP file (isn't it?).
Instead, just define your Javascript function in a JS file and load it via a script (or, if it should be loaded dynamically, you may use an AMD loader like require.js)
If you want to load a PHP function in JS, then it's not possible. You may call that function and fetch its result instead, though.
It doesn't work like this.
$('#jokes').load('jokes.php');
does an http request to jokes.php. If you want to execute a specific function, you can use a parameter, like this:
$('#jokes').load('jokes.php?func=jokes');
From your php script, get 'func' and execute the proper function.
...
function jokes() {
return 'some output';
}
...
$func='';
if (!empty($_REQUEST['func'])) {
$func=$_REQUEST['func'];
}
if ($func=='jokes') {
echo jokes();
}
You don't need AJAX for this. You want to put the Jokes() function in a JavaScript file, maybe called Jokes.js, include it in index.php and then call it normally in a JavaScript block in index.php.
I am trying to get the image links from 9gag (what also works) and when I click on a button the image changes to the next one. The basic problem is that it works only once. I can then switch between the 1st and the 2nd image, though. This should be pretty simple, but I ´ve got no clue where the error is, so thanks in advance to anyone bothering to look at this.
<?php
$index = 0
$html = file_get_contents("http://www.9gag.com");
preg_match_all( '|http://d24w6bsrhbeh9d\.cloudfront\.net/photo/.+?\.jpg|', $html, $gags);
?>
<script>
function nextImg(){
<?php $index++;?>
pic.src='<?php echo $gags[0][$index];?>';
}
function prevImg(){
<?php $index--;?>
pic.src='<?php echo $gags[0][$index];?>';
}
</script>
You can't increment your PHP variables after the page has loaded. You are trying to increment them client-side with JavaScript. You are going to need to call that PHP using AJAX if you want to do this without refreshing the page, and even then you'll want to increment a javascript variable to keep track of where you are.
EDIT: I went a little nuts creating an ajax routine using PHP and JavaScript, specifically the jQuery library, which you will need to link to for this to work. You may also need to modify parts of the script to work with what you're trying to accomplish, but this certainly is a guide for running your ajax app as you're hoping to.
Start by making a PHP file with this script:
<?php
// Set content header to json
header('Content-Type: application/json');
// Get the index from the AJAX
$index = $_GET['index'];
// Grab file contents & parse
$html = file_get_contents("http://www.9gag.com");
preg_match_all( '|http://d24w6bsrhbeh9d\.cloudfront\.net/photo/.+?\.jpg|', $html, $gags);
// Send filename back to AJAX script as JSON
echo json_encode(array($gags[0][$index]));
?>
Then, in your HTML, include this jQuery to complete AJAX calls to your PHP script, and update the DOM with the data from the PHP script.
<script>
$(function() {
'use strict';
// Initiate index variable
var index = 0;
// Load initial image
loadImage(index);
// Add click event to a button with class of next-btn
$('.next-btn').click(function(e) {
e.preventDefault();
// Increment index to get next image
index++;
// Run AJAX function to retrieve image
loadImage(index);
});
// Add click event to a button with class prev-btn
$('.prev-btn').click(function(e) {
e.preventDefault();
// Decrement the index if it isn't 0
if (index > 0) {
index--;
}
// Run AJAX function to retrieve image
loadImage(index);
});
});
function loadImage(index) {
'use strict';
$.ajax({
type: 'GET',
url: 'your-php-script.php', // Filepath to your PHP script
data: 'index='+index, // Index is passed through GET request
dataType: 'json', // Return JSON
success: function (data) { // If the php script succeeds
// Change img with class of pic's src
// to the filename retrieved from php
$('.pic').attr('src', data[0]);
}
});
}
</script>
Configuring this for your needs will require some serious PHP and jQuery/JavaScript knowledge, as some debugging will likely be needed. Good luck!
EDIT 2:
I uploaded the working (tested, it works) source files to my website if you want to download. Please accept answer and let me know you grabbed the files...
http://www.wedgewebdesign.com/files/ajax-image-loader.zip
#Eric basically has it right but didn't really go into detail if you aren't familiar with the model...
PHP is a server side language in that it does all its processing on the web host server and once it is complete sends a static result back to the user. This means, whatever you see after the page is loaded within PHP is there to stay, unless you do one of two things:
1) Send a new request -- You provide different parameters, the page re-executes its logic and returns a new result to the user
2) Execute some form of clientside Javascript. Javascript is different from PHP in that it executes on the client (not the server) so you don't necessarily have to send responses back to the server unless you need more information. Javascript and PHP can be combined to create AJAX calls which allow the client to make asynchronous calls to the webserver for more data without reloading the entire page. The Javascript handles re-drawing the new information or updating the page which can appear seamless to the user.
What you therefore need is one of those two options. Either you provide 'next'/'previous' links to the user and the page is loaded differently each time or you create an AJAX call that fetches the url of the next image and then loads it.
Try assigning a variable to $gags[0][$index]. Something like
$imgsrc = $gags[0][$index];
and then
pic.src='<?php echo $imgsrc; ?>';
I am using php and an apache server. My application gathers data from the user, put's it in a database, then uses PDFLib to display the formatted data back to the user as a pdf. My problem is, I would like the pdf to display as a new page, this works. But, I also have a blank page left up with the URL containing the variables used to display the pdf. I would like this page to show a different summary page, in HTML, without the variables in the URL, but I don't know how to do that. In the code that follows, I am going to the summary page if the medical flag is false. What I would like is to go to BOTH pages if the medical flag is true. Is this possible?
if($medical_flag) {
header("Location: {$_SERVER['PHP_SELF']}/./index.php?step=wc_pdf&id={$event_id}");
} else {
header("Location: {$_SERVER['PHP_SELF']}?step=success&id={$event_id}");
}
exit;
OK, I understand how this is impossible, but I still haven't figured out how to solve the problem. I thought I could toss the opening of the PDF back at jQuery with something like this:
jQuery(document).ready(function ()
{
function display_pdf_page(data, textStatus) {
var current_record = data || {};
//somehow display the pdf now
}
function show_pdf(eventid){
jQuery.getJSON(
'./inc/get_current_record_data_json.php',
{'id': eventid},
display_pdf_page
);
}
...
});
Then after I process the data in php "call" the above using:
echo '<script type="text/javascript">'
, 'show_pdf($event_id);'
, '</script>';
But that doesn't work either, php doesn't know where to find show_pdf. My lack of understanding of client/server side events is killing me here. Call be obtuse... I don't get it.
This solution will not work as designed.
First, if you want to hide the data, you should switch to POST rather than GET. This way, the data is included in the HTTP payload instead of the URI.
Secondly, you should either include a hidden iframe for javascript to access the page for which generate the PDF. On successful execution of the AJAX call (or whatever method you use), you can then redirect the page to your desired destination.
As suggested by sixeightzero, POST should be used instead of GET in such cases.
However, maybe you could accomplish the desired effect with a big iframe spaning the window (100% width and height)?
I have js file where i need to call the function defined in the php file to calculate the value and then move on to next step. Is this possible to do? I am not able to access the function of the php file from my script. Also is there some way around to include php file in a html page without changing the extention .html
No, you cannot do that. PHP and Javascript do not execute in the same environment, nor at the same time.
PHP executes on YOUR web server (server-side) before the page is served up.
Javascript is executed on the CLIENT's browser after the page has been served up.
To call a PHP function from javascript, you will need to make an AJAX call. This sends a value from the client side to the server side where it can be processed, and the response is then sent back to the client.
Try JQuery Ajax
It´s easy to use.
$.ajax({
type: "POST",
url: "yourphpfile.php",
data: { values: "100"}
}).done(function( msg ) {
console.log("php file called"+msg);
});
replace yourphpfile.php with your php file and your php file gets executed
If you want to access server-side resources (filesystem writing, database), you'd need to use AJAX to switch back and forth.
If you're just more familiair with PHP, you could take a look at http://phpjs.org/, which reimplements many PHP functions in Javascript.
PHP files are files that are executed by the server.
"I have js file where i need to call the function defined in the php file to calculate the value." Browsers cannot run php functions, you need server to do that.
"Also is there some way around to include php file in a html page without changing the extention .html" If you do that your php code will not run, because server use the extensions to know if a file needs execution or not.
To call a PHP function from javascript, you will need AJAX. The value is send from the client to the server where it is processed, and the response is then sent back to the client.
I want to use jQuery to include some PHP at a certain point in the page. When jQuery finds the class #site-index .sitetopic I want to append the content from a PHP file called images.php.
I presume I can use include or file_get_contents
Something like:
OnLoad.find('#site-index .sitetopic')
InsertPHP
You can't insert server side code on the client.
By the time Jquery would execute, the server is already done processing the page.
You could however use an iframe that you use jquery to add, or even use jquery's .load function http://api.jquery.com/load/
You cannot load and execute PHP code on the client side, but you can load the output of images.php.
I'm not sure if you want to place the output where #site-index .sitetopic is, or somewhere else:
// loads the output of images.php into the elements with class sitetopic
$('#site-index .sitetopic').load('images.php');
You can't insert server side code on client side - however you could call the script images.php which would do what you want to achieve.
Use jQuery's get(or post) function:
http://api.jquery.com/jQuery.get/
This allows you to send some variables to your server side script wich in turn returns some html or a variable you can use in your javascript.
As said before, you just can't.
And I assume it was for the sake of speed but don't worry, PHP doesn't include files with an HTTP request but it fetches them from the HDD, so your page won't load slower.