php ajax and normal page difference - php

is there difference whether when a page called with ajax when called normally?
I mean how i could figure out a page called with ajax or called directly ?

You can add a parameter to the call, for example:
xmlhttp.open("GET","page.php?request=ajax",false);
And then check for it in php:
if($_GET['request'] == 'ajax'){
//this was called by ajax!
}

To distinguish between a normal page load, and an AJAX load ... some might code into the JS a variable to pass to the PHP page that indicates AJAX. This would let you modify output as JSON or whatever you wish to do.
Others use separate php scripts for AJAX.
But yeah, there are many ways to figure this out. More details if you have questions, but these are probably the easiest.
Edit: If you did not see the URL posted as the main comment as possible duplicate. this should answer your question about identifying ajax requests only.
Most well-known Ajax frameworks like
jQuery and mooTools add a specific
header which you can check with PHP:
if (strcasecmp('XMLHttpRequest', $_SERVER['HTTP_X_REQUESTED_WITH']) === 0)
{
// Ajax Request
}

Related

php - interface for and ajax calls

I'm writing a PHP application which uses AJAX to submit forms via POST when required. When javascript is not able to be used, I submit the form via HTML/PHP as per normal.
What I really want to do is return JSON or XML to the AJAX call and I don't want to write all of the form processing logic twice or repeat myself at all really.
I'm trying to determine the best way to write the form processing logic as a single interface which can then be used by both an AJAX call and the PHP script.
I have come up with two options, which both seem like hacks. Hoping I can be given some cleaner/better/more correct solutions or have my two solutions evaluated to determine which one is preferred.
Form: form.php
Processor: process.php
AJAX: JS intercepts submit click in form.php, POSTs to process.php which returns JSON result back to JS. JS updates HTML accordingly using JSON result.
PHP:
Option 1
form.php posts to process.php which outputs HTML if a certain variable is passed with the POST data. e.g.
if ($_POST['output'] == 'html') {
//output as html
} else {
//output JSON
}
Option 2
form.php posts to intermediate.php which will then include('process.php'), catch the JSON output and use the JSON output to display the HTML as required. e.g.
ob_start();
include('process.php');
$json = json_decode(ob_get_contents());
ob_end_clean();
//use json to create HTML to display to waiting user here
Both of these options seem a little hacky. The second seems cleaner (although I never feel like I'm doing something cleanly when I use ob_start) because it doesn't require me to write process.php any differently - which emulates an external web service better - although this is not a concern since process.php is fully under my control.
Thoughts?
Thanks as always,
Aaron
I would choose option 1. Just like in popular frameworks like Yii. The typical workflow is like this one:
if (isAjaxRequest()) {
// Ouput JSON and finish script
die(json_encode($output));
}
else {
// This is not AJAX request, proceed
}
And isAjaxRequest is:
// Taken from Yii framework method
function isAjaxRequest() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
}
You don't need to set certain variable to indicate that the request is via AJAX because browser sends HTTP_X_REQUESTED_WITH header and you just need to check if it's been set.
Maybe something along the lines of option 1?
Just before the ajax script fires, use javascript to change the form variable from HTML to JSON and then the PHP script can capture it right?
If the ajax script fails, it will never change the variable.
You could even use javascript to change the form action to JSON_process.php or something like that
I'd recommend using an MVC framework. In the controller, set all the data you'll need. Then, set up two view templates, one for JSON (which could just do a simple json_encode of the data), and one for HTML. You can then just set the view based on an output parameter as in your Option 1.

Populate PHP variable with AJAX?

