Question

I've studied up on the Oracle documentation and examples and still can't get this to work.

I have a Java Applet that is simply trying to send a text field to a PHP script via POST, using URLConnection and OutputStreamWriter. The Java side seems to work fine, no exceptions are thrown, but PHP is not showing any output on my page. I am a PHP noob so please bear with me on that part.

Here is the relevant Java portion:

    try {
            URL url = new URL("myphpfile.php");
            URLConnection con = url.openConnection();
            con.setDoOutput(true);
            out = new OutputStreamWriter(con.getOutputStream());
            String outstring = "field1=" + field1 + "&field2=" + field2;
            out.write(outstring);

            out.close(); 

    }
    catch (Exception e) {
        System.out.println("HTTPConnection error: " + e);
        return;
    }

and here is the relevant PHP code:

    <?php
            $field1= $_POST['field1'];
            $field2= $_POST['field2'];
            print "<table><tr><th>Column1</th><th>Column2</th></tr><tr><td>" .
                 $field1 . "</td><td>" . $field2 . "</td></tr></table>";
    ?>

All I see are the table headers Column1 and Column2 (let's just keep these names generic for testing purposes). What am I doing wrong? Do I need to tell my PHP script to check when my Java code does the write?

Was it helpful?

Solution 2

Well, I feel like I've tried every possible thing that can be tried with PHP, so I eventually went with JSObject. Now THAT was easy.

Working Java code:

JSObject window = JSObject.getWindow(this);

// invoke JavaScript function
String result = "<table><tr><th>Column1</th><th>Column2</th></tr><tr><td>" 
+ field1 + "</td><td>" + field2 + "</td></tr></table>";
window.call("writeResult", new Object[] {result});

Relevant working Javascript:

function writeResult(result) {
        var resultElem =
            document.getElementById("anHTMLtagID");
        resultElem.innerHTML = result;
    }

From here I can even send the results from Javascript to PHP via Ajax to do database-related actions. Yay!

OTHER TIPS

Not USE $_POST ,USE $_REQUEST OR $_GET

WHERE TO SET $field1 and $field2 in your php script?

Try URL url = new URL("myphpfile.php?field1=" + field1 + "&field2=" + field2);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top