Jump to content

Recommended Posts

I'm trying a simple AJAX request but it's not working no matter what I do. I'm just trying a simple submit from one form for now to get the whole concept of AJAX better, it seems settup fine from what I can tell. What am I missing?

My index page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" />

<head>                    

<title>Test Ajax</title>

<script type="text/javascript" src="js/jquery.js"> </script>
                
      </head>
      <script type="text/javascript">
        $(document).ready(function(){
        $("form#submit_wall").submit(function() {
        
        var message_wall = $('#message_wall').attr('value');
        
        $.ajax({
        type: "POST",
        url: "insert.php",
        data: "message_wall="+ message_wall,
        success: function(){
        $("ul#wall").prepend("<li style="display: none;">"+message_wall+"</li>");
        $("ul#wall li:first").fadeIn();
        }
        });
        return false;
        });
        });
        </script>
      

<body id="thetrue1">

                    <form id="submit_wall">

                  <input type="text" id="message_wall" />
                  <button type="submit">Post to wall</button>
                  </form>

<ul id="wall">
</ul>

</body>
  </html>

 

Then my insert page:

<?php
if(isset($_POST['message_wall'])){
/* Connection to Database */
include('includes/db_login.inc');
/* Remove HTML tag to prevent query injection */
$message = strip_tags($_POST['message_wall']);

$sql = "INSERT INTO Wall (message) VALUES('$message')";
mysql_query($sql);
echo $message;
} else { echo '0'; }
?>

 

I know my database connection is working so that's not the problem, but what am I missing in this code to make it work? I have the jquery.js file correct as well using jQuery v1.7.1. I'll complicate this more once I understand it, but just trying to get the basics completly understood first. And I know it's not secure, I haven't done and mysql_escapes or anything yet on the insert either.

 

Oh and what it's doing is well, nothing. It just refreshes the page, so no Ajax is firing at all. :(

Thanks

Link to comment
https://forums.phpfreaks.com/topic/258991-ajax-request-not-working/
Share on other sites

1. You have ended the <head> tag before the javascript code.

 

2. Does anything happen at all when you submit the form?

 

3. use .val() instead of .attr('value') when grabbing field values.

 

4. Have you debugged this at all to make sure that the request is even being sent?

 

