Jump to content
  • Announcements

    • boen_robot

      Guidelines and Netiquette   03/28/2017

      Posting Problems:   Having problems posting your topic? Read through this: To join, you agree to our terms and conditions and fill out and submit a registration form. An activation email will be sent to your email adress, so you'll need to verify your account. After that the account has to be validated by one of the moderators. This will mean that it can take up to a day to be activated. A couple of things to remember to ensure approval: Don't use an email address in one of those $2 four character .com domains eg. xyds.com. These will be deleted and the domain added to the banned list. Don't use an email address that is within a domain with a bad reputation for spam. A Google search is run on every email address and email domain. Don't sign up with an email address that doesn't exist, doesn't work or requires the sender to answer a quiz before their email can get to you. Put your country and or state and city in the signup form. Blank forms will go to the botton of the "to do" list. And make sure that your email address and your country match, saying you're from Alabama and using a .ru email address is not going to get you activated. After a membership is activated the first few posts will be monitored. Posting spam or unapproved topics described in the agreement results in an immediate ban. The email provider and the IP addresses associated with the account will be banned and all posts will be deleted. These strict measures have been deemed necessary to hinder spam. Sorry for any inconvenience this causes, but it's not liable to change. If, after reading this, you still can't post and don't understand why, contact one of the Moderators listed here.   Topic Guidelines   Including the following information can expedite an accurate response from board members: Must be a Specific Problem or Question related to web design and development Include Code in Question (wrap with   for small blocks of code and for longer blocks   ) Include Code Author Include Extra Notes/Modifications/Attempts Include web link to page/file when possible Content Guidelines   You may not post, upload, link to, or email any Content that contains, promotes, gives instruction about, or provides prohibited Content. Prohibited Content includes any Content that breaks any local, state, county, national or international law. Prohibited Content also includes: No direct or indirect advertising or websites, forums, products, services No hijacking of posts (do not post your question in someone elses) Content that infringes upon any rights [ex. MP3s and ROMs] (including, but not limited to, copyrights and trademarks) Abusive, threatening, defamatory, racist, or obscene Viruses or any other harmful computer software False Information or libel Spam, chain letters, or Pyramid schemes Gambling or Illicit drugs Terrorism Hacking or cheating for internet/online games Warez, Roms, CD-Keys, Cracks, Passwords, or Serial Numbers Pornography, nudity, or sexual material of any kind Excessive profanity Invasive of privacy or impersonation of any person/entity Hacking materials or information Posting Tips   There are more BBcodes than there are buttons for on the reply menu. To get the full list, click "BB Code Help" underneath the clickable smilie face menu. Use   for small snippets of code Use   for lengthy snippets of code Use   if your snippet is HTML (optional) Use   if your snippet is SQL (optional) Rules of Conduct   Be nice. There's no need for calling someone stupid if they ask an 'easy' question. Keep your avatars and signatures absolutely child friendly. We have a younger audience on this forum. Keep your language appropriate for the same reason above. Do not PM moderators for help on the forum. Post on the topic, or create a new one.   Spam:   Recently, as you have all without doubt noticed, we have had lots of spam and advertisement on the forum. Therefore, we'd like to alert you as to what to do when you have found any of the aforementioned annoying messages: it. Immediately. Give a clear reason, please, if the advertising is not evident. DO NOT POST! Report, let the post stay as is, and we will get to it, meanwhile if you continue to post as normal in the other threads, it won't be on the top so long. Refrain from PMing the member. This won't help at all, as they are most likely spambots anyway. Thank you.       Images in signatures:   After thinking of users on dial-up, we have decided to enforce the following rules regarding signatures. Please pay heed to them. Respecting these rules is respecting the members on this forum with dial-up. Signature rules: No animated images AT ALL. No matter the amount of animation. Maximum image widthxheight: 300x150 Maximum image (file) size: 15kb Use calm colors. Do not use highly contrasting images in your signature, as this can get really annoying when seeing several posts from one member in the same thread. The same prohibited content goes for images as for posts. Lastly, use common sense. No lengthy signatures please. Save us some scrolling. Thank you.       Links in signatures:   Please understand that w3schools.com only exists because of voluntary work and is barely supported by the advertising littered throughout the tutorials and the forum. So, please, stop advertising other sites. DO not post links that drive traffic away from the w3schools domain - especially to a site that offers similar if not identical information. Please help support the site by keeping individuals on it. Thank you. Here are some guidelines as to what you can put in your signature: w3schools links --> allowed w3.org links --> allowed browser links --> allowed html editor links --> allowed personal sites --> allowed tutorial sites competing with w3schools --> NOT allowed sites completely irrelevant to webprogramming and this forum --> NOT allowed   Thanks for understanding, and for taking the time to read this. ~W3Schools Modstaff~
Loois

Issues comments

Recommended Posts

iwato    6

 

            <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
Loois    0
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
iwato    6

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
Loois    0

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
iwato    6

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
dsonesuk    702

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
iwato    6

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
dsonesuk    702

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
iwato    6

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
dsonesuk    702

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
iwato    6

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
dsonesuk    702

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
justsomeguy    941

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
iwato    6

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
dsonesuk    702

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
justsomeguy    941

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
iwato    6

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
justsomeguy    941

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×