understanding the logic of parsing multiple $POST without using id

29 views
Skip to first unread message

rico harley

unread,
Apr 27, 2015, 12:05:40 PM4/27/15
to atlan...@googlegroups.com
/* comment_parsers.php  */

<?php
/*if(isset($_POST["message"])){
    echo $_POST["message"]." is information ";
exit();
}*/
echo 'Thank you '. $_POST['message'] . ' ' .', says the PHP file';
?>   


The question is, how can I use this snippet to parse multiple textareas?

this gets the value in Javascript of the textarea when parsed.    var m = document.getElementById("message").value;

But the problem is I am going to be outputting the textarea through a While loop, which means I can't have multiple id's.
So how can I get the value  of each textarea, so that I can get the $POST value of each textarea?



<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script>
<!-- ******** ajax.js ******** -->
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
   return true;
}
}

</script>
</head>

<body>
<!--This will be output using a While loop for however many records are in the database. -->

<h2>Ajax Post to PHP and Get Return Data</h2>
<textarea id="message"></textarea>  <br><br>
<button onclick="comment();">Post</button><br><br>

<textarea id="message"></textarea>  <br><br>
<button onclick="comment();">Post</button><br><br>
<div id="status"></div>


</body>
<script>


function comment(){
    var m = document.getElementById("message").value;
var vars = "message="+m;
  if ( m ) {     // check to see if m is an empty string or undefined  
var ajax = ajaxObj("POST", "comment_parser.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
alert(ajax.responseText);
}
}
ajax.send(vars);
} else {
            alert( "You must enter text." );
        }
}

</script>

</html>

Brad

unread,
Apr 28, 2015, 3:54:22 PM4/28/15
to atlan...@googlegroups.com
This is a situation where you really need to learn to walk before you can run. You can't have multiple elements with the same ID attribute. If you're going to have a form, make it an actual working form first and then extend the functionality with Javascript. Your loop of forms should look something like this:

<h2>Ajax Post to PHP and Get Return Data</h2>
<form method="post" action="comment_parser.php" class="post-comment">
    <textarea name="message" class="comment-message"></textarea><br />
    <button type="submit">Post</button>
</form>

<form method="post" action="comment_parser.php" class="post-comment">
    <textarea name="message" class="comment-message"></textarea><br />
    <button type="submit">Post</button>
</form>

Even without Javascript, these will still work. Then use Javascript to intercept the form submit, use the form's action attribute as the request URL and post the form with ajax. In plain Javascript this requires a lot of boilerplate, so here it is in jQuery for the sake of space and readability:

<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
    $('.post-comment').on('submit', function(e) {
        e.preventDefault();
        $.ajax({
            method: 'POST',
            dataType: 'text',
            url: $(this).attr('action'),
            data: { message: $('.comment-message', this).val() }
        }).fail(function() {
            alert('Error!');
        }).done(function(data) {
            alert(data);
        });
    });
</script>

In your PHP file you can determine if the request is from AJAX or not using: if ($_SERVER['HTTP_X_REQUESTED_WITH']) === 'XMLHttpRequest') ...

As an aside, it's never a good idea to echo out unfiltered $_POST variables. You'll leave yourself open to XSS attacks. Use some sort of Request object like http://framework.zend.com/manual/1.12/en/zend.controller.request.html or http://laravel.com/api/5.0/Illuminate/Http/Request.html or whatever to add a layer of abstraction between superglobals and your codebase. Always validate inputs as much as possible, look into the Filter functions as a good starting point. http://php.net/manual/en/ref.filter.php

Randall

unread,
May 2, 2015, 1:32:31 PM5/2/15
to atlan...@googlegroups.com, rmhar...@gmail.com
What you are running into is that in HTML, each "id" needs to be unique.  Your HTML is actually not compliant and may not send you the same post from one browser to another.

To resolve this, you should give each textarea its own name/id. 

