1

I am using a form to collect values to add a new player to my created database. To do this I am required to have an HTML page (this is where the form is held) a Javascript file with an ajax call to post and a php file to connect to the database.

However when I fill in the form and click submit, instead of showing me the newly added player it will just show me my Javscript code on the browser. I am not too sure where the error is, as I have kept everything lower space both in the form and database.

Here is my form code linking to the JS file:

 <h2>Add a Player:</h2>
         <form action="api2.js" method="post">
         <input type="text" name="firstname" placeholder="First Name" /><br>
         <input type="text" name="lastname" placeholder="Last Name" /><br>
         <input type="text" name="team" placeholder="Team" /><br>
         <input type="submit" value="submit" />
         </form>

and here is my JS file:

$(document).ready(function(){   

    $.ajax({    
                 type:  'POST', 
                 url:   'api.php/players',  
                 data:JSON.stringify(nhl),
                 success:   showResponse,   
                 error: showError
                    }); 

    function    showResponse(responseData)  {   
             console.log(responseData); 
}   
function    showError() {   
             alert("Sorry,  there   was a   problem to  add new staff!" );  
}

});


    function    Player(firstname,   lastname,   team){  
this.firstname = firstname; 
this.lastname = lastname;   
this.team = team
}   
                        $('form').on('#submit', function(event){

                            event.preventDefault();

                            var player = new Player(firstname, lastname, team);
                            var firstname = $('.firstname').val();
                            var lastname = $('.lastname').val();
                            var team = $('.team').val();




}); 

and lastly my php file:

//Add Player

function    addPlayer() {   
                $request    =   Slim::getInstance()->request(); 
                $nhl    =   json_decode($request->getBody());   
                $sql    =   "insert into    nhl (lastname,  firstname,  team)   values  (:lastname, :firstname, :team)";    
                try {
                                $db =   getConnection();    
                                $stmt   =   $db->prepare($sql); 
                                $stmt->bindParam("lastname",    $nhl->lastname);    
                                $stmt->bindParam("firstname",   $nhl->firstname);   
                                $stmt->bindParam("team",    $nhl->team);    
                                $stmt->execute();   
                                $nhl->Player_Id =   $db->lastInsertId();    
                                $db =   null;   
                                responseJson(json_encode($nhl),201);    
                }   catch(PDOException  $e) {   
                                responseJson(   '{"error":{"text":'.    $e->getMessage()    .'}}',500); 
}   
}   

I have tried changing the form action to the php file but it will either show a 404 error or if I link it straight to the api.php/players it will show me this error:

{"error":{"text":SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'lastname' cannot be null}}`

Any help or guidance would be greatly appreciated.

2
  • 1
    The error message is pretty clear. Did you check the values in $nhl? Commented Apr 22, 2015 at 10:05
  • yeah all values are spelt the same and all in lowercase, I was told to change the DB columns to null to troubleshoot, once I did this it posted to my database, but instead of the values I input in the form it is posting the Values as NULL instead Commented Apr 22, 2015 at 10:21

3 Answers 3

1

Because you are doing this:

<form action="api2.js" method="post">

The HTTP POST method sends form data to the specified URL, and redirects to that URL. If that URL is a web page, it will be rendered as such. JavaScript (your api2.js file) is not.

What you probably want to do is have your form post to your PHP file.

Sign up to request clarification or add additional context in comments.

1 Comment

ahh ok, the problem is I am required to have it link through the js to the php, is there anyway around this? When I do link it to the api.php/players it is collecting the values of the form but posting them to my database as NULL values.
0

I don't think you need 'action="api2.js"'. Is there a script link such as

<script type="text/javascript" src="path/to/js/api2.js"></script>?

If so your js file should take care of picking up the submit form by changing it to

$('input').on('click', 'input#submit', function(event){

              event.preventDefault();
              var player = new Player(firstname, lastname, team);
              var firstname = $('.firstname').val();
              var lastname = $('.lastname').val();
              var team = $('.team').val();

              var nhl = {};
                  nhl['firstname'] = firstname;
                  nhl['lastname'] = lastname;
                  nhl['team'] = team;
});

and

<input type="submit" value="submit" /> to  <input type="submit" value="submit" id="submit" />

I would print the variables at this stage and check in the console to see if they had been picked up and then I would check again that they are passed to the php file (var_dump($nhl)) and make sure the form contents make it to the php file.

One other thing to check is the URL of the php file and make sure it is accessible. I don't think it is correct as it stands.

7 Comments

Seems it is saying that the nhl variable in this line data:JSON.stringify(nhl), is not defined
where are you saving your js vars (firstname, lastname etc) to nhl? You need to save these variables to the JSON object nhl when you submit them to form the form to the js script, I will update my answer
nhl is the tablel that the values need saved to
Yes but in this line data:JSON.stringify(nhl) you are turning a js value nhl into a JSON string but nhl is never set.
So what would you suggest I do to rectify this?
|
0

1) If you set form action to api2.js, how will you receive the data in the JS file,? instead, you may do like this. Try this,

 <h2>Add a Player:</h2>
         <form action="" method="post">
         <input type="text" id="firstname" name="firstname" placeholder="First Name" /><br>
         <input type="text" id="lastname" name="lastname" placeholder="Last Name" /><br>
         <input type="text" id="team" name="team" placeholder="Team" /><br>
         <input type="button" value="submit" onClick="showData();" />
         </form>

         <div style="position:absolute;padding:30px 20px 30px 20px;text-align:center;width:80%;left:0px;right:0px;"> </div>



         <script type="text/javascript">
         function showData()
         {
         var first = document.getElementById('firstname').value;
         var last = document.getElementById('lastname').value;
         var team = document.getElementById('team').value;

         // COMPOSE YOUR "nhl" STRING THE ABOVE VALUES 

         $.ajax({    
                 type:  'POST', 
                 url:   'api.php/players', THAT'S WHY IT'S SHOWING 404 ERROR.
                 data:JSON.stringify(nhl),
                 success:   showResponse,   
                 error: showError
                    }); 

        function    showResponse(responseData)  {   
             console.log(responseData); 
         }   
         function    showError() {   
             alert("Sorry,  there   was a   problem to  add new staff!" );  
          }

          });


          function    Player(firstname,   lastname,   team){  
            this.firstname = firstname; 
            this.lastname = lastname;   
            this.team = team
            }   
                        $('form').on('#submit', function(event){

                            event.preventDefault();

                            var player = new Player(firstname, lastname, team);
                            var firstname = $('.firstname').val();
                            var lastname = $('.lastname').val();
                            var team = $('.team').val();


         }

         </script>

4 Comments

That is unfortunately doing nothing. It just stays on the homepage and nothing happens
1) right click => insepect elements => console, if you see any javascript errors, fix them, 2) alert javascript response.
I have sent you the files there Nandan
Ok, I'll have a look at it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.