Im not sure if this is possible, but at the moment I have a form on my page where users can insert their interests, beneath that form are 3 PHP variables (Which dont currently show at first as there is no value assigned to them).
When a user enters an interest and clicks submit, my AJAX takes over, populates the table and then reloads the page so the Variable now shows as it has a value.
Is it possible to not have to refresh the page, so I can say "if success $var = 'value';"?
I hope this doesnt sound too confusing, thanks
Since you're already using AJAX, why don't you just do the logic using Javascript? If you're using jQuery, have a success callback function execute the code you want.
The problem with sending data from AJAX to PHP is that PHP is a server side language, while AJAX is a client side one. By the time your browser sees the page, the PHP has been entirely executed and returned to you as HTML / CSS / Javascript etc.
No, you can't. By the time the HTML has rendered/displayed in the browser, PHP will most likely have long since finished generating the HTML in the first place. You could round-trip the values through an AJAX handler and then populate the places in your page where the values are displayed, but when why bother round-tripping? Just have the AJAX call fill in the values right then and there.
It is absolutely possible, and quite easy to do. Just make another php script and call it from your form page's javascript (I'm going to assume you're using jQuery):
$('#mysubmit').click(function() {
$.getJSON(
'form_ajax.php', // This is the php file that will be called
{ formVar1: $('#form-var-1').val() }, // Add all your form data here
function(data) {
// This is the function that is called after the php script is
// done executing. The 'data' variable will contain the $data
// array you see in the following php file.
}
);
});
I prefer to use JSON, but other approaches are just as good. Check out the documentation for getJSON() and ajax(). Your php file would look something like this:
<?php
$data = array();
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$data['formVar1'] = $_POST['formVar1'];
}
echo json_encode($data);
?>
Of course, yours would probably do a lot more with the form data. Also, theres plenty of other approaches so go explore for the one the best suits your needs.

Assign Javascript variable to PHP with AJAX

I understand...
the disparity between PHP being server-side and Javascript being client-side.
AJAX can patch this issue.
the XMLHttpRequest object is significant.
However, I still can't work out how to pass the variable between the two languages.
Any assistance would be much appreciated!
EDIT: Thanks for your replies so far, I should clarify that I would like to do this without loading a new page.
You need to send an AJAX request containing the value of the variable in the query string or POST body.
The PHP script at the other end of the URL can read the value from the query string or POST body.
you could use JSON with JS and decode it with php, but as the post above states, it involves ajax.
UPDATE: Tutorial found at link
You should give a more detailed example of what you want to accomplish. But if I understand correctly, you want to use a value from your JavaScript code in your PHP code?
You should try using POST or GET parameters to pass values into PHP. For PHP to be able to do anything, you will have to load a new page.
Lets say you have list.php serving a list of posts. You want to "like" a post. Your JavaScript is on this page. When you click "like", an AJAX POST is sent to like.php with POST parameter id=123.
In like.php, you get the value from the request (using $_POST['id'] or something more appropriate), do your magic (save to db) and echo some result, json_encode(array('success' => true)) for example.
The JavaScript-code that called like.php can then use it's callback to check if the "like" was a success or not and display feedback. The like.php could be any page, you could use list.php if you'd want. I used like.php for clarity.
If this is not at all what you wanted, please provide more information.
If you haven't looked at jQuery framework for javaScript, do it.
If you have a variable called city in JS, you can pass it to the file.php by using
var city = "London";
$.get("file.php", {location:city} );
Which is a HTTP GET request.
In PHP(file.php), you then grab it by using
$city = $_GET['location'];
echo $city; //London

How to query database using javascript?