$.ajax({
        type: "POST",
        url: "insert.php",
        data: "message_wall="+ message_wall,
        success: function(){
            alert("success!");
        }

Ok, I moved it inside the </head> I just moved it out of it for a little bit while testing it and forgot to put it back inside.  I also put the alert inside, and I get nothing at all, it just refreshes the page is all it does.

I tried:

<script type="text/javascript">
        $(document).ready(function(){
        $("form#submit_wall").submit(function() {
        
        var message_wall = $('#message_wall').val();
        
        $.ajax({
        type: "POST",
        url: "insert.php",
        data: "message_wall="+ message_wall,
        success: function(){
        alert("success!");
        $("ul#wall").prepend("<li style="display: none;">"+message_wall+"</li>");
        $("ul#wall li:first").fadeIn();
        }
        });
        return false;
        });
        });
        </script>

And

<script type="text/javascript">
        $(document).ready(function(){
        $("form#submit_wall").submit(function() {
        
        var message_wall = $('#message_wall').val();
        
       $.ajax({
        type: "POST",
        url: "insert.php",
        data: "message_wall="+ message_wall,
        success: function(){
            alert("success!");
        }
        });
        });
});
        </script>

But get no alert or anything, just a page refresh.

Yep, the below brings up the alert popup when I submit it.

<script type="text/javascript">
        $(document).ready(function(){
        $("form#submit_wall").submit(function() {
    alert("form submitted");
    return false;     
});
        }); 
        </script>

 

So why would what I have written not do anything at all?

And doing the following returns the request fromt he input (message_wall).

<script type="text/javascript">
      
        $(document).ready(function(){
        $("form#submit_wall").submit(function() {
        
        
        
        var message_wall = $('#message_wall').val();
        alert(message_wall);
        
       
        return false;
        });
        }); 
        </script>

 

but as soon as I put the ajax part in it breaks it with no alerts, just a page refresh.

Actually, it's just this part.

$("ul#wall").prepend("<li style="display: none;">"+message_wall+"</li>");
        $("ul#wall li:first").fadeIn();

 

Because if I take that part out and put the alert back in the ajax area it returns the alert.

 

Like this

 <script type="text/javascript">
      
        $(document).ready(function(){
        $("form#submit_wall").submit(function() {
        
        
        
        var message_wall = $('#message_wall').val();
        
        
        $.ajax({
        type: "POST",
        url: "insert.php",
        data: "message_wall="+ message_wall,
        success: function(){
        

        
        alert(message_wall);  
        }
        });
        return false;
        });
        }); 
        </script>

 

This:

 

<script type="text/javascript">
        $(document).ready(function(){
        $("form#submit_wall").submit(function() {
        
        var message_wall = $('#message_wall').val();
        
       $.ajax({
        type: "POST",
        url: "insert.php",
        data: "message_wall="+ message_wall,
        success: function(){
            alert("success!");
        }
        });
        return false;
        });
});
        </script>

 

should most certainly work.

If it doesn't, make sure that the path leading to insert.php is correct.

 

Edit: Now it works?

the posting etc works, but it doesn't prepend the new LI into the UL which is called in this area of the code that breaks it. If I put this part in, which displays the li it breaks.

$("ul#wall").prepend("<li style="display: none;">"+message_wall+"</li>");
        $("ul#wall li:first").fadeIn();

 

So what you wrote works as far as writing the new input to the database and bringing up the alert, but by putting this other part, which should prepend a new LI into the <ul id="wall"> makes it break and nothing works. 

Ah, you are not escaping the double quotes that you use for the style attribute..

Change to:

 

$("ul#wall").prepend("<li style=\"display: none;\">"+message_wall+"</li>");
$("ul#wall li:first").fadeIn();

 

or wrap it in single quotes:

 

$("ul#wall").prepend('<li style="display: none;">'+message_wall+'</li>');
$("ul#wall li:first").fadeIn();

Oh wow, AWESOME, it works! Thanks, so it's like PHP, didn't even realize that you have to escape quotes like that in js. Thanks, it works fine now. Thanks for helping me learn the alert system better as well through this process, I learned alot. Thanks so much! :)

When debugging javascript, I tend to use alerts each step to make sure that every level works correctly before moving on.

There are also browser Developer tools available to debug front-end code: such as FF's firebug and Chrome's Dev Tools.

Yep, I have firebug and use it alot for finding div's and layouts, never used it for js tho. Another quick question tho, ok, so say I wanted to have this submit based on a key stroke enter. I have it working, but I only get undefined now when I type something and press enter, instead of like before with the submit button.

 

<script type="text/javascript">
         function send()
    {document.commentupdate.submit()}

        $(document).ready(function(){
        $("form#commentupdate").submit(function() {

        var message_wall = $('#message_wall').val();

        $.ajax({
        type: "POST",
        url: "insert.php",
        data: "message_wall="+ message_wall,
        success: function(){
        
        $("ul#wall").prepend("<li style=\"display: none;\">" + message_wall + "</li>");
        $("ul#wall li:first").fadeIn();

        }
        });
        return false;
        });
        }); 
        </script>
      </head>

<body id="thetrue1">

                                <form method="post" id="commentupdate" name="commentupdate" action="">
                                    <input type="hidden" name="action" value="commentupdate" />
                                    <input type="text" class="message_wall" name="message_wall" size="100" onUnfocus="send()" onFocus="clearText(this)" onBlur="clearText(this)" value="Make a comment..." />
                                    </form>
                  

<ul id=

 

Here's what I have to send when pressing enter, but there isn't a .send(function) only submit right?

One more question AyKay.

Ok, so I'm looping through multiple posts pulling the ID's fromt he database, and putting them into the UL, sooo.. I need this to carry over to the commentupdate form. Right now, it's working, but it's posting only to the first post when I click enter, rtather then posting to the correct ID'ed post. So let's say I am trying to comment on post #24, I have in my code.

<?echo"
<form method=\"post\" id=\"commentupdate$PostID\" action=\"\">
                                    <input type=\"hidden\" id=\"action\" value=\"commentupdate\" />
                                    <input type=\"hidden\" id=\"commentviewedID\" value=\"$PostUserID\" />
                                    <input type=\"hidden\" id=\"commentID\" value=\"$CommentmainID\" />
                                    <input type=\"hidden\" id=\"user\" value=\"$user\" />
                                    <input type=\"hidden\" id=\"userID\" value=\"$user_ID\" />
                                    <input type=\"hidden\" id=\"PostID\" value=\"$PostID\" />
                                    <input type=\"hidden\" id=\"UserPostID\" value=\"$CommentUserID\" />
                                    <input type=\"text\" class=\"comment-insert\" id=\"commentinsert\" name=\"commentinsert\" size=\"100\" onUnfocus=\"send()\" onFocus=\"clearText(this)\" onBlur=\"clearText(this)\" value=\"Make a comment...\" />
                                    </form>
";?>

so then commentupdate in the form is commentupdate24

 

now in my ajax from earlier here, how do I use this to say I want to

 

<script type="text/javascript">
         function send()
    {document.commentupdate.submit()}
    
        $(document).ready(function(){ 
        $("form#commentupdate" + PostID + "").submit(function() {
        var commentinsert = $('#commentinsert').val();
        var action = $('#action').val();
        var commentviewedID = $('#commentviewedID').val();
        var commentID = $('#commentID').val();
        var user = $('#user').val();
        var userID = $('#userID').val();
        var PostID = $('#PostID').val();
        
        $.ajax({
        type: "POST",
        url: "include_wall_front/updatecomment_ajax.php",
        data: "commentinsert="+ commentinsert + "&action="+ action + "&commentviewedID="+ commentviewedID + "&commentID="+ commentID + "&user="+ user + "&userID="+ userID + "&PostID="+ PostID,
       success: function(){
        
        $("ul#wall" + PostID + "").append("<li style=\"display: none;\">All my dang code</li>");
                       
      $("ul#wall" + PostID + " li:first").fadeIn();

        }
        });
        return false;
        });
        });
        </script> 

of course $("form#commentupdate" + PostID + "").submit(function() { won't work because it's before when it makes the values. So how would I do this? And I guess I would also need to do this to my on hitting enter part?

 

function send()

    {document.commentupdatel" + PostID + ".submit()}

 

Any ideas?

 

Thanks!

How I have done this in the past is:

 

I set the form to a class, so that every form generated by the loop has the same class.

I also use the post_id in the loop somewhere using the JS "data" attribute (you can google this).

I then write a function that checks for one of the forms submitted via the class I assigned them, and use the post_id in the Ajax data to send to the server.

It seems like all I would have to do is change the $(document).ready(function(){  to a function to call the script at the time the form is submitted rather than when the page is loaded, because if I use

 $(document).ready(function(){ 
         var PostID = $('#PostID').val();
         alert(PostID);
        $("form#commentupdate"+PostID+"").submit(function() {
          
        var commentinsert = $('#commentinsert'+PostID+'').val();
        var action = $('#action').val();
        var commentviewedID = $('#commentviewedID').val();
        var commentID = $('#commentID').val();
        var user = $('#user').val();
        var userID = $('#userID').val();

        $.ajax({
        type: "POST",
        url: "include_wall_front/updatecomment_ajax.php",
        data: "commentinsert="+ commentinsert + "&action="+ action + "&commentviewedID="+ commentviewedID + "&commentID="+ commentID + "&user="+ user + "&userID="+ userID + "&PostID="+ PostID,
       success: function(){
     
        $("ul#wall"+PostID+"").append("<li style=\"list-style-type: none;\">code here</li>");
                       
      $("ul#wall"+PostID+" li:first").fadeIn();

        }
        });
        return false;
        });
        });
        </script> 

 

it alerts the first ID on page load, and since I have onUnfocus=\"send(this)\" in my input area, (like a button submit) can't I change the  $(document).ready(function(){ into a function that would then submit with that PostID that I have as a value in the form to look at that area then? How would I do that tho, it seems easier and more straight forward than the entire looping form into a class and everything else. I suck with classes. :(

So I came up with this.

function send(id){
         var PostID = (id);
         var Form = ("commentupdate"+PostID+"");
        return false;
        });
        }

 

Which alerts the correct ID number when I unfocus my text area, but I can't get the ajax part below it to work, what am I missing? If I try something like this, it doesn't post the form.

function send(id){
         var PostID = (id);
         var Form = ("commentupdate"+PostID+"");     
        
        $("form#"+Form+"").submit(function() {
        var PostID = $('#PostID').val();
          
        var commentinsert = $('#commentinsert'+PostID+'').val();
        var action = $('#action').val();
        var commentviewedID = $('#commentviewedID').val();
        var commentID = $('#commentID').val();
        var user = $('#user').val();
        var userID = $('#userID').val();
        
                
        $.ajax({
        type: "POST",
        url: "include_wall_front/updatecomment_ajax.php",
        data: "commentinsert="+ commentinsert + "&action="+ action + "&commentviewedID="+ commentviewedID + "&commentID="+ commentID + "&user="+ user + "&userID="+ userID + "&PostID="+ PostID,
       success: function(){
     
        $("ul#wall"+PostID+"").append("<li style=\"list-style-type: none;\"><div class=\"comment-main\"><div class=\"comment_pic\"><a href=\"/profile/index.php?id=" + userID + "\" class=\"gallery\"><img width=\"28px\" alt=\"" + user + "\" src=\"profilepics/03072be4743c-3288-3054-9132-5d80c0cf9d7c2012/profile/" + userID + ".jpg\" class=\"profile_pic_smaller\"/></a></div><div class=\"comment-main2\"><div class=\"commentname\"><a href=\"/profile/index.php?id=" + userID + "\" title=\"" + user + "\">" + user + "</a></div><div class=\"deletecomment-holder\"><div class=\"deletecomment1\" style=\"display: none;\"></div></div><div class=\"comments-inner\"><div class=\"comment more\">" + commentinsert + "</div> <br/><div class=\"Likecomment\"><form action=\"\" name=\"likecomment\" id=\"likecomment\" method=\"post\"><input type=\"hidden\" value=\"likecomment\" name=\"action\"/><input type=\"hidden\" value=\"" + PostID + "\" name=\"PostID\"/><input type=\"hidden\" value=\"" + userID + "\" name=\"UserPostID\"/><input type=\"hidden\" value=\"" + commentID + "\" name=\"commentID\"/><input type=\"submit\" value=\"Like\" name=\"submit\" class=\"likecomment\"/></form></div><div class=\"comment-date\">Just Now</div> </div></div></div></li>");
                       
      $("ul#wall"+PostID+" li:first").fadeIn();

        }
        });
        return false;
        });
  
        }

 

I have tried alerts and removing various pieces, it stops at the $("form#"+Form+"").submit(function() { part, but when alerting the var Form it shows the correct form as commentupdate26 or which ever form id I am on if I remove this whole function area and just alert(Form);

 

Here is my form.

<form method=\"post\" id=\"commentupdate$PostID\" action=\"\">
                                    <input type=\"hidden\" id=\"action\" value=\"commentupdate\" />
                                    <input type=\"hidden\" id=\"commentviewedID\" value=\"$PostUserID\" />
                                    <input type=\"hidden\" id=\"commentID\" value=\"$CommentmainID\" />
                                    <input type=\"hidden\" id=\"user\" value=\"$user\" />
                                    <input type=\"hidden\" id=\"userID\" value=\"$user_ID\" />
                                    <input type=\"hidden\" id=\"PostID\" value=\"$PostID\" />
                                    <input type=\"hidden\" id=\"UserPostID\" value=\"$CommentUserID\" />
                                    <input type=\"text\" class=\"comment-insert\" id=\"$PostID\" name=\"commentinsert\" size=\"100\" onblur=\"send(this.id)\" onFocus=\"clearText(this)\" value=\"Make a comment...\" />
                                    </form>

 

Sorry, I know I'm a pain, but I also know there are a bunch of ways to come to a finalized part in coding, and I know I'm sooo close. :)

OK, I got this working the way I want to, cept the comment from the input line comes up undefined, I guess the val doesn't like numbers? Because I have,

 <script type="text/javascript"> 
        function searchKeyPress(e, id)
    {
        // look for window.event in case event isn't passed in
        if (typeof e == 'undefined' && window.event) { e = window.event; }
        if (e.keyCode == 13)
        {
        var PostID = (id);
        var Form = ("commentupdate" + PostID + ""); 
     
        $("form#" + Form + "").submit(function() {
          
        var commentinsert = $('#'+ PostID +'').val();
        var action = $('#action').val();
        var commentviewedID = $('#commentviewedID').val();
        var commentID = $('#commentID').val();
        var user = $('#user').val();
        var userID = $('#userID').val();

        alert(PostID);
        
        $.ajax({
        type: "POST",
        url: "include_wall_front/updatecomment_ajax.php",
        data: "commentinsert="+ commentinsert + "&action="+ action + "&commentviewedID="+ commentviewedID + "&commentID="+ commentID + "&user="+ user + "&userID="+ userID + "&PostID="+ PostID,
       success: function(){
          
        $("ul#wall" + PostID + "").append("<li style=\"list-style-type: none;\">My code</li>");
                       
      $("ul#wall" + PostID + " li:first").fadeIn();
        }
        }); 
        return false;
        });
        }
        
        }      
        </script> 

 

then for the text are, form I have

<form method=\"post\" id=\"commentupdate$PostID\" action=\"\">
                                    <input type=\"hidden\" id=\"action\" value=\"commentupdate\" />
                                    <input type=\"hidden\" id=\"commentviewedID\" value=\"$PostUserID\" />
                                    <input type=\"hidden\" id=\"commentID\" value=\"$CommentmainID\" />
                                    <input type=\"hidden\" id=\"user\" value=\"$user\" />
                                    <input type=\"hidden\" id=\"userID\" value=\"$user_ID\" />
                                    <input type=\"hidden\" id=\"PostID\" value=\"$PostID\" />
                                    <input type=\"hidden\" id=\"UserPostID\" value=\"$CommentUserID\" /> 
                                    <input type=\"text\" class=\"comment-insert\" onkeypress=\"searchKeyPress(event, this.id)\" id=\"$PostID\" size=\"100\" onblur=\"clearText(this)\" onFocus=\"clearText(this)\" value=\"Make a comment...\" />
                                    </form>

 

so the id for the form comes up as just a number 26 or whatever the $PostID form is, then I append this to the commentupdate for the post to match the comments. Pretty tricky huh? ;) But then it doesn't work because the actual ajax part won't let numbers be a variable is my guess, the rest of the values come thru that are hidden, it's just the input=\text\" area, well it doesn't even come up undefinaed now, because of some tweaks, now it just comes up empty completely, no text goes with it for this one value. Any ideas?

 

Edit: Maybe it's not the numbers, because I just changed "user" to "54" and ran it,a nd the user name still came thru, so why would the text area come up empty?

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.