0

I'm trying to load a response from the php onto the same page. My Client side html looks like this.

<p>
    <script type="text/javascript">// <![CDATA[
        function sendForm() {
            var dataSend = "?ClientName=" + $("#ClientName").val();

            $.post("AddClient.php", dataSend, function(data) {
                $("#responseDiv").html(data);
            });
    // ]]></script>
</p>
<div id="responseDiv"> </div>
<form action="AddClient.php" onsubmit="sendForm()">
    <h1>Client Wizard <span>Please fill all the texts in the fields.</span></h1>
    <label> <span>Client Name :</span> <input id="ClientName" type="text" name="ClientName" /> </label> <span> </span> <input class="button" type="Submit" value="Send" />
</form>

My Server side php looks like this:

<?php
$dbhost='127.0.0.1';
$dbuser='name';
$dbpass='password';
$dbname='dbname';
$conn=mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
if(!$conn)
{
    die('Could not connect:'.mysqli_connect_error());
}
$client=$_REQUEST["ClientName"];
$retval=mysqli_query($conn,"INSERT into client (clientid,clientname) VALUES (NULL,'$client')");
if(!$retval)
{
    die('Could not add client:'.mysql_error());
}
$display_string="<h1>Client Added Successfully</h1>";
echo $display_string;
mysqli_close($conn);
?>

Unfortunately not only is the response being shown in anew html page, Its not accepting any name typed in the form. When I check the sql table the Column has a blank entry under it. I have not been able to figure out where I'm going wrong. Any help would be really appreciated.

allicarn
  • 2,859
  • 2
  • 28
  • 47

3 Answers3

0

Forms default behavior is to redirect to the page given in the action attribute (and if it's empty, it refreshes the current page). If you want it to make a request without redirecting to another page, you need to use Javascript to intercept the request.

Here's an example in jQuery:

$('form').on('submit', function(e) {
    e.preventDefault(); // This stops the form from doing it's normal behavior
    var formData = $(this).serializeArray(); // https://api.jquery.com/serializeArray/

    // http://api.jquery.com/jquery.ajax/
    $.ajax($(this).attr('action'), {
        data: formData,
        success: function() {
            // Show something on success response (200)
        }, error: function() {
            // Show something on error response
        }, complete: function() {
            // success or error is done
        }
    });
}

Would recommend having a beforeSend state where the user can't hit the submit button more than once (spinner, disabled button, etc.).

allicarn
  • 2,859
  • 2
  • 28
  • 47
0

First off, you have a syntax error on your sendForm function. It's missing the closing bracket:

function sendForm() {
    //...
}

Next, You need to stop the form from submitting to a new page. Using your onsubmit function you can stop this. In order to do so, return false in your function:

function sendForm() {
    //...
    return false;
}

Next, you aren't actually sending any POST data to your PHP page. Your second argument of your .post method shouldn't be a query string, but rather an object (I've commented out your line of code):

function sendForm() {
    var dataSend = {ClientName:$("#ClientName").val()}

    //var dataSend = "?ClientName=" + $("#ClientName").val();

    $.post("AddClient.php", dataSend, function(data) {
        $("#responseDiv").html(data);
    });
    return false;
}

Lastly, you have got to sanitize your data before you insert it into a database. You're leaving yourself open to a lot of vulnerabilities by not properly escaping your data.

You're almost there, your code just need a few tweaks!

Samuel Cook
  • 16,620
  • 7
  • 50
  • 62
  • Thank You! This method makes more sense. Although I tried executing this and got the folloing error. 'Syntax error in template "content:content_en" on line 4 "var dataSend={ClientName:$("#ClientName").val()};" - Unexpected ":", expected one of: "}"' Could you help me out? – Martin Kumar Nov 15 '15 at 14:12
  • No Worries. I got it working now! I had a few syntax errors and I changed my onsubmit="sendForm()" to onSubmit="return false" and I included a onclick="sendForm()" part to the submit button – Martin Kumar Nov 15 '15 at 17:23
  • you never want to have a submit function attached to an `onclick` event. There are other ways of submitting forms (like hitting enter when a text input if focused) which would completely ignore your onclick method. – Samuel Cook Nov 15 '15 at 17:28
  • When I used return false at the end of my JS code my page still refreshed and redirected itself to my home page. While I get your logic and it makes perfect sense, this was the only way I could avoid that. You have any other way in which I could avoid this? – Martin Kumar Nov 15 '15 at 19:20
  • use `onsubmit="return sendForm()"` on your form. it will "submit" or not submit based on what's returned – Samuel Cook Nov 15 '15 at 20:08
0

All right. Your code have some room for improvement, but it's not an endless thing.

I saw somebody mention sanitization and validation. Alright, we got that. We can go in details here

This is how I will restructure your code using some improvements made by Samuel Cook (thank you!) and added a lot more.

index.html

<p>
    <script type="text/javascript">// <![CDATA[
        function sendForm() {
            var dataSend = {clientName: $('#clientName').val()}

            $.post("AddClient.php", dataSend, function(data) {
                $('#responseDiv').html(data);
            });

            return false;
        }
    //]]>
    </script>
</p>
<div id="responseDiv"></div>
<form action="AddClient.php" onsubmit="sendForm(); return false;">
    <h1>Client Wizard <span>Please fill all the texts in the fields.</span></h1>
    <label><span>Client Name :</span><input id="clientName" type="text" name="clientName"/><span></span><input type="submit" class="button" value="Send"></label>
</form>

Notice change in an input id and input name - it's now start with a lower case and now clientName instead of ClientName. It's look a little bit polished to my aesthetic eye.

You should take note on onsubmit attribute, especially return false. Because you don't prevent default form behavior you get a redirect, and in my case and probably your too, I've got two entries in my table with a empty field for one.

Nice. Let's go to server-side.

addClient.php

<?php

$dbhost = '127.0.0.1';
$dbuser = 'root';
$dbpass = '123';
$dbname = 'dbname';


$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if (!$conn) {
    die('Could not connect: ' . mysqli_connect_error());
}

$client=$_REQUEST["clientName"];
$client = filter_var($client, FILTER_SANITIZE_STRING);

if (isset($client)) {
    $stmt = $conn->prepare("INSERT into client(clientid, clientname) VALUES (NULL, ?)");
    $stmt->bind_param('s', $client);

    $stmt->execute();
}

if (!$stmt) {
    die('Could not add client:' . $conn->error);
}
$display_string = "<h1>Client $client Added Successfully</h1>";
echo $display_string;
mysqli_close($conn);

?>

That is going on here. We are using PHP filters to sanitize our incoming from somewhere string.

Next, we check if that variable $client even exist (you remember that twice sended form xhr? Double security check!)

Here comes a fun part - to protect our selves even more, we start using prepared mySQL statements. There is no way someone could SQL inject you somehow.

And just check for any errors and display it. Here you go. I've tested it on my machine, so it works.

Community
  • 1
  • 1
Alex Pogiba
  • 622
  • 5
  • 15