0

I am coming from asp.net and in asp.net you have the onclick event that is triggered when you press the button.. in that event you could write your code that you want to be executed...

But in PHP there is no such mechanism...

Whats the best practice to initiate a link and pass it url variables..

Do I put a javascript function in the onclick that will do the work for me (go to the server and execute the code..

<script type="text/javascript>
  function Javascript()
  {
    //what do you do here..how can you make the javascript go back to ther server.. 
    // or initialize a link say.. http://home.com?newVariable=2
  }
</script>
4
  • 6
    onclick is purely a client-side thing, and PHP is purely-serverside. I wouldn't complain that an apple doesn't support oranges. ASP itself doesn't have onclick either, when you get right down to it. It just auto-generates some JS for you to make it LOOK like it does. Commented Oct 12, 2011 at 16:57
  • You can use onclick to call a function that performs an Ajax POST to a PHP file and retrieve some new data from the server... (but all depends on what do you whant to do exactly) Commented Oct 12, 2011 at 17:01
  • how do I achieve the similar effect. I want the button press to send me to the server or redirect to the same url to pass some variables.. I want the user to press on a button and I want the button to deliver him to the same or different page Commented Oct 12, 2011 at 17:01
  • Ok, thats the answer from Jasper!! Take a look. Commented Oct 12, 2011 at 17:03

2 Answers 2

1

If you want to put query string variables in your JavaScript code here's an example:

<script type="text/javascript>
document.getElementById('some_link_id').addEventListener('click', function () {
    window.location = 'http://home.com?newVariable=<?php echo $_GET['newVariable']; ?>';
}, false);
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

look at the bright side, now you get to learn more about JavaScript event handling :)
0

As I understand:

You need to use ajax to make your event onclick communicates with the server (your file.php).

The simplest is to use jQuery functions .click and .ajax :

$('#myButton').click(function(){
    $.ajax({
        type: "POST",
        url: "file.php"
        data: "newVariable = 2"
        success: function (msg) {
            alert("Data Saved:" + msg);
        }
    })
});

In file.php :

<?php
    $newVariable = $_POST['newVariable']; //$newVariable = 2
?>

1 Comment

Make sure you are including the jQuery library before using the code in the above example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.