php - interface for and ajax calls - php

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.

Related

PHP return partial script

I am creating a php (let's call it pageX.php) file that produces some html. The html has a button that when you press it, I would like to send an AJAX request.
To avoid having multiple files, I want to send the AJAX request to the same file. (pageX.php)
I don't want the AJAX response to return the entire php generated response that it would have with a normal GET request to pageX.php. So I am looking for a php method to simply stop executing and return what it currently has.
I understand I can do this with a big if statement, but I don't like wrapping the bottom part of my code with all the braces. So I am almost looking for the equivelent of a "break" statement for php that will simply return the current php generated html.
Is that possible?
Send your ajax request to pageX.php?ajax=y now you can do this
<?php
if(!empty($_GET['ajax'])) {
//return ajax data
exit;
}
?>
//your Normal html code here

passing variable value from javascript to php

I am working on a project where I used ajax for asynchronous DB access.
I store the value in JavaScript variable as follows..
var content=xmlhttp.responseText;
now what I wanted is to pass this value to the php module on same page..
Please suggest me..its urgent
You'll have to make a separate AJAX request to another script to achieve this. PHP is server-sided and therefore cannot directly interact with the client.
You should handle the data (which you are assigning to content) in PHP because, as the other answers here tell you, PHP is server-side and JavaScript is on the client. If you are getting this data from a page you control, instead of var content = xhr.responseText; just modify the data BEFORE you send it. For example, if you are making an AJAX call to a process.php file on your server to get the data you are otherwise assigning to content in JavaScript, be sure to handle the data in process.php PRIOR to echo()'ing the data (which you are then storing inside content on the client):
In process.php:
// below is the normal server script which you are storing in content on the client
// echo $result;
// instead, we are going to operate on the data first:
return doSomething($result);
Then on the client:
var newContent = xhr.responseText;
And the newContent variable will contain the data you previously wished to modify with PHP. If you DO NOT have control of the server script which you are calling with AJAX, then as mentioned here already, you will need to send a SECOND AJAX call to the server with your PHP, and use $_GET or $_POST to retrieve that content data and then play with it there.
Am unclear about your need to pass value from javascript to php.
But I can give you,
A non-recommended but working approach towards your problem:
You said, you are making an Ajax call at first. While processing the corresponding server side php function, Store the response value (value of xmlhttp.responseText) into a $_SESSION variable. Finally Reload the page (using location.reload()) inside the ajax response handler function.
And a recommended approach towards your problem:
You might have added some if-else control-flow structures in the php code and expecting to execute them after getting the ajax response value (sadly you cannot do that). So if you do have some logic like that, then convert those if-else conditions to corresponding Javascript code. May be a javascript function and call that function by passing the ajax response value to it. This new function will use your ajax response value and make changes in some parts of your webpage by applying necessary logic.

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.

php ajax and normal page difference

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
}

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.

Categories