Jump to content
Loois

Issues comments

Recommended Posts

 

            <form method="post" name="form_name" id="form_name" action="https://www.w3schools.com/comment.php">
                <fieldset>
                    <legend>Title</legend>
                    <p>A brief explanation about what you would like to see entered.</p>
                    <textarea  name="comment" form="form_name" maxlength='400' rows="8" placeholder='Character Limit:  400'></textarea>
                </fieldset>
                <input type="submit" value="Submit comment">
            </form>

In addition you must decide what you want to do with the comments  and how to process them one they are received via the post ($_POST) method at comment.php.

Roddy

  • Like 1

Share this post


Link to post
Share on other sites
I actually had problems with comments.php i can not establish the 
function, i form i already keep it alike but i can not create the 
function behind. Can not you help me?
Edited by Loois

Share this post


Link to post
Share on other sites

Please post the contents of the file comments.php.  Show us what you have done, what does not work.

Share this post


Link to post
Share on other sites

comment.sql

CREATE TABLE `comment` (
  `user_id` int(8) NOT NULL,
  `photo_id` int(8) NOT NULL, 
  `comment` text NOT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`user_id``photo_id`)
);

ajax_comment.php

<?php
// code will run if request through ajax
if (isset( $_SERVER['HTTP_X_REQUESTED_WITH'] )):
  include('../config.php');
  // connecting to db
  dbConnect();
  
  if (!empty($_SESSION['user_id']) AND !empty($_POST['photo_id']) AND !empty($_POST['comment'])) {
    // preventing sql injection
    $user_id = $_SESSION['user'];
    $photo_id = $_POST['photo_id'];
    $comment = $_POST['comment'];

    // insert new comment into comment table
    $query = "INSERT INTO comment (user_id, photo_id, comment) VALUES('$user_id', '$photo_id', '$comment')");  
  }
?>
<!-- sending response with new comment and html markup-->
<div class="comment-item">
  <div class="comment-avatar">
        <a href="<?php echo $baseurl . "/" . $photo_username ?>"><img src="./core/getimg.php?profiloimg=<?php echo $photo_userid ?>" class="home-foto-profilofoto" /></a>  </div>
  <div class="comment-post">
    <h3><?php echo $photo_username . "/" . $user_id ?> <span>ha commentato:</span></h3>
    <p><?php echo $comment?></p>
  </div>
</div>

<?php
  // close connection
  dbConnect(0);
endif?> 

jQuery.js

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
  var form = $('form');
  var submit = $('#submit');

  form.on('submit', function(e) {
    // prevent default action
    e.preventDefault();
    // send ajax request
    $.ajax({
      url: 'ajax_comment.php',
      type: 'POST',
      cache: false,
      data: form.serialize(), //form serizlize data
      beforeSend: function(){
        // change submit button value text and disabled it
        submit.val('Submitting...').attr('disabled', 'disabled');
      },
      success: function(data){
        // Append with fadeIn see http://stackoverflow.com/a/978731
        var item = $(data).hide().fadeIn(800);
        $('.comment-block').append(item);

        // reset form and button
        form.trigger('reset');
        submit.val('Submit Comment').removeAttr('disabled');
      },
      error: function(e){
        alert(e);
      }
    });
  });
});
</script> 

home.php (Where there are my users posts)

		
		<!--  Commenti -->
		
	<form id="form" method="post">
    <!-- need to supply post id with hidden fild -->
    <input type="hidden" name="comment" value="1">
        <label>
      <a href="<?php echo $baseurl . "/" . $photo_username ?>"><img 	width="25"
	height="25"src="./core/getimg.php?profiloimg=<?php echo $photo_userid ?>" class="home-foto-profilofoto" /></a>
		</label>
		<label>
        <a href="<?php echo $baseurl . "/" . $photo_username; ?>"><?php echo $photo_username; ?></a>

		</label>
	<label>
      <span>Commenta</span>
      <textarea name="comment" id="comment" cols="0" rows="0" placeholder="Scrivi un commento.." required></textarea>
    </label>
    <input type="submit" id="submit1" value="Submit Comment">
  </form>
  <?php 
include ("ajax_comment.php");
include ("jquery.js");
  ?>
      <!-- Fine commenti -->

 

Share this post


