PHP return partial script - php

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

Related

run php function, display the response, and start another php function

Run php script, display the response, and start another php script and then display it
I have two functions in php I would like to display the response of the first function in order to make loading less long
Exemple Pseudo-code
Function hello1()
{
echo 'hello1';
[...]
}
Show response and run another function
Function hello2()
{
echo 'hello2'
[...]
}
all php methods will be executed before rendering the html page. May you think about Javascript event handling or an method "injections" with Ajax request to a code behind file which is php based.
Regards,
Tobo

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.

Why do you echo results of php functions to get them back to jQuery

I call a php function using jquery
$.get("tableau_trusted.php",{username:$("#username").val(),password:$("#password").val()},function(data){
alert(data);
});
Why do I return the result from the php file like this:
echo "http://$server/trusted/$ticket/$view_url?$params";
Instead of:
return "http://$server/trusted/$ticket/$view_url?$params";
I know I should use POST with the password, I'm just playing around for now.
Thanks!
Because Javascript and PHP can only communicate via HTTP. The PHP script receives an HTTP request, which is just a bunch of text. It sends back a reply, which is also just a bunch of text. The way to output this bunch of text is by echoing it to the standard output. An AJAX request/response is exactly the same as any other normal webpage you'd write using PHP.

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.

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