-1

EDIT

I have implemented the changes suggested and I still cant get this to work:

Form Page Follows (login.php)

<?php
   $mac=$_POST['mac'];
   $ip=$_POST['ip'];
   $username=$_POST['username'];
   $linklogin=$_POST['link-login'];
   $linkorig=$_POST['link-orig'];
   $error=$_POST['error'];
   $chapid=$_POST['chap-id'];
   $chapchallenge=$_POST['chap-challenge'];
   $linkloginonly=$_POST['link-login-only'];
   $linkorigesc=$_POST['link-orig-esc'];
   $macesc=$_POST['mac-esc'];
if (isset($_POST['postcode'])) {
    $postcode = $_POST['postcode'];
}
if (isset($_POST['email'])) {
    $email = $_POST['email'];
}
?>

**SOME HTML HERE**


<script src="jquery-3.2.1.min.js"></script>

<script>

var js-postcode = document.login.getElementsByName("postcode").value;
var js-email = document.login.getElementsByName("email").value;
var formdata = {postcode:js-postcode,email:js-email};

        $("button").click(function(){
                $.ajax(
                {
                type: "POST",
                url: "database.php", //Should probably echo true or false depending if it could do it
                data : formdata,
                success: function(feed) {
                  if (feed!="true") {
                     // DO STUFF
                  } else {
                    console.log(feed);
                     // WARNING THAT IT WASN'T DONE
                  }
                }}}

</script>

</head>

<body>

<table width="100%" style="margin-top: 10%;">
        <tr>
        <td align="center" valign="middle">
        <table width="240" height="240" style="border: 1px solid #cccccc; padding: 0px;" cellpadding="0" cellspacing="0">
        <tr>
        <td align="center" valign="bottom" height="175" colspan="2">
<!-- removed $(if chap-id) $(endif)  around OnSubmit -->
                <form name="login" action="<?php echo $linkloginonly; ?>" method="post" onSubmit="return doLogin()" >
                        <input type="hidden" name="dst" value="<?php echo $linkorig; ?>" />
                        <input type="hidden" name="popup" value="true" />

                        <table width="100" style="background-color: #ffffff">
                                <tr><td align="right">login</td>
                                <td><input style="width: 80px" name="username" type="text" value="<?php echo $username; ?>"/></td>
                                </tr>
                                <tr><td align="right">password</td>
                                <td><input style="width: 80px" name="password" type="password"/></td>
                                </tr>
                                <tr><td align="right">Postcode</td>
                                <td><input style="width: 80px" name="postcode" type="text" /></td>
                                </tr>
                                <tr><td align="right">Email</td>
                                <td><input style="width: 80px" name="email" type="text" /></td>
                                </tr>
                                <td><button><input type="submit" value="OK" /></button></td>
                                </tr>
                        </table>
                </form>
        </td>
        </tr>
        </table>

        </td>
        </tr>
</table>

<script type="text/javascript">
<!--
  document.login.username.focus();
//-->
</script>
</body>
</html>

and called file database.php is as follows:

<?php 

if ((isset($_POST['postcode'])) && (isset($_POST['email']))) {

   $postcode = $_POST['postcode'];
   $email = $_POST['email'];

  $connect= new mysqli_connect('xx','xx','xx','xx');


  if ($conn->connect_errno) {
    echo "There was a problem connecting to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error;
  }

  if (!($sql = $conn->prepare("INSERT INTO visitors(postcode,email) VALUES(postcode,email)"))) {
    echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
  }

  //NOTE: the "ss" part means that $postcode and $email are strings (mysql is expecting datatypes of strings). For example, if $postcode is an integer, you would do "is" instead.

  if (!$sql->bind_param("ss", $postcode, $email)) {
    echo "Binding parameters failed: (" . $sql->errno . ") " . $sql->error;
  } 


  if (!$sql->execute()) {
    echo "Execute failed: (" . $sql->errno . ") " . $sql->error;

  } 


} else {

  echo 'Variables did not send through ajax.'; // any echoed values would be sent back to javascript and stored in the 'response' variable of your success or fail functions for testing.

}

?>

Still I get nothing fed through from the form to the database. Even if I swap the variables for strings I get nothing through to the database however if I run database.php separately it works. Surely Im close to getting this working now .. any help appreciated and thanks so much for the assistance provided so far.

*************************** ORIGINAL QUESTION FOLLOWS *******************

I have a simple form as follows:

       <form name="login" action="somethingelse.php" method="post" onSubmit="return doLogin()" >
                <input type="hidden" name="dst" value="<?php echo $linkorig; ?>" />
                <input type="hidden" name="popup" value="true" />

                <table width="100" style="background-color: #ffffff">
                        <tr><td align="right">login</td>
                        <td><input style="width: 80px" name="username" type="text" value="<?php e$
                        </tr>
                        <tr><td align="right">password</td>
                        <td><input style="width: 80px" name="password" type="password"/></td>
                        </tr>
                        <tr><td align="right">Postcode</td>
                        <td><input style="width: 80px" name="postcode" type="text" /></td>
                        </tr>
                        <tr><td align="right">Email</td>
                        <td><input style="width: 80px" name="email" type="text" /></td>
                        </tr>
                        <td><button><input type="submit" value="OK" /></button></td>
                        </tr>
                </table>
        </form>

Because I need to use the form action to do something else, I need to use jQuery on the click of the button to send data to a database. Specifically the postcode and email address taken from the form. The part of the code relating to the jQuery is shown below:

<script  language="JavaScript" >

$(document).ready(function(){
    $("button").click(function(){

mysqli_query();

});
});
</script>

The called function mysqli_query is declared via an include statement and therefore lives in a different file. The function called is shown below:

mysqli_query( $connect, "INSERT INTO visitors(postcode,email) VALUES(postcode,email)");

I have been going round in circles for days with this. I know Im close to making it work but cant quite cross the finish line. Could somebody please point out what I'm doing wrong here?

Paula Livingstone
  • 1,175
  • 1
  • 12
  • 21
  • `VALUES(postcode,email)` is that pseudo code? – Funk Forty Niner Oct 05 '17 at 15:24
  • 1
    you also have `mysqli_query();` inside script tags; that won't work. – Funk Forty Niner Oct 05 '17 at 15:25
  • 2
    Do you realize PHP runs on server and JavaScript in the browser, they do not work at the same time? You need to post a form or make an Ajax request to the server to run the PHP code. – epascarello Oct 05 '17 at 15:25
  • 2
    You're attempting to call a PHP function from within Javascript, if I'm interpreting this correctly. PHP lives on your server, Javascript on your client. You're going to have to handle this through some kind of API or background web HTTP request for it to work as you intend. – Grady Phillips Oct 05 '17 at 15:26
  • why not using the action="required_page" in PHP ?? if u want to pass data to another page then use ajax request to do so – Sifat Haque Oct 05 '17 at 15:30
  • Could you please tell us exactly how you include that different file where `mysqli_query()` lives? And what file extension does that file have? – Binarus Oct 05 '17 at 15:44
  • Code like this, where there's rampant confusion of concerns, is why [development frameworks](http://codegeekz.com/best-php-frameworks-for-developers/) exist. They'll show you a way of organizing your code better, will steer you towards solutions by employing patterns, and generally keep you on the path to success instead of leaving you to your own devices. They come in many forms from the very light-weight [Fat-Free Framework](https://fatfreeframework.com/) to the far more comprehensive [Laravel](http://laravel.com/), and all shades between. – tadman Oct 05 '17 at 17:08
  • 1
    Note: The object-oriented interface to `mysqli` is significantly less verbose, making code easier to read and audit, and is not easily confused with the obsolete `mysql_query` interface. Before you get too invested in the procedural style it’s worth switching over. Example: `$db = new mysqli(…)` and `$db->prepare("…”)` The procedural interface is an artifact from the PHP 4 era when `mysqli` API was introduced and should not be used in new code. – tadman Oct 05 '17 at 17:08

4 Answers4

3

WARNING: Never ever trust user input, always sanitize the input first AND use prepared statements otherwise, you're leaving youself vulnerable to SQL INJECTION ATTACKS

You're mixing up, Javascript is a clientside language, and mysqli is a PHP based function on the serverside of things.

What you should be doing is an ajax call with the values to a different PHP file that will make the database connection and insert the data.

var dataString = "postcode="+ postcode+"&email="+email;
$.ajax({
type: "POST",
url: "file_that_does_the_work.php", //Should probably echo true or false depending if it could do it
data: dataString,
success: function(feed) {
  if (feed=="true") {
     // DO STUFF
  } else {
    console.log(feed);
     // WARNING THAT IT WASN'T DONE
  }
}

file_that_does_the_work.php

<?
include("config.php"); // your thing that configures the connection
$postcode = sanitizationfunction($_POST["postcode"]);
$email = sanitizationfunction($_POST["email"]);
$query = $connection->prepare('INSERT INTO visitors(postcode,email) VALUES(?,?)');
$query->bindParam(1, $postcode);
$query->bindParam(2, $email);
if ($query->execute()) {
  echo "true";
} else {
  echo "false";
}
?>
LordNeo
  • 1,195
  • 1
  • 8
  • 21
  • 1
    Not my DV but [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 Oct 05 '17 at 15:33
  • that's why i'm leaving the sanitization at viewer's discretion with "sanitizationfunction". There is a lot more that can be done to improve the SQL part, but i think is not part of the question or what's requested. – LordNeo Oct 05 '17 at 15:35
  • True, but you should at least warn them. – Jay Blanchard Oct 05 '17 at 15:36
  • @JayBlanchard despite i feel it like a waste, there is the warning. honestly if he is mixing up clientside with serverside, i doubt it will do any difference in the final proyect. Most probably will try to copy/paste the code and get errors of "sanitizationfunction not defined" lol – LordNeo Oct 05 '17 at 15:40
  • 1
    Maybe so, but you've also taught the OP something. This stems from the disccusions on Meta: "If you post an answer without prepared statements [you may want to consider this before posting](http://meta.stackoverflow.com/q/344703/). Additionally [a more valuable answer comes from showing the OP the right method](https://meta.stackoverflow.com/a/290789/1011527)." – Jay Blanchard Oct 05 '17 at 15:45
1

form.php

<table width="100" style="background-color: #ffffff">
        <tr><td align="right">login</td>
        <td><input style="width: 80px" name="username" type="text" value="<?php echo $username?>"/>
        </tr>
        <tr><td align="right">password</td>
        <td><input style="width: 80px" name="password" type="password"/></td>
        </tr>
        <tr><td align="right">Postcode</td>
        <td><input style="width: 80px" name="postcode" type="text" /></td>
        </tr>
        <tr><td align="right">Email</td>
        <td><input style="width: 80px" name="email" type="text" /></td>
        </tr>
        <td><input type="submit" value="OK" /></td>
        </tr>
</table>
</form>

`

somethingelse.php

<?php foreach ($_POST as $key => $value) { echo $key."=".$value."<br/>"; } ?>

I leave connectivity part to you :D

Premkumar chalmeti
  • 800
  • 1
  • 8
  • 23
1

So, as others have pointed out, you are mixing up your client-side code and your server-side code. You need to send all the form data to a php file. The jquery ajax will send the data over to the script, and determine if this call was successful or not. If the call is not successful, you can run test logic. If it is, than you can do other logic, such as alert the user of a successful form submit.

Below is an example of the process:

ajax:

<script>

  var formData = 'some data' // Get your form values and save here - postcode and email

  $("button").click(function(){
    $.ajax ({
        method: 'POST',// you can do either post or get...
        url: "page_to_handle_mysql_code.php",
        data: formData
        success: function( response ) {
           //do something like alert("Submitted Successfully!");
        }
        fail: function( response) {
          //Do testing such as console.log(response); NOTE: Response will be what ever your php page sends back.
        }

      });
  )};

</script>

On your php page: page_to_handle_mysql_code.php

<?php 

if ((isset($_POST['postcode'])) && (isset($_POST['email']))) {

   $postcode = $_POST['postcode'];
   $email = $_POST['email'];

  //connect to mysql - I prefer prepared statements as the variables are prepared for safety when sent to MySQL

  $conn = new mysqli($servername, $username, $password, $dbname);//you can either put the actually values in, or I include another php page in this one that sets my variables so I can resuse my code easily.


  if ($conn->connect_errno) {
    echo "There was a problem connecting to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error;
  }

  if (!($sql = $conn->prepare("INSERT INTO visitors(postcode,email) VALUES(?,?)"))) {
    echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
  }

  //NOTE: the "ss" part means that $postcode and $email are strings (mysql is expecting datatypes of strings). For example, if $postcode is an integer, you would do "is" instead.

  if (!$sql->bind_param("ss", $postcode, $email)) {
    echo "Binding parameters failed: (" . $sql->errno . ") " . $sql->error;
  } 


  if (!$sql->execute()) {
    echo "Execute failed: (" . $sql->errno . ") " . $sql->error;

  } 


} else {

  echo 'Variables did not send through ajax.'; // any echoed values would be sent back to javascript and stored in the 'response' variable of your success or fail functions for testing.

}

?>

This should help you get your values entered to MySQL. I hope it helps!

rdimouro
  • 225
  • 1
  • 4
  • 17
-1

You can submit a form with jquery

mysqli_query is a function in your PHP, your javascript doesn't have access to the function. You have to make an http call from your javascript, which your PHP will receive and run mysqli_query on its end

TKoL
  • 13,158
  • 3
  • 39
  • 73
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. – Jay Blanchard Oct 05 '17 at 15:33