Link to post
Share on other sites

There is no action attribute in the following line of code

<form id="form" method="post">

You must enter an URL for ajax_comment.php as the value of your action attribute in the above <form> element.

<form id="form" method="post" action='pathto/ajax_comment.php'>

Replace the word "pathto" with whatever is necessary to connect the document that contains your form with the document that processes your $_POST variable -- namely, ajax_comment.php.

Edited by iwato
  • Like 1

Share this post


Link to post
Share on other sites

Its AJAX, it does not require those, without action the form will submit to itself, and as that php file is included in the form page itself, which maybe used to takes into account if JavaScript is disabled it will then as said be submitted, page reloaded and processed by the same page, BUT! currently it will only show if AJAX request is sent ($_SERVER['HTTP_X_REQUESTED_WITH']), which seems pointless including in the form page as a non JavaScript alternative. While with JavaScript enabled, the form is prevented from being submitted, it gathers the input data and sends it to the php file specified in the JavaScript AJAX url code to be processed and return the result without reloading of page

  • Like 1

Share this post


Link to post
Share on other sites

OK.  Thank you for the correction, Dsonesuk.  I have never used AJAX and looked only for what was different from what I use -- namely, PHP. Upon a more careful reading I now see the statement

include ("ajax_comment.php");

If I have further understood, you find the following statement to be ill-conceived,

if (isset( $_SERVER['HTTP_X_REQUESTED_WITH'] )):include('../config.php');

and give as a reason that the PHP will only be used, if the Javascript succeeds.

So, if Loois were to write, 

if (!isset( $_SERVER['HTTP_X_REQUESTED_WITH'] )):include('../config.php');

would this fix his problem.

  • Like 1

Share this post


Link to post
Share on other sites

It would transfer the problem to AJAX code, it depends on WHY the ajax php code was included in the form page

if (isset( $_SERVER['HTTP_X_REQUESTED_WITH'] )):include('../config.php');

will not run php code beyond this 'if' condition, if page reloads because JavaScript was disabled which prevents the form being submitted, it is no longer a JavaScript AJAX request.

if (!isset( $_SERVER['HTTP_X_REQUESTED_WITH'] )):include('../config.php');

Will allow the php code within the form to be processed if JavaScript disabled, BUT! will prevent AJAX request being processed if JavaScript is enabled and it goes directly to ajax_comment.php

  • Like 1

Share this post


Link to post
Share on other sites

So, why use AJAX at all?

Since AJAX depends on Javascript being turned on or off, and since this decision is made by the user-client, why not use PHP whose functioning is determined solely by the host-server?

  • Like 1

Share this post


Link to post
Share on other sites

You should always provide a pure php script, to sanitize and validate, BECAUSE JavaScript CAN be disabled, You can use AJAX to update content, make database requests/update/insert etc without the need to reload the page constantly, which is required for pure php code to do the same thing.

Usually you would not include the php script in the form page, only the AJAX JavaScript code would access it externally, to process the form data and return results to a specific location, it makes more sense this way checking with $_SERVER['HTTP_X_REQUESTED_WITH'] that it is a AJAX request.

Without this it could be included in the form page, it would retrieve default information or content on loading of page, a AJAX request could be made using form using the same php script externally, the new AJAX returned results can be use to update/overwrite the default content without reloading the page.

Edited by dsonesuk
  • Like 1

Share this post


Link to post
Share on other sites

OK.

The advantage of using AJAX is to prevent having to reload the page each time the form is submitted, and
the advantage of using PHP is to insure that the submitted data is sanitized and validated.

Are implying with this that it is not possible to use Javascript for the purpose of sanitization and validation?

If I have understood correctly, AJAX serves only as an intermediary between the form page and the PHP page.  In other words,

  • the PHP page should be written, as if the AJAX did not exist, and
  • the AJAX should always refer to the PHP page via the following piece of code