Another question by a newbie. I have a php variable that queries the database for a value. It is stored in the variable $publish and its value will change (in the database) when a user clicks on a hyperlink.
if ($publish == '') {
Link to publish.html
} else {
Link to edit.html
}
What is happening in the background is i am querying a database table for some data that i stored in the $publish variable. If the $publish is empty, it will add a link for publish.html in a popup. The popup will process a form and will add the data to the database and which means that the $publish is no more empty. What i would like to achieve is that as soon as the form is processed in the popup and a data has been added to the database, the link should change to edit.html. This can happen when the page will re-query the database but it should happen without page refresh.
How can it be donw using javascript, jquery or ajax?? Please assist.
Javascript by itself cannot be used to deal with database. That is done using php (Or the server side language of your choice). Ajax is used to send a request to your php script using javascript which will in turn communicate with the db. And it doesn't require a page refresh.
So what you are trying to do can be easily achieved using ajax. Since you mentioned jquery, you can check out the $.ajax or $.post methods in jquery which make the process even more simple.
You need to process the form using ajax. The ajax request is sent to a php script which will make the necessary changes in the database and send the new link (link to edit.html) in the response. Upon getting the response, just replace the current anchor element with the new one ..
for eg..
$.post(url, formdataobject , function (resp) {
$("a.youra").text('edit').attr('href', resp);
});
url - where the php script is located
formdataobject - a javascript object that will have the form data as key value pairs
the third parameter is an anonymous function also known as callback function since it will be invoked only when the response is received from the server. This is because ajax requests are asynchronous.
Inside the callback function, jquery is used to change the text inside the anchor element to edit and the href attribute is changed to value that came in the response.
$.post means we are using the post method. so the parameters can be accessed as elements of $_POST array in php.
After updating the db, you can simply echo out the new link and it will be received in the response.
Also, there are other formats in which you can get the response for eg. xml, json.
I'll try to leave the technical jargon aside and give a more generic response since I think you might be confused with client-side and server-side scripting.
Think of javascript as a language that can only instruct your WEB BROWSER how to act. Javascript executes after the server has already finished processing your web page.
PHP on the other hand runs on your web server and has the ability to communicate with your database. If you want to get information from your database using javascript, you'll need to have javascript ask PHP to query the database through an AJAX call to a PHP script.
For example, you could have javascript call a script like:
http://www.myserver.com/ajax_function.php?do=queryTheDatabase
In summary: Javascript can't connect to the database but it can ask PHP to do so. I hope that helps.
Let me try, you want to change the link in a page from a pop-up that handles a form processing. Try to give your link a container:
<div id="publish_link">Publish</div>
As for the form submission use Ajax to submit data to the server to do an update and get a response back to change the link to edit or something:
$.post("submit.php", { some_field: "some_value"}, function(response) {
if(response.isPublished)
$('#publish_link', window.opener.document).html('Edit');
});
Basically your publish link is contained in a div with an ID publish_link so you change its content later after data processing without reloading the page. In the pop-up where you would do the form processing it is done using jQuery Ajax POST method to submit the data. Your script then accepts that data, update the database and if successful returns a response. jQuery POST function receives that response and there's a check there if isPublished is true, get the pop-up's opener window (your main window) and update the link to Edit. Just an idea, may not be the best out there.
It cannot be made with javascript, jquery or ajax. only server side script can query a database. with ajax request you can get the script output. ajax requests can be sent either with pure javascript or jquery.
Well, i think i understand your quaestion, but you have to get a starting point, try to understand this:
try to understand what are client variables and server variables.
javascript does not comunicate with database.
you can use javascript to retrieve data to a specific "Object variable".
Using ajax methods of jquery you can post that data do other page, that will execute the
proper actions
you can ;)
at first you must create php file to query database and return something like true or flase and then with file url check the function and get answer
function find_published(folder_id) {
var aj_url = "{{server_path}}/ajax/url"
var list;
$.getJSON(aj_url+"?callback=?&",
function(data) {
//here is your data... true false ... do every thing you want
}
);
};
this app for node.js does mysql queries https://github.com/felixge/node-mysql
You need to use AJAX for this, like .post() or .get() or JSON.

Calling JavaScript with PHP

