What is the best way to just run a PHP script when the user clicks a button? It sends nothing back to the user whatsoever! (The PHP script only sends a PostgreSQL query.)
I have only found ways of returning data. I only want to run it.
You're looking for AJAX (asynchronous javascript). Just have a javascript function call the target script and either don't return anything OR don't do anything with the return value. Alternately, you could simply have form that submits to a hidden iframe on the page.
This is the best I could come up with. Hope it was what you were looking for.
/* Function that we create to handle backwards compatiblity to browsers.
What it does is to try diffrent types of XMLHttpRequests. */
function getXMLHttp() {
var xmlHttp;
try {
//Firefox, Opera, Safari, Chrome, IE7+
xmlHttp = new XMLHttpRequest();
} catch (e) {
try {
//Internet Explorer 6
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
//Internet Explorer 5
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
return false;
}
}
}
return xmlHttp;
}
// Here, we send the request
function send() {
/* We say the variable xmlHttp is the function
where we try the diffrent XMLHttpRequests*/
var xmlHttp = getXMLHttp();
// We open your PHP file...
xmlHttp.open("POST", "yourphpfile.php", true);
// ...and send it to the server
xmlHttp.send();
}
A little brief
Since you're not getting anything back to the user, you use POST and not GET. It sends a request to the server to the file. And as you said in your question, something was sent to a PostgreSQL server. However, that PHP script is runned on your hosting server that supports PHP.
The most basic way to do this would be an html form.
<form action="somePHPfile.php" method="post">
<input type="button" value="Run somePHPfile.php" />
</form>
You could also do what Ben D suggested, but that's not the most basic way of doing this. Using jquery:
$("#YOURbuttonID").click(function(){
$.post("yourPHPfile.php", function(){
alert("Success!");
});
});
You will need to use Ajax and then you can update a div etc so user knows if the query was executed properly or not.
Related
I need to post a single form to 2 different URLs. One is just a logging script so the response doesn't need to be passed back to the user.
Unfortunately in this instance I can't just post to a single PHP script and turn around and re-POST it using Curl. This has to be done in the user's browser.
This is some Javascript I'm using right now but it's failing at a seemingly random rate for almost all the major browsers (but works 95%+ of the time). The rest of the form does require Javascript to function so I know the problem isn't just that some users have Javascript turned off.
function makePOSTRequest(url, parameters) {
http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}
http_request.open('POST', url, true);
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Content-length", parameters.length);
http_request.setRequestHeader("Connection", "close");
http_request.send(parameters);
}
I'm calling that after building the request manually in another function, then calling the submit() function of the form.
Can anyone suggest an alternative that might work better? This seems to be working ~95% of the time but that 5% failure rate is a killer... Thanks!
Try using a framework that supports error checking any try repeating the request on failure.
JavaScript frameworks like jQuery support sending post requests and can be used to check if a request was successful. Also your code will be easier to write and maintain.
I've trying to send some infromation to a php file and display the result returned. First of all I'm not receiving any results from php file i.e. no value in xmlhttp.responseText. Instead of responseText, I tried putting 'something else' which made no difference. But when i comment out //if (xmlhttp.readyState==4 && xmlhttp.status==200), the result briefly appears.
What have I done wrong?
Ajax code looks like this:
var div = 'display';
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
writeBack (div, xmlhttp.responseText+'something else', 'red');
}
}
xmlhttp.open("POST","update_profile2.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("rr="+id);
Php code:
..
if(isset($_POST['rr']))
{
die('connection made');
}
..
Every problem I've ever had with AJAX is usually caused by trying to submit an AJAX request using a 'submit' button in a form. If you are doing that, make sure you stop the .submit() .... Also, if you use jQuery, your AJAX code will look sooooo much better :)
As others users say with jquery the code looks much better.
However I am quite sure your problem is with this line:
xmlhttp.open("POST","update_profile2.php",true);
The request above access directly the update_profile2.php and gets back the entire content of the php page, not the output elaborated by the page.
This is way you access the page without asking the web server (with the php engine) to serve it for you. And of course the http call fails so the condition && xmlhttp.status==200 blocks the execution of the next instruction that fills in the div.
use instead:
xmlhttp.open("POST","http://localhost/update_profile2.php",true);
This will send a ajax http request to apache, il will run the php page and returns the answer of the page!
I have written few php files which sit in a server. The output of the php would be as follows:
172.xx.xx.xx/myphpfile.php?arg="abc"
Output
{
status: "ok",
result: "asdsdf"
}
My requirement is to call this php api (172.xx.xx.xx/myphpfile.php?arg="abc") from my javascript, parse the output and draw a chart in the page. To summarize the following are my doubts.
How to call a remote php file from javascript?
How to capture the output of a php file in a javascript?
Remote PHP? Due to the same origin policy you have to write the PHP so it emits JSONP. (That link also explains how to use it from JS).
Alternatively, and with more limited browser support, use CORS with XHR
First of all, javascript is client-side and php is server-side. The web servers outputs text to your browser and it doesn't know about server techniques used.
For fetching and manipulating the data, have a look at jQuery and jQuery ajax
Both can easily be done with javascript (and even easier with jQuery). If your resulting page is in JSON format (which it appears to be), you can simply do..
$.getJSON('172.xx.xx.xx/myphpfile.php', 'arg=abc', function(obj){
alert(obj.status);
});
More info: http://api.jquery.com/jQuery.getJSON/
If the API file is not on your server
If the API is not on the same domain as your page with the JS, you will need to create your own PHP page to read the remote file, and dump its contents locally to the domain.
getJson.php
die(file_get_contents('172.xx.xx.xx/myphpfile.php?arg='.$_REQUEST['arg']));
JS
$.getJSON('gtJson.php', 'arg=abc', function(obj){
alert(obj.status);
});
You have to use Ajax.
Avoid the classic method, prefer using a framework like jQuery or ExtJS, it will be easier and cross-browser.
http://api.jquery.com/jQuery.ajax/
http://docs.sencha.com/ext-js/4-0/#!/api/Ext.Ajax
Here is the code which I use
<script type="text/javascript">
//Global Variables
var xmlHttpFP;
if (window.ActiveXObject)
{
xmlHttpFP = new ActiveXObject("Microsoft.XMLHTTP");
}//End if
else
{
xmlHttpFP = new XMLHttpRequest();
}//End else
//Function To fetch Data From Server
function LoadFPSummary()
{
xmlHttpFP.open("GET","172.xx.xx.xx/myphpfile.php?arg='abc'");
xmlHttpFP.send();
document.getElementById("response").innerHTML = xmlHttpFP.responseText;
}
xmlHttpFP.send(null);
</script>
AJAX is the tool you need.
Read more here.
You have to move AJAX technology
<html>
<head>
<script type="text/javascript">
var xmlhttp;
function loadXMLDoc(url,cfunc)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function myFunction()
{
loadXMLDoc("172.xx.xx.xx/myphpfile.php?arg=abc",function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
});
}
</script>
</head>
<body>
<div id="myDiv"><h2>Get from PHP</h2></div>
<button type="button" onclick="myFunction()">Load</button>
</body>
</html>
I've been working out the best way to bridge javascript to get data from php with Ajax.
And all while trying to keep the lines of code to a minimum and with greatest speed.
I've come up with a way to pass AJAX a value by Object so it can be altered as if it was passed by reference and then send it back. But so far, I can only do this synchronous as the data will not be available until AJAX completes.
Point is:
I've been looking for an easy way access all of my PHP content with javascript.
Build a simple javascript(GetSomePHPstuff) API if you will.
As I am a novice at web programming, I would love to hear some input and feedback on this.
This is what I have come up with.
In this example, I am sending a text value from html through javascript to ajax to php and php sends it back to ajax back to javascript back to my html page.
Here is our simple HTML type file.
TEST.html
<script language="javascript" src="ajax.js"></script>
<input type="text" id="text"/>
<input type="button" value="Return Text"
onClick="alert(ajaxReturnText(document.getElementById('text').value));"/>
Here is the ajax/javascript file.
AJAX.js
function ReturnText(input, output){
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
output.value = xmlhttp.responseText;
}
}
xmlhttp.open("GET","php.php?text="+input,false);
xmlhttp.send();
}
function ajaxReturnText(input){
var output = new Object();
ReturnText(input, output);
return output.value
}
And here is the PHP file
php.php
<?php
function ReturnText($text){
return $text;
}
if($text = $_GET["text"]){
echo ReturnText($text);
die();
}
?>
This cannot work asynchronously this way. You have to understand that this line:
output.value = xmlhttp.responseText;
is going to be executed after ajaxReturnText() is done if you define it asynchronously. If you defined synchronously then ajaxreturtext() will not proceed until the request is done. To me your problem is that the code must respect the foundamental rules, in your case this is that you have to remember to define what to do after ajax inside this the "update function here:
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
output.value = xmlhttp.responseText;
/*define what to do next here*/
}
So you never call code to be executed asynch directly but insted you call it from inside the proper function, see complete code:
<html>
<head>
<script type="text/javascript">
/*to be called synch*/
function ReturnText(input){
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
/*here define what to be called asynch*/
ajaxReturnText(xmlhttp.responseText);
}
}
xmlhttp.open("GET","php.php?text="+input,true);
xmlhttp.send();
}
/*to be called asynch*/
function ajaxReturnText(input){
var output = new Object();
output.value =input;
alert(output.value);
document.getElementById('test').innerHTML=
"This is the value of the object: "+input;
}
</script>
</head>
<body>
<div id="test"></div>
<input type="text" id="text"/>
<input type="button" value="Return Text"
onClick="ReturnText(document.getElementById('text').value);"/>
</body>
</html>
If you want to experience more I have a class for it: see here
You can receive server-generated events asynchronously in realtime without any problem, I did it long time ago before any AJAX. Now this way called Comet. I used frames and script techniques. Now it's better to do with ajax, but here some problems you have to solve.
You can receive data in realtime using .onreadystatechange callback with .readyState==3.
This callback generated every time when new data come from server. You need to remember last .responseText size and read new data from this point to end, then store new size.
Problem number one:
IE generate exception when you try to read .responseText before event with .readyState==4. So server part must drop connection after every event to make readyState readable and force client recreate it again (see 'long polling'). If browser is not IE you don't need to recreate connection every time. But here we face problem number too.
Problem number two:
.responseText size. It can be very big if connection used for long time. So you need to implement (events or bytes send) counter on server or client and recreate connection by counter overflow.
One more problem - timeouts. You need to disable timeout on server (see set_time_limit()) and send something insignificant (space forexample) to browser when you have no events to prevent browser timeout.
Usually you need two channels to server: upload and download. You have upload channel with jQuery or another framework but I don't sure about download. I afraid you can't use readyState==3 technique with jQuery. May be APE Framework can do it?
Ok, this is my second post, and PLEASE accept that I am a complete newbie, willing to learn, spending many hours trauling various sites for answers, and I've almost got to where I need to be (at least for this bit).
I have a web page which has a nubmer of javascript functions that work together to generate a Google Map with various lines etc. using the google maps API.
I also have a MySQL Database with some information in.
I have created a PHP script to dynamically generate a dropdown box with information from the database. (and that bit seems to work fine) - http://www.bournvilleconservatives.com/temp/select.php
What I now need to do is get that dropdown box to appear in the HTML / Javascript page that I already have, so that when a user selects something from the list, it calls a javascript function with the value selected.
I'm told I need to use AJAX to pull the box in, and use innerhtml to display it, but I really have no idea how, and could do with an example of something similar to help me on my way.
I would put the PHP in the html page, but that page is actually wrapped up in a Joomla! wrapper, so its all rather complicated.
Thanks in advance.
jQuery solution
If you are willing to use jQuery, it will help you a lot with accessing the DOM, making Ajax calls and stuff. Let me give you a solution in jQuery:
First, put a div into HTML (this will store your select box):
<div id="i_want_my_select_here"></div>
Then put this code in the end of you HTML before </body>.
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#i_want_my_select_here').load('/temp/select.php');
});
</script>
In the first script tag, we include the jQuery library from Google's CDN. In the second, we write our Javascript/jQuery code. The .load() function makes it easy to make an Ajax call and load the response into an HTML element.
You can see this is much easier than all that code in my other answer :).
If you're using prototype, you can use either Ajax.Request or Ajax.Updater, tho you should have a parent div with either to replace/insert into.
Example w/ Request:
new Ajax.Request('select.php', {
method: 'post',
onSuccess: function(r) {
var select = r.responseText;
$('parent_div').update(select);
}
});
Example w/ Updater:
new Ajax.Request('parent_div', 'select.php', { method: 'post' });
First, the Ajax example (taken from tizag.com and modified), Javascript code comes:
var ajaxRequest; // The variable that we will put an XMLHTTPRequest object in
//We try to create an XMLHTTPRequest object,
//it is the object that lets us use Ajax
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
// and do stuff with it (this function will only run,
// when the data arrives back from the server!)
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){ //if request is successful
//HERE COMES THE DOM INSERTION
}
}
//We call the PHP file
ajaxRequest.open("GET", "/temp/select.php", true);
ajaxRequest.send(null);
What basically happened is that through XMLHTTPRequest we called your PHP file. When the response (PHP file's output) comes, ajaxRequest.onreadystatechange will run instantly. So whatever we want to do with the data received, we have to do it in the place I've written //HERE COMES THE DOM INSERTION.
We want to insert the output into the HTML. To take the easiest route, first create a div/span in your HTML at the exact place you want your select to appear (it's very important to define the ID).
<div id="i_want_my_select_here"></div>
Then again, here comes the Javascript that replaces //HERE COMES THE DOM INSERTION.
//use the id to get Javascript access to the DIV
var div=document.getElementById('i_want_my_select_here');
//put the output of PHP into the div
div.innerHTML=ajaxRequest.responseText;