How to turn following PHP process into AJAX process?

On my website I give users an option to subscribe to blog authors. Right now it is a php process and requires page refresh each time user clicks "SUBSCRIBE" or "UNSUBSCRIBE" button. I was thinking that it is a time to make this process sort of AJAX based, so when users click "SUBSCRIBE" or "UNSUBSCRIBE" buttons there would be no page refresh, but their subscription arrays would be updated. therefore buttons will change respectively e.g. if user clicks "SUBSCRIBE" button it will change to "UNSUBSCRIBE" and backwards. The problem is that I never used AJAX before and I can't find useful information to achieve this specific task, because there is a lot of it. So could anyone suggest how to make this process sort of AJAX, so no page refresh takes place? If possible jQuery based solution would be great.


HTML & PHP for Buttons

//SUBSCRIBE Button
<?php if (($isLogedIN) && ($canSubscribe) && (!$isBlogOwner)) { ?>
<form id="subscribeform" name="subscribeform" method="post" action="blog.php?id=<?php echo $id;?>">
   <input type="submit" name="subscribe" value="Subscribe"/>
</form>
<?php } ?>

//UNSUBSCRIBE Button
<?php if (($isLogedIn) && ($canUnSubscribe) && (!$isBlogOwner)) { ?>
<form id ="unsubscribeform" name="unsubscribeform" method="post" action="blog.php?id=<?php echo $id;?>">
   <input type="submit" name="unsubscribe" value="Unsubscribe" />
</form>
<?php } ?>

PHP to update database records

//Subscribe
if (isset $_POST['subscribe'])){
   //First Update Visitors Subscription Array
   if($subscription_array != ""){
      $subscription_array = "$subscription_array,$blogauthid";
   } else {
      $subscription_array = "$blogauthid";}
   $updateSubscription_array = mysql_query("UPDATE members SET subs='$subscription_array' WHERE id='$reader'") or die (mysql_error());
   //Then Update blog writers subscribers array
   $subArray7 = mysql_query("SELECT subscribers FROM members WHERE id='$blogauthid' LIMIT1");
   while($subrow7=mysql_fetch_array($subArray7)) {subscription_array7 =  $subrow7["subscribers"];}
   if ($subscription_array7 !="") {
       $subscription_array7 = "$subscription_array7,$reader";
   } else {
   $updateSubscription_array7 = mysql_query("UPDATE members SET subscribers='$subscription_array' WHERE id='$blogauthid'") or die (mysql_error());
   header("location: blog.php?id=$blogid");exit();



//Unsubscribe
if (isset($_POST['unsubscribe'])){
   //First Update visitors subscription array
   foreach ($subscription_array2 as $key => $value) {
            if ($value == $blogauthid)
                unset($subscription_array2[$key]);
            }
}
$newSubArray = implode(",", $subscription_array2);
$updateSubscription_array = mysql_query("UPDATE members SET subs='$newSubArray' WHERE id='$reader'") or die (mysql_error());
//Than update blog writers subscription array
$subArray9 = mysql_query("SELECT subscribers FROM members WHERE id='$blogauthid' LIMIT 1");
while($subrow9=mysql_fetch_array($subArray9)) {subscriber_array9 = $subrow9["subscribers"];}
$subscriber_array9b = explode(",", $subscriber_array9);
foreach ($subscribe_array9b as $key9 => $value9) {
         if ($value9 == $reader) {
             unset($subscriber_array9b[$key9]);
         }
}
$newSubArray9 = implode(",", $subscriber_array9b);
$updateblogSubsArray = mysql_query("UPDATE members SET subscribers='$newSubArray9' WHERE id='$blogauthid'") or die (mysql_error());
header ("location: blog.php?id=$blogid");exit();

Answers


This could be optimized a little, but it's functionality is more clear at each step and it should work. This is Jquery $.post, as requested.

You only need one form element:

<form id="subscribeform" name="subscribeform" method="post" action="blog.php?id=<?php echo $id;?>">
   <input type="submit" name="subscribe" value="Subscribe"/>
</form>

At the bottom of your document, just before the closing body tag, link the jquery library, followed by the script:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() { 
    $('#subscribeform input:submit').click(function() {
        // $.post is the jquery shorthand method for $.ajax - it always uses POST 
        $.post(
                // url
                'blog.php?id=<?=$id?>',
                // serialized form data to POST
                $('#subscribeform').serialize(),
                // success callback toggles form value
                function(data) {
                    if ($('#subscribeform input:submit').val() == 'Subscribe') {
                        $('#subscribeform input:submit').
                           attr('name','Unsubscribe').val('Unsubscribe');
                    }
                    else {
                        $('#subscribeform input:submit').
                           attr('name','Subscribe').val('Subscribe');
                    }
                }
         );
    });
});


Basically you want to have a JavaScript function like this:

function subscribe(id)
{
if (window.XMLHttpRequest)
  {// code for real browsers
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for abominations
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.status==200 && xmlhttp.readyState==4)
    {
    document.getElementById("subscribeStatus").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","blog.php?id="+id,true);
xmlhttp.send();
}

Call it and pass it the variable (id) you want with a button like this on the frontend.

<input type="button" name="click" value="Subscribe" onmousedown="subscribe(document.getElementById('id').value);">

Embed the user's ID as a hidden form field with id = "id" (or whatever).

Then on the PHP side (blog.php) just handle it with $_GET instead of $_POST. And duplicate it for unsubscribe or find a way to work it together using a switch (or if) statement.

Hope that helps.


Need Your Help

With jQuery UI autocomplete results dependant upon other input values

jquery jquery-ui cakephp jquery-ui-autocomplete

I am using the autocomplete feature of jQuery UI to create a passive database of associative values. I have three inputs: Lens Type, Lens Design and Lens Material.

How to check the facebook application permission for specific user through graph api in rails?

facebook facebook-graph-api ruby-on-rails-3.1 koala

I want to check whether the user has give publish_stream permission to my application or not. If not want to get publish_stream permission.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.