I don't know the exact use case you have, but the classic example is to just number your text areas like this:

<textarea name="area1"></textarea><br />
<textarea name="area2"></textarea><br />
<textarea name="area3"></textarea><br />
<textarea name="area4"></textarea><br />
<textarea name="area5"></textarea><br />


Then you can loop through them like this:

for($i=1; $i <= 5; $i++){

    echo $_POST['area' . $i]. "is information ";

}

You can also write that as $_POST["area{$i}"] if you prefer.

...

If you are displaying content provided directly from the user, make sure you understand what Cross Site Scripting attacks are.  Your application may be vulnerable to them.  As a minimum safety precaution, you might do this instead:

echo htmlentities($_POST['area' . $i]));

....

Feel free to contact me directly if you need follow-up or additional assistance.

-Randall
--
You received this message because you are subscribed to the Google Groups "AtlantaPHP Discussions and Job Postings" group.
To unsubscribe from this group and stop receiving emails from it, send an email to atlantaphp+...@googlegroups.com.
To post to this group, send email to atlan...@googlegroups.com.
Visit this group at http://groups.google.com/group/atlantaphp.
To view this discussion on the web visit https://groups.google.com/d/msgid/atlantaphp/fecabd66-5e52-44b6-8742-95676c599e5b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

rico harley

unread,
May 2, 2015, 11:35:04 PM5/2/15
to atlan...@googlegroups.com, rmhar...@gmail.com
<script>
$('.postThis').click(
function(){
$.ajax(
{
url:'comments.php?ip=<?php echo $ip;  ?>&logid=<?php echo $log_id;  ?>',
method:"POST",
data:$('.messageForm').serialize(),
complete:function(data){
//$('.status').text("SENT");
alert(data.responseText+ '<br><br>');
}
}
)
});
</script>

Alphonso Clay

unread,
May 4, 2015, 3:07:54 PM5/4/15
to gh...@uxch.com, atlan...@googlegroups.com, rmhar...@gmail.com
Actually you don't need to name each uniquely just the ID, but you can do what you are trying to several ways, the easy way (FOR ME), is to name the textareas as an array within the POST array, then when you run the loop to get the values, its easier and cleaner.

This sample works, you can validate by using the network tab in your developer console, I posted the values back to the same page and printed them in the response section of the dev tab, you can post to a separate script if you like (preference).

Look at the naming and the class, if you want to, you can use the class to retrieve the values and then a data parameter in the method on POST that way.

Either way, it depends on your level of comfort.

Save this as testo.php.

<html>
<head>
<title>AJAX test page</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>

<h2>Ajax Post to PHP and Get Return Data</h2>
<form id="messageForm" onsubmit="return false">
<textarea class="message" name="messageBox[]"></textarea>  <br><br>
<textarea class="message" name="messageBox[]"></textarea>  <br><br>
<textarea class="message" name="messageBox[]"></textarea>  <br><br>

<button id="postThis">Post</button><br><br>
</form>

<div id="status" style="font-size:2em;"></div>
<div id="returnedText"></div>
<script>
    $('#postThis').click(
        function(){
            $.ajax(
                {
                    url:'testo.php?mode=test',
                    method:"POST",
                    data:$('#messageForm').serialize(),
                    success:function(data){
                        //alert(data);
                        $('#status').text("SENT");
                        alert($(data).find('#returnedText').text());
                        //$(data).find('#returnedText').html();
                        //alert($(data).filter('#returnedText').text());
                        //$("#returnedText").text($(data).find('#returnedText').text());
                        //alert("SENT");
                    }
                }
            )
    });
</script>
<?php
    if(isset($_GET['mode']))
        foreach($_POST['messageBox'] as $messageItem){
            /*
            do some processing here
            DB insert etc
            */
            echo($messageItem . "</br>");
        }
?>
</body>
</html>




Reply all
Reply to author
Forward
0 new messages