$.ajax({
      url: 'ajax_comment.php',

What is more, the PHP code should only be included in the page, if the following condition is satisfied.

!isset( $_SERVER['HTTP_X_REQUESTED_WITH'] )

Thus, it was wrong for Loois to have included the following code at the bottom of his form page

include ("jquery.js");

Under the assumption that all of the above is correct, why is the following code not entered at the top of the form page?

include ("jquery.js");

My very best,

Roddy

  • Like 1

Share this post


Link to post
Share on other sites

No! the PHP file in its present state should not be included in to the form page, it is AJAX specific because of the if condition, which should be access by JavaScript  AJAX code that uses url to that php file to retrieve required data using server script language PHP.

I don't know what jquery.js is? is it the users own custom code or jquery framework code? either way it is perfectly all right if not the norm to place js code at bottom of page, as it will help in loading of page quicker as html and css needs to loaded primarily first, and JavaScript secondary as most of the time JavaScript is triggered by events by the user after the page is fully loaded.

The main problem with

include ("jquery.js");

is that is needs to be within <script>...</script> tags if custom js code, OR if jQuery framework file, it should link to it, using for example

<script type="text/javascript" src="jquery.js"></script>

 

  • Like 1

Share this post


Link to post
Share on other sites

Are implying with this that it is not possible to use Javascript for the purpose of sanitization and validation?

You can use Javascript to validate data as a convenience for the user (so they don't have to refresh the page when something is wrong), but there's no reason to sanitize with Javascript, and on the server you have to assume that any data coming in is untrusted.  No one has to use your Javascript code to submit whatever they want to your server.  If I use your code to submit a request once then I can use my developer tools to inspect that request and submit something that I create myself which your server won't be able to know is malicious but could contain whatever data I want.  Always validate and sanitize if necessary on the server.  The only reason to validate in Javascript is for convenience.

Share this post


Link to post
Share on other sites

Dsonesuk:  I am still a little confused by this statement 

Quote

if (!isset( $_SERVER['HTTP_X_REQUESTED_WITH'] )):include('../config.php');

Will allow the php code within the form to be processed if JavaScript disabled, BUT! will prevent AJAX request being processed if JavaScript is enabled and it goes directly to ajax_comment.php

The condition is true when AJAX is absent, but false when it is present.  So, if AJAX is present, ajax_comment.php' will be called, and if AJAX is absent config.php is called.  As we do not know what is contained in config.php, it is difficult to know why there would be two different PHP pages to process the same code.  Does this make sense to you?

Loois:  Could you show us config.php?

JSG:  OK. I appear to understand that sanitization, perhaps not validation, should always take place on the server side.  And, in the event that the user has turned Javascript off, one would also want to sanitize on the server-side.  What I am unclear about is the nature of the manipulation of the Javascript.  Can the user actually rewrite the author's Javascript?  Or, is it that the user submits his own Javascript as input data that takes advantage of the Javascript that the author has written?

Share this post


Link to post
Share on other sites

No! the if condition is from top and ends at bottom with endif  if the condition is true  it will include config.php and process the rest of code present, and that is that! There is no alternative like an else condition.

Share this post


Link to post
Share on other sites

Can the user actually rewrite the author's Javascript?

Well, I can use my browser to specify my own Javascript file to run on your site, but I can't change your code.  I'm saying that Javascript shouldn't be used as a protection mechanism for submitted data, because I can submit any arbitrary data I want to by creating my own request.  I don't need to use your form or your page at all to submit a post or get request to any endpoint on your server.  People trying to attack websites know that, and you have to know it when dealing with application security.  The general rule is to not trust any submitted data, everything needs to be validated and, if necessary, sanitized.

Share this post


Link to post
Share on other sites

JSG - Up until now I have understood that a Javascript script can be entered via an <input> or <textarea> control form, or for that matter any other data that is passed from a form to the same or another processing page when the <submit> control is triggered.  What you seem to be suggesting is something else.  Am I in error?  If not, could you provide an example.  I would like to see what i am up against.

Roddy

Share this post


Link to post
Share on other sites

Up until now I have understood that a Javascript script can be entered via an <input> or <textarea> control form, or for that matter any other data that is passed from a form to the same or another processing page when the <submit> control is triggered.

I'm not sure what you mean by that.

I'm just saying that in terms of validation, sanitizing, etc, that you can't rely on Javascript, it's a convenience for the user at best, and that the final word is what you do on the server.  As long as the server is sanitizing the data and not trusting that the form submitted everything in the right format then you should be fine. 

Share this post


Link to post
Share on other sites

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.   Paste as plain text instead

  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.

Loading...

×
×
  • Create New...