Hi i would like to use ajax in my website where all requests pass are loaded in index.php (i use htacess for rewriting urls) so when i use ajax i always reload the current page and then use if(expressio) to check if the user has called a function with ajax but this cause that all the page is reloaded each time i use ajax.
I was wondering if there is a method to call a specific php method/function or property in the current page with ajax without reloading all the page.
I'm using the jquery library for ajax
If someone knows some other ways is ok!
A main use of ajax is that you call asynchronously something. Most often functions-methods that are called with ajax do rely on the same php file (if not then it's okay) with other stuff that you do not need to call asynchronously.
For example you have a method that is called via ajax to autocomplete a text field (like google search) in a file that there is other stuff you don't want to execute too.
If you are under some mvc then you have controller check this out and make sure that only the requested method is called (I've done it successfully). So it is easier controlled under an mvc, all things are in classes...
If not under mvc then I guess you have to implement something like controller in order to call only the methods you like. However there is a conition that should be espected, no code should be found out of classes cause it would be executed on "include", it would go like this:
file ajax handler
1.Check if an ajax call
2.if check false return;
3.if true then get the name of the class file
4. call the desired method (or methods, you have an execution flow predefined during to your needs)
So it can be done. It is important not to execute code that is not supposed to be executed since then undesired results (or errors) would occur.
in ajax i use the current url as the action of the request but this
cause the re-load of the whole page.
Since you have your own mvc it could go like this index.php/rt=request/action where request=the name of the controller (which in the end is a class), and action is the name of the action (which in the end is a method inside the class-controller you are requesting) for example
mysite.com/rt=user/create
My point is that you don't care what the current url is, all you care is to call the right method(=action) of the right class(=controller).
The login class is istantiater in all pages because it check if a user
is logged;
I don't really understand this (when you say pages you mean php files?), whatever it is I suggest (if haven't done already) to follow the single entry point (no need to do this for ajax calls) where every request hits only to index.php like I showed you above. Then a few lines of code on the very top can do the login check.
And a last thing what kind of ajax is this that reloads all the page, this an example how I do ajax for autocomplete in a text field:
put this as it is in head-script-javascript to make the connection
var request = false;
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
if (!request)
alert("Error initializing XMLHttpRequest!");
or even better you can have it in a separate file and include it wherever you need it
then I use a function to do the asunchronous call, what I am doing is similar to your needs because I too get data from html and pass it to php (read the comments) and then execute sql.
function getMatch()
{
//get the form values, I have one value here, you get as need as many as you need
var str = document.getElementById("categ_name").value ;
var url = "internal.php";//php file to execute
//now pass the html form parameters to php
//do you see here controller is defined, it is named asynch
//then see the action (method of controller class) it is called getMatch
//then see how I pass the html form data with str, it is the string to match
//comcateg is the mysql table to get the match
var params = "rt=asynch/getMatch&data=" + (str)+"&from=comcateg";
request.open("POST", url, true);//use post for connect harder to attack, lots of data transfer
//Some http headers must be set along with any POST request.
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
request.setRequestHeader("Content-length", params.length);
request.setRequestHeader("Connection", "close");
request.onreadystatechange = updatePage;
request.send(params);
}////////////////////
Then when the answear will be back this function will be called because we defined so above in the code
function updatePage() {
if (request.readyState == 4) {
if (request.status == 200)
{
//test
var r=request.responseText.split("$$");
alert(r[1]);
}
else{
//alert("status is " + request.status);
}
}
}
I think now you can do it without problem, remeber whatever would be echoed by php even errors all of them will come back in the request.responseText. This is a tutorial among others about mvc that I like, https://sites.google.com/site/mhabipi/php-reading-material/superMVC.htm?attredirects=0&d=1 it's written by Kevin Waterson but sadly phpro.org does not work anymore.
Related
Maybe the title doesn't make sense...
When loading page.php, it should return content A. But if a user clicks a button 'B' on page.php, that triggers JS which makes an AJAX call to page.php?param=B.
page.php has php code that's supposed to load content B if it gets requested with ?param=B . In the network tab, it shows that a request was indeed sent to page.php?param=B but the code doesn't run.
What essentially I want to do is display data on page.php sorted based on url param.
I hope this makes sense lol.
page.php
<script>
function sort(selection) {
//idk y this doesn't work
let xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "/test.php?sortby=" + selection);
xmlhttp.send();
}
</script>
<input type="button" onclick=sort(this.value) value="A"></input>
<?php
if (empty($_GET)) {
//query DB for content, don't sort, display
} else if (isset($_GET['sortby'])) {
if ($_GET['sortby'] === 'A') { //query db for content, sort by A and display }
if ($_GET['sortby'] === 'B') { //query db for content, sort by B and display }
?>
Oh one last note, when I manually enter page.php?sortby=A in the url bar and hit enter, php runs correctly, but when AJAX calls for that same url, php doesn't run.
The point of an Ajax request is that the browser does not navigate to a new page, but that the response is handled by JavaScript instead.
You aren't handling the response at all.
You need to wait for the response to load and then do something with it.
function loadHandler() {
const data = this.response; // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/response
console.log(data);
}
xmlhttp.addEventListener("load", loadHandler);
In the above example I'm just logging it to the console. Normally you would want to insert it into the HTML document.
Generally you wouldn't want to return entire HTML documents from an Ajax request. It is typical to return some data in a JSON structure and use that to update the page.
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 have just started into OO PHP and have created my first class. As it is, it works, but I want to tidy things up a bit.
Right now elements in the class call an ajax function that is declared in the head of the document.
I don't want the class to be dependent on a proper head, so to keep it self contained, I moved the script functions into the class file. I could not find information on whether this is a no-no, so if it is, I want to know "Why is putting javascript/ajax in a PHP class bad form?" If, however, it is an acceptable practice, I have a trickier question.
The AJAX calls a PHP page who's results will then fill in more of the class object on the page. But, I figure the class would be better if it didn't rely on external php files either. So, I moved the files into functions on the class file. Here's the tricky bit.
How do I get the AJAX to get the results from a function located on the same file as the AJAX call instead of an external page?
Here is my AJAX code so far. var url currently is the path to one of two possible PHP pages instead of the desired internal php functions. var dest is where in the class object the results end up.
function createRequestObject() {
var ro;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
ro = new ActiveXObject("Microsoft.XMLHTTP");
}else{
ro = new XMLHttpRequest();
}
return ro;
}
var http = createRequestObject();
function sndReq(url,dest) {
http.open('get',url);
http.onreadystatechange = function () {
if (http.readyState == 4) {
if (http.status == 200) {
var responce = http.responseText;
document.getElementById(dest).innerHTML = responce;
}
}
};
http.send(null);
}
What you're asking for sounds like xml-rpc or json-rcp. It lets you dynamically execute server-side code and get the results.
Example javascript rpc library: http://barracudaserver.com/doc/WebServices/JRpcDoc.html
However, I think that simply passing parameters is what you want. The simplest way is to pass get parameters in the url
http://www.site.com/ajax.php?cmd=find_user&user_id=12
then in php check for those parameters in the global $_GET variable
if(isset($_GET["cmd"]) && $_GET["cmd"] == "find_user"){
$user_id = $_GET["user_id"];
//some server-side stuff
echo results;
}
I've researched and played around a fair bit, but I am stumped. Essentially I want to setup my site so that it can detect if a user is 'logged in' and thereby change the way it looks: removing the "Sign In" link and replacing it with a "Sign Out" link, and so forth.
For testing purposes I started my index.html page with:
<?php
session_start();
$_SESSION["username"]="javaman";
?>
Next, I call my setup function from within the jquery document.ready:
$(document).ready(function() {
setup_page();
};
The setup function looks like:
function setup_page()
{
var username = get_user();
//check for error
var index = username.indexOf("error");
//if not an error
if(username.length > 0 && index == -1)
{
//do the jquery calls to hide/show links
}
}
And that get_user function looks like:
function get_user()
{
var result;
$.post("./session.php", {action : "get", key : "username", value : "val"}, function(data){
result = data;
});
return result;
}
The session.php is a simple app that takes in 3 post values and hopefully spits out the proper result, the problem I am running into is that the js result variable is often undefined, especially so when I debug via the IE dev toolbar. FF seems ok though. Am I using the callback in the correct way? I've tried putting alert() functions everywhere to figure out where the code is screwing up, but that doesn't help either as often the alert's say the result is undefined. Meanwhile, it seems like the get_user calls the post function but the stack immediately returns and never gets to the return statement until AFTER the get_user has returned a value of.. undefined. I believe I am misunderstanding the code flow here. I am used to C where logically one function follows another. In that vein I am interpreting the callback to essentially be like:
int i = callback_function(post("some data"));
So in my mind the post completes it's action and then calls another function or at least performs another action and then that completes and then the get_user can return it's value.
Or is the order of operation: post, get_user, callback?
...confused in Seattle
Internet Explorer does not natively support indexOf on arrays. Use jQuery's $.inArray() instead:
var index = $.inArray("error", username);
Keep in mind that AJAX stands for Asynchronous Javascript and XML. So the callback fires as soon as a response comes, but the rest of execution goes on. If you want to lock the execution until AJAX-request will be completed, use
$.ajaxSetup({async:false});
before AJAX call.
Users of my website will, ideally, be sending a few hundred posts to a db server over the course of about an hour (basically its an online-experiment). The experiment is implemented in js, so I'm trying to use an XMLHttpRequest object to post the data the script collects.
The thing I'm uncertain about is how to use the POST parameter. I want to set about 8 different key/value pairs to the $_POST variable so it can be accessible to a .php page for processing before sent to the db server. I'm not interested in retrieving any information from the server itself, only sending it (which is why, and I'm not sure whether it's the correct approach, I'm setting the readyState conditional to '1'/open).
Here's the script I'm working with at the moment:
function postData(dataList) {
var xmlhttp = new XMLHttpRequest();
var processingUrl = "process_exercise_data.php";
var POSTBody = "";
POSTBody+="block_type="+encodeURIComponent(dataList[0]);
POSTBody+="&block_number="+encodeURIComponent(dataList[1]);
POSTBody+="&trial_type="+encodeURIComponent(dataList[2]);
POSTBody+="&trial_number="+encodeURIComponent(dataList[3]);
POSTBody+="&input_value="+encodeURIComponent(dataList[4]);
POSTBody+="&output_value="+encodeURIComponent(dataList[5]);
POSTBody+="&prediction_value="+encodeURIComponent(dataList[6]);
POSTBody+="&error="+encodeURIComponent(dataList[7]);
xmlhttp.open("POST",processingUrl,true);
if (xmlhttp.readyState==4) {
xmlhttp.send(POSTBody);
}
}
The main goal is to send the key/value pairs to the .php page using POST while remaining on the current page(simple AJAX request, if I'm not mistaken). Any comments or suggestions are very appreciated!
Remember, all I'm trying to accomplish is having the user, when he/she acts in a certain way under a certain condition (outside of the scope of this function), to call this function and POST this data to the server. A server response text isn't needed.
EDIT:
Now my question is this: Will I still be able to access the $_POST array in at the processing php page? Here's an example:
$block_type = $_POST['block.type'];
You don't want to set request headers. What you want is to send request body along. And the body should be like
'block_type='+encodeURIComponent(dataList[0])+'&block_number='+encodeURIComponent(dataList[1])
etc. Guess you got the idea. Body is what you pass to the send() method of XMLHTTPRequest object.
Consider using jQuery, it will make your task so much easier. Using the jQuery.post method you only have to provide the data hash, you don't have to worry about serialization, correct escaping or readyState.
You must call send before readyState will change.
Replace
xmlhttp.open("POST",processingUrl,true);
if (xmlhttp.readyState=4) {
xmlhttp.send(POSTBody);
}
with
xmlhttp.open("POST", processingUrl, false);
xmlhttp.send(POSTBody);
If you want to handle a response, add define xmlhttp.onreadystatechange:
xmlhttp.open("POST", processingUrl, false);
xmlhttp.onreadystatechange = function () {
if (this.readyState === 4) {
// handle response
}
};
xmlhttp.send(POSTBody);
Edit: I would also like to mention that = is not the JavaScript equality operator, it's the assignment operator. Use === for equality checking and == for type-converting equality checking.