I want to call a PHP function when pressing on a button, sort of like:
<?php
function output(){
// do something
}
?>
<input type="button" value="Enter" onclick="output()"/>
I tried to make something like:
<input type="button" value="Enter" onclick="test.php?execute=1"/>
where test.php is current page and then by php
<? if(isset(&execute)){ echo "Hello"; } ?>
but it doesn't work.
Since PHP runs on the webserver, and buttons (and JavaScript in this case) appear on the client, you have to make an HTTP request to the server.
The easiest way to do this is to use a form. No JavaScript is required. You can add JavaScript (although it should be layered on top of a working non-JS version). Using JavaScript to make an HTTP request without leaving the page is known as Ajax, and generally achieved with the XMLHttpRequest object. There are various libraries such as YUI and jQuery that can do some of the heavy lifting for you.
I think using an AJAX call would do sort of what you are asking. I don't know PHP very well but you can use the following example, and add another variable with the data you are passing in to the server to indicate which function you want to call on the server. On the server you can add some "IF" statements that will call a certain function based on the name passed in and return the result.
Here is what you could use on in your javascript client using the jQuery library as a helper to do the AJAX call:
<input type="button" value="Enter" onclick="output()"/>
<script type="text/javascript">
function output(){
$.ajax({
type: "POST",
url: "submit_data.php",
data: "username=" + "SomeUser"
+ "&email=" + "someEmail#google.com"
+ "&functionName=" + "theFunction1",
success: function(html){
alert('sucess! Result is:' + html);
}
});
}
</script>
and you can use code such as this to catch the data your javascript is passing in. In this example you would want to call this file name as "submit_data.php" to match the javascript above:
<?php
// Variables
$Username = $_POST['username'];
$Email = $_POST['email'];
$FunctionName = $_POST['functionName'];
//Add code here to choose what function to call and echo the result
// If $FunctionName equals 'theFunction1' then execute theFunction1
// If $FunctionName equals 'theFunction2' then execute theFunction2
echo "You called A Page!";
?>
Here I am doing nothing with the "username" and "email" simply grabbing it and storing them into holding variables. But you can easily add extra functionality here, such as checking for a name of a function that you want to run.
PHP is server side and javascript is client side. So I'm not sure if that is really what you want to be doing??
Perhaps you could explain why you want to specifically call a php function?
I googled PHP function from button and found this question on webdeveloper.com
It doesn't use Javascript.
This is PHP you're talking about, not ASP.NET. In PHP, there is no such thing as a button click event. PHP runs entirely on the server and has absolutely no knowledge of client-side events.
Your first try won't work because the PHP code only runs when the page first loads. It does not run when you call a JavaScript function. Your second example won't work because JavaScript and PHP can't talk directly to eachother like that. Trying to directly call a PHP function from JavaScript just doens't make sense. Remember, PHP only runs on the server. By the time you get to the point where JavaScript can run, the PHP code has long since completed its work.
If you want to do something when a button is clicked, you have to explicitly make a request back to the server. You can do this by just POSTing the form as CTphpnwb suggested. Just be aware that this will reload the page and you will have to manually save and restore the page state, e.g. repopulate input boxes. There is no built-in magic that will do this for you.
Alternatively, you can get all AJAXy and do the POST in JavaScript. However, you will have to write the JavaScript to send the request and process the response, and write the server-side PHP code to handle the request. This gets a little awkward to do in a single page.
From : http://www.dreamincode.net/forums/showtopic72353.htm
You cannot directly invoke a PHP function from Javascript this way :
PHP code is executed on the server
HTML / Javascript are interpreted on the client-side.
One the HTML page has been generated and sent to the client (the browser), there is nothing more PHP can do.
One solution would be to use an Ajax request :
Your onclick event would call a Javascript function
This Javascript function would launch an Ajax request : a request sent to the server
The server would then execute some PHP code
And, then, return the result of that execution to the client
And you'd be able to get that result in your Javascript code, and act depending on what was returned by the server.
There are plenty of solutions to do an Ajax request :
You can re-invent the wheel ; not that complex, I should say -- but see the next point
If already using a Javascript framework, like jQuery, Prototype, ... Those provide classes/methods/functions to do Ajax requests
Googling a bit will get you lots of tutorials/examples, about that ;-)

Categories