Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 12 of 12
  1. #1
    Regular Coder
    Join Date
    Nov 2007
    Posts
    680
    Thanks
    319
    Thanked 1 Time in 1 Post

    Adding database entry AJAX

    Now I cannot get this code working. At the moment it needs to just update the table with the message and the user id ($uid) but it will not, the status does not return as "200", which the IF statment checks.

    AJAX:
    Code:
    function sendMessage() {
    	if (sendReq.readyState == 4 || sendReq.readyState == 0) {
    		var url = "scripts/get_data.php?uid=<?=$uid?>";
    		sendReq.open("POST", url, true);
    		sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    		sendReq.onreadystatechange = sendReset; 
    		var param = 'message=' + document.getElementById('txt_message').value;
    		param += '&chat=1';
    		sendReq.send(param);
    		if (sendReq == 4 || sendReq == 200) {
    			document.getElementById('txt_message').value = '';
    		}
    	}
    }
    PHP Code:
    //Send message
    if (isset($_POST['message']) && $_POST['message'] != '') {
        
    //Variables
        
    $chat mysql_real_escape_string($_GET['chat']);
        
    $message mysql_real_escape_string($_GET['message']);
        
        
    $query "INSERT INTO message (chat_id, post_uid, recipient_uid, message, post_time) VALUES (1, ".$sid.", 4, ".$message.", date)";
        
    mysql_query($query);

    And here is the form if you want to see it:
    Code:
     <form id="frmmain" name="frmmain" onsubmit="">
          <input type="button" name="btn_get_message" value="Refresh Chat" onclick="getMessage()" />
          <input type="button" name="btn_reset_chat" id="btn_reset_chat" value="Reset Chat" onclick="resetChat()" />
          <br />
          <input type="text" id="txt_message" name="txt_message" style="width: 447px; color:#000000;" />
          <input type="button" name="btn_send_message" id="btn_send_message" value="Send" onclick="sendMessage()" />
        </form>
    I am using an example of this kind of feature to reference to, and I don't understand how the param is being sent to the server, is it being added to the URL?

    URL before param:
    scripts/get_data.php?uid=3

    after param has been sent (changes in dark orange):
    scripts/get_data.php?uid=3message=message goes here&chat=1

    If so then I am guessing that the var param should look like this(change in red):
    Code:
    var param = '&message=' + document.getElementById('txt_message').value;
    		param += '&chat=1';
    		sendReq.send(param);
    Last edited by martynball; 04-12-2010 at 07:51 PM.

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,155
    Thanks
    75
    Thanked 4,338 Times in 4,304 Posts
    I see nothing in that PHP code that returns anything at all. So if it doesn't return anything, your AJAX code can't get any status value and can't get the non-existent return value.

    But the JS code is very very wrong, too.

    Might I suggest reading up more on how AJAX works???

    http://www.w3schools.com/ajax/ajax_example.asp
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #3
    Regular Coder
    Join Date
    Nov 2007
    Posts
    680
    Thanks
    319
    Thanked 1 Time in 1 Post
    I thought it seemed wrong :/ Was using the examle, why is it that examples NEVER work without a lot of work Lol.

  • #4
    Regular Coder
    Join Date
    Nov 2007
    Posts
    680
    Thanks
    319
    Thanked 1 Time in 1 Post
    Can you explain to me what send() is actually doing, then I can write some new code.

  • #5
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,155
    Thanks
    75
    Thanked 4,338 Times in 4,304 Posts
    AAARRRGGHHH!!! Nice long answer and the forum ate it.

    Try again.
    Code:
    function sendMessage() 
    {
        var url = "scripts/get_data.php";
        sendReq.open("POST", url, true);
        sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        sendReq.onreadystatechange = processAnswer; 
        var param = "uid=<?=$uid?>&chat=1&message=" 
                      + encodeURIComponent(document.getElementById('txt_message').value);
        sendReq.send(param);
    }
    function processAnswer()
    {
        var answer;
        if ( sendReq.readyState != 4 ) return;
        if ( sendReq.status != 200 ) 
        {
            answer = "Invalid status returned from server";
        } else {
            answer = "Messge #" + sendReq.responseText + " added.";
        }
        document.getElementById('txt_message').value = answer;
    }
    The whole idea of send(postdata) is that what you send must match what a submit from <form method="post"> would send. Using encodeUriComponent() is the closest you can come to that.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    martynball (04-12-2010)

  • #6
    Regular Coder
    Join Date
    Nov 2007
    Posts
    680
    Thanks
    319
    Thanked 1 Time in 1 Post
    Hmmm, message didnt add and the txt_message input changed to:
    Messge # added.

    so I am guessing there is something going wrong where sending the request. I don't know if the code is actually executing, but I had a problem with the IF statement before.

    Okay, here is the JS (Code that you gave me, edited a bit though):
    Code:
    function sendMessage() 
    {
        var url = "scripts/get_data.php";
        sendReq.open("POST", url, true);
        sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        sendReq.onreadystatechange = processAnswer; 
        var param = "message=" 
                      + encodeURIComponent(document.getElementById('txt_message').value);
        sendReq.send(param);
    }
    and the php:
    PHP Code:
    //Send message
    if (isset($_POST['message']) && $_POST['message'] != '') {
        
    //Variables
        //$chat = mysql_real_escape_string($_GET['chat']);
        
    $message mysql_real_escape_string($_GET['message']);
        
        
    $query "INSERT INTO message (chat_id, post_uid, recipient_uid, message, post_time) VALUES (1, 3, 4, ".$message.", date)";
        
    mysql_query($query);

    As you can see only the message var is needed at the moment for testing purposes and so the script isnt complex until we get it working. Would the IF statement be returning as true when the request is sent?

    If you understand what I mean Lol.

  • #7
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,155
    Thanks
    75
    Thanked 4,338 Times in 4,304 Posts
    As I said in my first post, you are *NOT* RETURNING anything at all from that!!

    You *must* echo something in order for anything to be returned.

    If you want the message number that was just added, you will need to make another SQL query: SELECT last_insert_id()

    If just OK versus BAD is all you need, then just echo one or the other.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #8
    Regular Coder seco's Avatar
    Join Date
    Nov 2008
    Location
    Oregon
    Posts
    687
    Thanks
    6
    Thanked 79 Times in 77 Posts
    or you can use jquery

    Code:
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
    
        $('#btn_send_message').click(function(){
          $('#loader').show();
          $.post("get_data.php", {
    		message: $('#txt_message').val()
          }, function(response){
            $('#result').fadeOut();
            setTimeout("finishAjax('result', '"+escape(response)+"')", 400);
          });
        	return false;
    	});	
    
    });
        function finishAjax(id, response) {
         $('#loader').hide();
         $('#'+id).html(unescape(response));
         $('#'+id).fadeIn();
        }
    </script>
    Code:
     <input type="text" id="txt_message" name="txt_message" style="width: 447px; color:#000000;" />
          <input type="button" name="btn_send_message" id="btn_send_message" value="Send" />
    <span id="loader" style="display: none;"><img alt="Please Wait" src="images/ajax-loader1.gif" /></span>
    <span id="result" style="display: none;"></span>
    PHP Code:
    <?php
    $message 
    $_POST['message'];

    if (empty(
    $message)) {
        echo 
    'Please enter a message';
    }else{
    //mysql insert

    echo "Message Sent!!";
    }
    ?>
    Last edited by seco; 04-12-2010 at 10:56 PM.

  • #9
    Regular Coder
    Join Date
    Nov 2007
    Posts
    680
    Thanks
    319
    Thanked 1 Time in 1 Post
    Got it working now, changed $_GET to $_POST *facepalm*

    Edit: @seco: As dumb as it sounds I HATE using other peoples code, or copying it fully, hate it with a passion. Lol. I feal as if I have acheived nothing because someone has done it for me.

    So I don't want to use any frameworks.

  • #10
    Regular Coder seco's Avatar
    Join Date
    Nov 2008
    Location
    Oregon
    Posts
    687
    Thanks
    6
    Thanked 79 Times in 77 Posts
    Quote Originally Posted by martynball View Post
    Got it working now, changed $_GET to $_POST *facepalm*

    Edit: @seco: As dumb as it sounds I HATE using other peoples code, or copying it fully, hate it with a passion. Lol. I feal as if I have acheived nothing because someone has done it for me.

    So I don't want to use any frameworks.
    well, JS is pretty much a global framework that requires more work. you still have to code to make jquery work, plugins, etc... no magic in the world of frameworks. but do what works for you. speed and efficiency works for me in this fast web world.

  • Users who have thanked seco for this post:

    martynball (04-12-2010)

  • #11
    Regular Coder
    Join Date
    Nov 2007
    Posts
    680
    Thanks
    319
    Thanked 1 Time in 1 Post
    Where as "speed and efficiency" works for you, pride and the feel of achievment works for me :P its just the way I am Lol.

  • #12
    Regular Coder seco's Avatar
    Join Date
    Nov 2008
    Location
    Oregon
    Posts
    687
    Thanks
    6
    Thanked 79 Times in 77 Posts
    Quote Originally Posted by martynball View Post
    Where as "speed and efficiency" works for you, pride and the feel of achievment works for me :P its just the way I am Lol.
    i hear ya. wait until you have a ton of clients barking down your throat, then speed and efficiency comes into play, lol


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •