Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onclick append textarea to div

Tags:

javascript

php

I currently have an ajax call after a user presses a button on my web page..

The problem is, that after submitting, there is a slight delay (as a second ajax call needs to complete to show the DIV) to avoid a slight lag.. I was wondering if it was possible to append the content to a DIV:

    <textarea name='Status'> </textarea>
    <input type='hidden' name='UserID' value="<?=$_SESSION['UserID']; ?>">
    <input type='button' value='Status Update'>
  <script>
  $(function () {
    $('input').on('click', function () {
        var Status = $(this).val();
       $('#output').append(Status);
});
  </script>

The above is my current code configuration. Now, this does not work as expected. It does not add the submitted content to the DIV.. here is how it's displayed through my ajax call:

window.setInterval(function()
{
  $(function () 
  {
    $.ajax({                                      
        url: 'Ajax/AjaxStatuses.php', data: "", dataType: 'json',  success: function(rows)        
        {
        $('#output').empty();
            for (var i in rows)
            {
                var row = rows[i];          
                var User = row[0];
                var Status = row[1]
                    $('#output').append(''+
                    '<div class="small-3 large-2 columns "><img src="http://placehold.it/80x80&text=[img]" /></div>'+
                    '<div class="small-9 large-10 columns">'+
                        '<p><strong><a href="#">'+User+'</a>:</strong>'+Status+'</p>'+
                        '<ul class="inline-list">'+
                            '<li><a href="">Reply</a></li>'+
                            '<li><a href="">Share</a></li>'+
                        '</ul><hr>');
            } 
        } 
    });       
  });
 }, 1000);

and the call:

 include "../PHP/Database.php";
    $Array = array();

        $Query = $DB->prepare("SELECT UserID, Text FROM statuses Order BY ID DESC");
        $Query->execute();
        $Query->bind_result($ID, $Text);
        $Query->store_result();
        while($Query->fetch()){
            $Second_Query = $DB->prepare("SELECT Username FROM users WHERE ID=?");
            $Second_Query->bind_param('i',$ID);
            $Second_Query->execute();
            $Second_Query->bind_result($Username);
            $Second_Query->fetch();
                $Array[] = array ($Username, $Text);
            $Second_Query->close();         
        }
        $Query->close();

How do I append the text area to a HTML div after pressing the button so my script doesn't have to wait for a response from the newly posted status?


Update. When the button is submitted it calls the following code:

$(function () {
    $('input').on('click', function () {
        var Status = $(this).val();
        $.ajax({
            url: 'Ajax/StatusUpdate.php',
            data: {
                userid: $("input[name=UserID]").val(),
                text: $("textarea[name=Status]").val(),
                Status: Status
            },
            dataType : 'json'

        });
    });
});

To handle the ajax input

like image 307
Sophie Mackeral Avatar asked May 27 '13 03:05

Sophie Mackeral


2 Answers

Sophie.

First, look at this snippet.

window.setInterval(function()
{
  $(function () 
  {
      ...   
  });
 }, 1000);

I guess this is jQuery:) This construction

$(function() { somecode(); }); 

serves to execute somecode(); when DOM is reaches "ready" state. That means - somecode() will be executed only once, on document's "ready" event, and setInterval here just binds functions execution for that event.

You should use this construction instead:

$(function () 
{
    window.setInterval(function()
    {

        somecode();

    }, 1000);
});

Second:

include "../PHP/Database.php";
 $Array = array();
        $Query = $DB->prepare("SELECT UserID, Text FROM statuses Order BY ID DESC");
        $Query->execute();
        $Query->bind_result($ID, $Text);
        $Query->store_result();
        while($Query->fetch()){
            $Second_Query = $DB->prepare("SELECT Username FROM users WHERE ID=?");
            $Second_Query->bind_param('i',$ID);
            $Second_Query->execute();
            $Second_Query->bind_result($Username);
            $Second_Query->fetch();
                $Array[] = array ($Username, $Text);
            $Second_Query->close();         
        }
        $Query->close();

This, actually, doesn't send any response. If this is all code, then you should add

echo json_encode($Array); 

at least, to get any response.

Third:

$.ajax({  
    url: 'Ajax/AjaxStatuses.php', data: "", dataType: 'json', ....

dataType: 'json' means, that you should send a valid JSON string from server, if not - "success" function will not execute.

If this doesn't help, you should check all data flows to find place where they are broken. Use developer console in your browser to see what is going to server and from server in ajax requests to locate the problem, and then you will be able to easily fix the problem.

Also i have some advices for you to make your code more clean:

Try to make more specific selectors for things like this:

$('input').on('click', function () {

Just add an id (or class, if you have many buttons) attribute for corresponding input, and make that like:

$('#id').on('click', function () { ...

or

$('.class').on('click', function () { ...

Also)) Try to extract things like:

<input type='hidden' name='UserID' value="<?=$_SESSION['UserID']; ?>">

out of HTML structure, if this is not inside the form or you use ajax. I see, that you use UserID in js, so better solution here will be

<script type="text/javascript">
   var UserID = "<?=$_SESSION['UserID']; ?>";
</script>

Notice, that this is just better, but not optimal ofcourse. Google for "pass variable from php to js" and choose optimal solutions:)

And the last: Try to make single SQL requests to get data from DB. For example:

"SELECT UserID, Text FROM statuses Order BY ID DESC" 

and

"SELECT Username FROM users WHERE ID=?" 

you can replace with:

"SELECT statuses.UserID, statuses.Text, users.Username
FROM statuses 
INNER JOIN users ON users.ID = statuses.UserID
Order BY ID DESC" 

This will improve performens by decreasing the amount of DB requests.

like image 175
QArea Avatar answered Oct 12 '22 12:10

QArea


Seems the $('#output') is missing . Add to your HTML :

<div id="output"></div>

You will note that there is an JavaScript error in Developer Console if it is the case.

like image 42
Raptor Avatar answered Oct 12 '22 12:10

Raptor