Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP click event handlers

Tags:

php

I'm new to PHP programming and I wanted to know that is it possible to handle PHP events as we do in ASP.NET

I mean I've got a img and I want to perform some task on click event of this img.

I know how to do it in ASP.NET but please help me in context of PHP

Thanks, GURU

like image 909
necixy Avatar asked Dec 13 '22 23:12

necixy


1 Answers

PHP itself does not handle client-side events. And PHP paradigm slightly differs from ASP.NET where client and server-side scripds bound together in the same page of code. On client-side, use javascript to handle onClick event, and in event-handler code issue AJAX call to your designated PHP page to send back a response.

<script type="text/javascript">
var http = false;

if(navigator.appName == "Microsoft Internet Explorer") {
  http = new ActiveXObject("Microsoft.XMLHTTP");
} else {
  http = new XMLHttpRequest();
} 

function click() {
  http.open("GET", "test.php?name=" + document.getElementById("name").value, true);
  http.onreadystatechange=function() {
    if(http.readyState == 4) {
      document.getElementById('foo').innerHTML = http.responseText;
    }
      }
  http.send(null);
    }
</script>
name:<input id="name" type="text">
<p><button onclick="click()">Click me</button></p>

<div id="foo">
  Hell
</div>

And this is a test.php code:

<?php
function validate($name) {
  if($name == '') {
    return '';
  }

 if(strlen($name) < 3) {
   return "<span id=\"warn\">Username too short</span>\n";
}

switch($name) {
case 'bob':
case 'jim':
case 'joe':
case 'carol':
  return "<span id=\"warn\">Username already taken</span>\n";
  }

  return "<span id=\"notice\">Username ok!</span>\n";
}

echo validate(trim($_GET['name']));
?>
like image 136
alemjerus Avatar answered Dec 30 '22 23:12

alemjerus