Domanda

PHP, Javascript, HTML

I have a PHP function stored in page2.php

function pot()
{
does something;
returns a value;
}

in another page (page1.php), i have a link and a textbox

<a href="#" onclick="pot();">when i click, call the function pot</a>

Calling pot() is simple, but I am not able to store the value returned by pot() into a textbox. This is my textbox

<input type="text" id="field" name="field" value="value the function returns">

Any suggestions??

È stato utile?

Soluzione

Try to set the returned value to the textbox using javascript/jquery like

function pot()
{
// your code
document.getElementById("field").value="returnedvalue";  // set the result value to element with id as field
}

This will set the value of the textbox when you click on the link

<a href="#" onclick="pot();">when i click, call the function pot</a>

Note: Make sure to include the function in the file, where you are calling the function. Otherwise it won't work. If needed you can create a js file with the function (if you want to use the same function in many places) and call the js file in your php file with

<script src="jsfilename.js">

Altri suggerimenti

by JavaScript

function pot()
{
document.getElementById("field").value="returnedvalue";
}

by jQuery

function pot()
{
$("#field").val(returnedvalue);
}

Besides using ajax (the preffered method) you can also use a hidden iframe on your page.

Your html would be:

<iframe src="about:blank" id="myhiddeniframe"></iframe>
<input type="text" id="field" name="field" value="">
<div onclick="pot();">when i click, call the function pot</div>

Javascript:

function pot(){
    document.getElementsById('myhiddeniframe').src="page2.php";
    }

And your php-function:

function pot(){
    //get the $value
    <script>
    var ret='<?php echo rawurlencode($value) ?>';
    window.top.window.document.getElementsById('field').value=decodeURIComponent(ret);
    <script>
}

[edit] added the rawurlencode() and decodeURIComponen() to make sure your value doesn't screw up the javascript :-)

I think you're having problem with the js? I'm assuming that you require page2.php on page 1.. in function pot you can add this..

function pot()
{
    document.getElementById('field').value = 'what ever value you want';
}

That is a native javascript, but there is a javascript library called jQuery that will helps you a lot regarding on that. It seems that you are new in Javascript, you can visit this http://jquery.com/ to help you

Have external .js file and add it in page1.php

script.js

function pot()
{
does something;
returns a value;
}

In page1.php

<script src="script.js" language="javascript" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function()
{
var t=pot();
$("#field").text(t);
});
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top