Viewed   135 times

I want to execute some php code on submit button click without refreshing/reloading my page. Is it possible? also i have javascript function on page load that's why i don't want to refresh my page. thanks in advance.

<?php
if(isset($_POST["search"]))
{
$show = "SELECT * FROM data";
$rs = mysql_query($show) or die(mysql_error());
 $add_to_textbox = "<input type='button' name='btn' value='add' />";
#****results in Grid****
    echo "<table width='360px' border='1' cellpadding='2'>";
    $rowID=1;
while($row = mysql_fetch_array($rs))
{
    echo "<tr>";
    echo "<td width='130px' id='name.$rowID.'>$row[Name]</td>";
    echo "<td width='230px' id='link.$rowID.'><a href = '$row[Link]'>$row[Link]</a></td>";
    echo "<td width='130px' onclick='Display($rowID);'>$add_to_textbox</td>";
    echo "</tr>";
    $rowID++;
}
    echo "</table>";
#**********************
mysql_free_result($rs);
}
?>

<script type="text/javascript">
function Display(rowID){
    var linkVal = document.getElementById('link'+rowID+'').innerHTML.replace(/</?[^>]+(>|$)/g, "n");
    document.getElementById("name").value = document.getElementById('name'+rowID+'').innerHTML;
    document.getElementById("link").value = linkVal; 
    }
</script>

here is my code

 Answers

2

Well, you need to use the javascript / ajax.

Example: on your submit link (a href for exaple), add call-in-to js function submitMe and pass on whatever variables you need

function submitMe() {
    jQuery(function($) {    
        $.ajax( {           
            url : "some_php_page.php?action=getsession",
            type : "GET",
            success : function(data) {
                alert ("works!"); //or use data string to show something else
                }
            });
        });
    }

IF you want to change some content dynamically, it is easy- you just need to create tags, and assign ID to them : <div id="Dynamic"> </div>

Then you load ANYTHING between those two tags using

document.getElementById("Dynamic").innerHTML = "<b>BOOM!</b>";

Meaning that you calling area between two tags and loading something into them. The same way you GET data from that place:

alert(document.getElementById("Dynamic").innerHTML);

Please read this: http://www.tizag.com/javascriptT/javascript-getelementbyid.php

In addition, play and experiment with DOM elements and learn how they interact. It is not hard, just takes some time to grasp all concepts.

Saturday, October 22, 2022
 
dbr
 
dbr
2

Use jQuery + JSON combination to submit a form something like this:

test.php:

<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="jsFile.js"></script>

<form action='_test.php' method='post' class='ajaxform'>
 <input type='text' name='txt' value='Test Text'>
 <input type='submit' value='submit'>
</form>

<div id='testDiv'>Result comes here..</div>

_test.php:

<?php
      $arr = array( 'testDiv' => $_POST['txt'] );
      echo json_encode( $arr );
?>

jsFile.js

jQuery(document).ready(function(){

    jQuery('.ajaxform').submit( function() {

        $.ajax({
            url     : $(this).attr('action'),
            type    : $(this).attr('method'),
            dataType: 'json',
            data    : $(this).serialize(),
            success : function( data ) {
                        for(var id in data) {
                            jQuery('#' + id).html( data[id] );
                        }
                      }
        });

        return false;
    });

});
Monday, September 5, 2022
 
5

Creaet Delete.php File

 include_once'DBConnect.php';
 if(isset($_REQUEST['userid']) && $_REQUEST['userid'])
 {
 $delObj= new DBConnect();
 $delObj->DeleteData($_REQUEST['userid']);
 }

create DBConnect.php File

<?php

class DBConnect
{
function DBConnect()
{
    $link= mysql_connect("localhost","root","")or die("Local Host Error".mysql_error());
    mysql_select_db("mydb");

}

 function viewData()
{

    $query="select * from userinfo";
    $resultset=mysql_query($query) ;

    return $resultset;


}

function DeleteData($userID)
{

    $query="DELETE from userinfo where id=".$userID;

    $resultset=mysql_query($query) ;

}


}

?>

Create index.php file

<script>
function deletedata(id)
{
    var xmlhttp;    
    if (id=="")
      {
          document.getElementById("Display").innerHTML="";
          return;
      }
    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)
          {
            window.location.reload()

          }
    }
        xmlhttp.open("GET","delete.php?userid="+id,true);
        xmlhttp.send();

}
</script>    




<?php include 'DBConnect.php';
$ViewObj= new DBConnect();
$ResultSet=$ViewObj->viewData();?> // I have created one function which will get all the data from the database if you don't want to do this just call deletedata() function onClick event and pass Record ID as agrument which you want to delete on DELETE button.
<br /><br /><br />
<span id ="Display">
<table align="center" border="1">
<tr>
      <th>Name</th>
      <th>operation</th>
</tr>
<?php
while($row= mysql_fetch_array($ResultSet))
{?>


<tr>
    <td><input type="checkbox"></td>
    <td><?php echo $row[1];?></td>

    <td align="center"><a href="#" onclick="deletedata('<?php echo $row[0];?>')" style="color:#FF0000"><b>Delete</b></a>

    </td>
</tr>

<?php 


}
?>
</table>

I think this will help you :)

Let me know if you are finding any problem.

Tuesday, November 1, 2022
 
das-g
 
3

You've got the right idea, so here's how to go ahead: the onclick handlers run on the client side, in the browser, so you cannot call a PHP function directly. Instead, you need to add a JavaScript function that (as you mentioned) uses AJAX to call a PHP script and retrieve the data. Using jQuery, you can do something like this:

<script type="text/javascript">
function recp(id) {
  $('#myStyle').load('data.php?id=' + id);
}
</script>

<a href="#" onClick="recp('1')" > One   </a>
<a href="#" onClick="recp('2')" > Two   </a>
<a href="#" onClick="recp('3')" > Three </a>

<div id='myStyle'>
</div>

Then you put your PHP code into a separate file: (I've called it data.php in the above example)

<?php
  require ('myConnect.php');     
  $id = $_GET['id'];
  $results = mysql_query("SELECT para FROM content WHERE  para_ID='$id'");   
  if( mysql_num_rows($results) > 0 )
  {
   $row = mysql_fetch_array( $results );
   echo $row['para'];
  }
?>
Tuesday, November 8, 2022
 
4

Within the on.submit.add(...) callback, you will receive the Event as an argument. The Event object provides a preventDefault() method to prevent or cancel the default action.

It can be used as follows:

querySelector('#myForm').onSubmit.listen((Event e) {
  // ... your code here
  e.preventDefault();
});
Friday, November 11, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :