0

I have this AJAX function that is supposed to pass on data to the php code which is then supposed to enter it into the data into the database which is happening but AJAX is really not working the way it should.

             <?php         
     session_start();
    include_once("../engine/database.php");
    if (isset($_POST["name"],$_POST["password"]) ) {      
      $uname  = htmlspecialchars(mysql_real_escape_string($_POST["name"]) );
      $passwd = htmlspecialchars(mysql_real_escape_string($_POST["password"]) );
      $query = "SELECT * FROM users WHERE username ='".$uname."' AND password='".$passwd."' LIMIT 1";
      $query= mysql_query($query);
      if(mysql_num_rows($query) == 1) {        
        $_SESSION['admin'] = "Welcome to the Admin Panel {$_POST['name']} ";
        $_SESSION['onOff'] = 'on';
       ?>        
     <!DOCTYPE html>
      <html>
      <head>
          <meta charset="utf-8">
          <meta http-equiv="X-UA-Compatible" content="IE=edge">
          <link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.3.0/pure-min.css">
          <script type="text/javascript" src="//tinymce.cachefly.net/4.0/tinymce.min.js"></script> 
          <script>
          tinymce.init({
              selector: "textarea#postCont",
              plugins: [
                  "advlist autolink lists link image charmap print preview anchor",
                  "searchreplace visualblocks code fullscreen",
                  "insertdatetime media table contextmenu paste"
              ],
              toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image"
          });
        </script>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript" charset="utf-8" async defer></script>

          <title>Admin Panel</title>     
      </head>
      <body>        
        <div class="pure-g-r" style="letter-spacing:0em; padding-left:2em; padding-right:2em;">   
           <div class="pure-u-5-10">                                
              <form class="pure-form pure-form-stacked" action='../engine/engine.php' method='post'>
                <fieldset>         
                  <legend><?php echo  $_SESSION['admin']; ?></legend>
                  <div style="margin:0 auto;">                      
                      <input type='text' name='postTitle' class="pure-input-1" placeholder='Article Title'/>                                
                  </div>
                  <textarea  class="pure-input-1" name='postDes' name='postDes' cols='102' placeholder='Article Summary'></textarea>                  
                  <textarea  id="postCont" name='postCont' cols='60' rows='10'></textarea>                  
                  <br />
                  <button type="submit" name="blogsubmit" class="pure-button pure-input-1 pure-button-primary">Submit</button>                  
                </fieldset>                
              </form>
          </div>
          <div class="pure-u-1-10">

          </div>
          <div class="pure-u-4-10">                             
                  <h2 style="margin:0 auto;">Posted articles</h2>
                  <dl>
                      <dt>How to create a Text editor</dt>
                      <dd><a href=""><small><a href="">Edit</a></small> | <small><a href=""> Delete</a></small></a>
                      <dt>How to create a Text editor</dt>
                      <dd><a href=""><small><a href="">Edit</a></small> | <small><a href="">Delete</a></small></a>                                 
                  </dl>                                
          </div>                  
        </div>
        <script type="text/javascript">
                function submit() {
                      var xhr = new XMLHttpRequest();
                      try {
                        xhr = new new ActiveXObject("Msxml2.XMLHTTP");
                      }
                      catch (e) {
                        try {
                          xhr = new ActiveXObject("Microsoft.XMLHTTP");
                        }
                        catch (e) {
                          alert(" Please upgrade your broswer");  
                          return false;
                        }
                      }

                     xhr.onreadystatechange = function () {
                          if (xhr.readyState === 4) {
                                if (xhr.status === 200) {
                                     alert(xhr.responseText);                                                 
                                  } else {
                                            alert("dang!!!");
                                            return false;
                                      }
                          } else {
                                alert("dang!!!! 2 buahahaha");
                                return false;
                          } 
                       var title = document.getElementById('postTitle').value;
                       var postDes = document.getElementById('postDes').value;                                        
                       var postCont = document.getElementById('postCont').value;                                           
                       var data = "title=" + title + "&summary=" + postDes + "&content=" + postCont;                                            
                       xhr.open("POST", "../engine/engine.php",true );
                       xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
                       xhr.send(data);                    
                     }                      

                }

          </script>  
      </body>
    </html>         

<?php   }
      else {
          echo "username or password is incorrect";
          die(mysql_error());

      }
    }  

?>

It is supposed to pass it on to this code

                 <?php
include_once('database.php');
if (isset($_POST['blogsubmit'])  ) {
    $title   =  mysql_real_escape_string($_POST['postTitle']);
    $summary =  mysql_real_escape_string($_POST['postDes']);
    $content =  mysql_real_escape_string($_POST['postCont']);
    insertBlogPost($title,$summary,$content);
}

function insertBlogPost($title,$summary,$content) { 
    $query = "INSERT INTO `blogposts` SET
            `title`     = '$title',
            `summary`   = '$summary',               
            `content`   = '$content' ";                                     
    mysql_query($query) or die(mysql_error());
    echo "Yaaaay";      
}
?>

The problem is that I get a page that prints the Yaaay part instead of alert. I have tried whatever I know of to fix the problem, so I would really appreciate the help. I have also tried switching between true and false for POST but it didn't help.

PS: Sorry for using mysql_* , I'm still not comfortable with using PDO yet. Many thanks in advance.

Bazinga777
  • 5,140
  • 13
  • 53
  • 92

2 Answers2

3

Where do you actually call this AJAX function? Currently, if you strip away all the cruft, you have this:

<form action='../engine/engine.php' method='post'>
    <button type="submit" name="blogsubmit">Submit</button>
</form>
<script type="text/javascript">
    function submit() {
    }
</script>

You're not using the function, just defining it. The form is a normal form submitting a normal POST request, nothing to do with AJAX. And after it submits the POST request, it shows the only output given in the response:

echo "Yaaaay";

One quick way to prevent the form from being submitted would be to make the button no longer a submit button:

<button name="blogsubmit">Submit</button>

Then you just need to attach the click handler to it to call your function. Something like this:

<script type="text/javascript">
    function submit() {
        // the rest of your function
    }

    document.getElementsByName('blogsubmit')[0].onclick = submit;
</script>

There are various other ways to attach a click event handler as well.

Community
  • 1
  • 1
David
  • 208,112
  • 36
  • 198
  • 279
  • I'm not done with the whole code yet and I was too absent minded to not use the onsubmit event handler. Thanks for your information, I learned something new from this. – Bazinga777 Oct 06 '13 at 19:13
1

from what I can see you never bind your submit-function to the submit-event of the form. Currently your function is never called, and the form is doing a regular post to the ../engine/engine.php page, which is why you see its results on a new page.

You should add the following attribute to your form tag:

onsubmit="return submit()"

and in order to override the regular form post so your function can do the work instead you must also return false from your function.

becquerel
  • 1,131
  • 7
  • 11