0

I'm getting problems with my php script and ajax. I have a unique home page where there is a central div that change content base on different clicks. I can't refresh my page in any case beacuse there is and audio player that can stop playing music. Now I have to execute the playlist creating by users. After that the user load all the attributes for its playlist, i submit the form to a php script to load the playist into the db. But I doesn't want to leave my home page. So I tried with an AJAX function in order to submit the form and load into the central div a message. I have already used AJAX for other goals with success, but in this case it's a little bit more difficult.

This is my form:

<div class="pers_playlist_add">
<h3> Aggiungi Playlist </h3>
<form class="pers_form_down" id="formaddplaylist" action="playlistaddscript.php" method="post">
    Nome Playlist: <input type="text" name="playlist" required></input>
    Descrizione Playlist: <input type="text" name="desc" required></input><br>
    Privata: <input type="radio" name="priv" value="y" checked="checked">Si</input>
    <input type="radio" name="priv" value="n">No</input>
    <button id="created" style="float: right;" class="btn waves-effect waves-light" type="reset">Pulisci</button>
    <button style="float: right; margin-left: 5px;" class="btn waves-effect waves-light" onClick="aggiungiplaylist()">Crea Playlist</button>
</form>

This is my php script

<?php
session_start();    
$name = $_POST['playlist'];
$desc = $_POST['desc'];
$priv = $_POST['priv'];

$conn = mysqli_connect('localhost','root', '') 
    or die("Cannot connect to the dbms");

$query = mysqli_query($conn, "use my_alessiocorvagliatsn") 
    or die ("Cannot choose the tsn_db");

if($priv == 'y'){
    $p = 1;
}
else{
    $p = 0;
}

$email = $_SESSION['email'];

$q = "Insert into tsn_playlists (playlistname, playlistdescription, private, email) values ('$name', '$desc', '$p', '$email')";
$query = mysqli_query($conn, $q)
    or die("Cannot add a playlist");
?>

This is my AJAX function:

function aggiungiplaylist() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("formaddplaylist").submit();
      document.getElementById("central").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "addedplaylist.html", true);
  xhttp.send();
}

The function work, but at the end of the processing takes me to the playlistaddscript.php with an (obviuous) blank page. If you need more information, please ask me. How can I solve it?

  • [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)*** Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! – Jay Blanchard May 30 '17 at 15:15
  • @JayBlanchard I know that, this is just for a school project, I will do that changes if I will have time – Alessio Corvaglia May 30 '17 at 15:19
  • 3
    If you don't have time to do it right the first time, when will you find the time to add it later? I hate when people say *"I'm not that far along..."* or *"This site will not be public..."* or *"It's only for school, so security doesn't matter..."*. If teachers and professors are not talking about security from day one, they're doing it wrong. Challenge them. They're teaching sloppy and dangerous coding practices which students will have to unlearn later. I also hate it when folks say, *"I'll add security later..."* or *"Security isn't important now..."* or *"Ignore the security risk..."*. – Jay Blanchard May 30 '17 at 15:19
  • rather than submit the form in a traditional sense I'd use a `FormData` ( https://developer.mozilla.org/en/docs/Web/API/FormData ) object and use the ajax callback to work with the response from the server. – Professor Abronsius May 30 '17 at 15:22
  • For your case, you just use a button (not submit). And you call onclick event. It wil not redirect to another page. One more, why you get data in php by POST, but you call AJAX by GET? – Freelancer May 30 '17 at 15:26

2 Answers2

0

You get a blank page because the form will submitted, this happens because the button type attribute isn't specified, so it takes the default value that's submit.

Button type attribute could be:

<button type="button|submit|reset">
  • button: The button is a clickable button
  • submit (default): The button is a submit button (submits form-data)
  • reset: The button is a reset button (resets the form-data to its initial values)

See following please:

function aggiungiplaylist() {
  console.log("dummy aggiungi");
}
<div class="pers_playlist_add">
<h3> Aggiungi Playlist </h3>
<form class="pers_form_down" id="formaddplaylist" action="playlistaddscript.php" method="post">
    Nome Playlist: <input type="text" name="playlist" required></input>
    Descrizione Playlist: <input type="text" name="desc" required></input><br>
    Privata: <input type="radio" name="priv" value="y" checked="checked">Si</input>
    <input type="radio" name="priv" value="n">No</input>
    <button id="created" style="float: right;" class="btn waves-effect waves-light" type="reset">Pulisci</button>
    <button style="float: right; margin-left: 5px;" class="btn waves-effect waves-light" onClick="aggiungiplaylist()" type="button">Crea Playlist</button>
</form>

In conclusion, you have to add the attribute type="button" on "Crea Playlist" button, like:

<button type="button" style="float: right; margin-left: 5px;" class="btn waves-effect waves-light" onClick="aggiungiplaylist()" type="button">Crea Playlist</button>

I hope it helps you, bye.

Alessandro
  • 4,382
  • 8
  • 36
  • 70
0

If you were to submit the data from the form using ajax ( and for convenience a FormData object ) rather than using the callback function to submit the form the page would not reload and you could send back a response from the php script - to use as you see fit.

function aggiungiplaylist() {
    var form=document.getElementById('formaddplaylist');
    var div=document.getElementById('central');
    var data=new FormData( form );

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function(e) {
        if( this.readyState == 4 && this.status == 200 ) {
            if( div ) div.innerHTML = this.response;
        }
    };
    /* send the data directly to the php script */
    xhttp.open( 'POST', 'playlistaddscript.php', true );
    xhttp.send( data );
}
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46