Jump to content

Clicking on cancle do not insert data into a database


Recommended Posts

Hello guys. I am new here. Well, I have some codes written in php. And I have several forms (insert, update etc.).

And I have that confirmation box written in Java Script.

The thing is next: when I click on submmit in my insert form the box shows up and when I click on OK the data is submmited in the database, but when I click on CANCLE the data is submmited too and I do not want that.

Can anybody helps me please???

 

THIS IS MI INSERT CODE.

 

<?php
$con=mysqli_connect("localhost","root","","");
// Provjeri konekciju
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Varijable za sigurnost
$naziv_artikla = mysqli_real_escape_string($con, $_POST['naziv_artikla']);
$cijena_artikla = mysqli_real_escape_string($con, $_POST['cijena_artikla']);
$na_stanju = mysqli_real_escape_string($con, $_POST['na_stanju']);
// Sql upit za insert novih podataka u bazu
$sql="INSERT INTO artikli (naziv_artikla, cijena_artikla, na_stanju)
VALUES ('$naziv_artikla', '$cijena_artikla', '$na_stanju')";
// Provjera upita
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo header ("Location: index1.php");
mysqli_close($con);
?>
THIS IS CONFIRMATION BOX (JAVA SCRIPT).
<script>
function myFunction() {
var x;
if (confirm("Da li želite da sačuvate promjene?") == true) {
x = "You pressed OK!";
} else {
x = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = x;
}
</script>

 

Link to post
Share on other sites

Keep it in mind that your javascript code simply asks if he is sure that he wants to save some changes, and if so, javascript will output text that he pressed ok, and if not, javascript will output that he pressed cancel. But, what does that mean? It means nothing. PHP code don't know if someone pressed cancel or not. Javacsript is executed on client side (web browser), while PHP is executed on server side(some remote computer that stores website). First thing that I have notices is that you don't have die function if the mysql connection is not successful. You said, echo the result of not being able to connect but that won't stop the php to continue through.

 

Instead of this:

$con=mysqli_connect("localhost","root","","");// Provjeri konekcijuif (mysqli_connect_errno()) {  echo "Failed to connect to MySQL: " . mysqli_connect_error();}

Use this way:

$con=mysqli_connect("localhost","root","","");// Provjeri konekcijuif (!$con) {  die("Failed to connect to MySQL: " . mysqli_connect_error());}

Now, let's think of this more logical. If the user clicks submit button it is quite logical that he want to insert data into database. BUT, before that, I don't see any database in your code selected. After the connection was successful , you should connect to some database:

mysqli_select_db($con,'Database Name');

When this is done, user can access database to insert data into. Let's assume he clicked on the button with a name of "ButtonName", we want to check if that happened after all and we do so like this:

if(isset($_POST['ButtonName'])) {   //DO YOUR SQL CODE HERE AND ALL RELATED TO INTERACTION WITH DB} else {   //YOU CAN SET WHAT WILL HAPPEN IF BUTTON WAS NOT SET, IF NEEDED}

You see, now when user clicks the button, something will happen, until then, code won't be executed.

Link to post
Share on other sites

There is no selected database because I have removed it. I have a database called sifrarnik. And I do not understand your reply, because I am not looking for that answer.

 

 

Well, do I need write an if condition or something in my Java Script code???

 

I told u, when I click on OK the data is submmited in a database and when I click CANCLE a data is submmited into a database too. I want when I click on CANCLE that nothing is submmited.. That is a point....

Edited by ale
Link to post
Share on other sites

As I have told you, When you click your button, it does more than javascript, it goes to submit and add data into database. The javascript itself that you created, simply do what you told her to do and after that, php to the server job. There is no relation between two of them.

Link to post
Share on other sites

on submit of the form (using onsubmit="return myFunction()") for cancellation confirmation should return false; else true for it to carry on, but because this confirmation is reliant on JavaScript being enabled, you should check it as suggested using php to cover all bases.

Link to post
Share on other sites

It seems you're using two buttons in the markup: one for 'submit' and the other for 'cancel. You can add an onclick function to the cancel button that sends an AJAX query to the post destination to check the database and reverse the last update.Your PHP code can set a variable, say $prev_data, to the previous state of the data in the MySQL database before updating it with new data. If the user, after submitting the update completely, decides it was a mistake, the 'cancel' button sends an AJAX request; the PHP code tests the request for a condition then updates the database with the data in $prev_data.I hope this makes sense a little.

  • Like 1
Link to post
Share on other sites

Grrrr... I am not good with the AJAX.. I am the beginner :)

 

yes I have two buttons... One for submmit and one for the cancelation written directly in my js confirmation box... Here is the code:

 

Java Script confirmation box code:

 

<script>
function myFunction() {
var x;
if (confirm("Da li želite da sačuvate promjene?") == true) {
x = "You pressed OK!";
} else {
x = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = x;
}
</script>

 

I know that this is a simple js function.. Do I need make some changes here (write an AJAX into this js code)???
Link to post
Share on other sites

Try this:

 

<script>function myFunction() {    var x;    if (confirm("Da li želite da sačuvate promjene?") == true) {        x = "You pressed OK!";    } else {        return;    }    document.getElementById("demo").innerHTML = x;}</script>

Or this:

<script>function myFunction() {    var x;    if (confirm("Da li želite da sačuvate promjene?") == true) {        x = "You pressed OK!";    } else {        break;    }    document.getElementById("demo").innerHTML = x;}</script>
Link to post
Share on other sites

Try this:

<script>function myFunction() {    var x;    if (confirm("Da li želite da sačuvate promjene?") == true) {        x = "You pressed OK!";    } else {        return;    }    document.getElementById("demo").innerHTML = x;}</script>
Or this:
<script>function myFunction() {    var x;    if (confirm("Da li želite da sačuvate promjene?") == true) {        x = "You pressed OK!";    } else {        break;    }    document.getElementById("demo").innerHTML = x;}</script>
I think he wants to provide a remedy for mistakes in form submission. He can do it by form or by AJAX. I'm not good at this but I may provide pseudocode instead. Edited by Jonathanks
Link to post
Share on other sites

Grrrr... I am not good with the AJAX.. I am the beginner :) yes I have two buttons... One for submmit and one for the cancelation written directly in my js confirmation box... Here is the code: Java Script confirmation box code: <script>function myFunction() { var x; if (confirm("Da li želite da sačuvate promjene?") == true) { x = "You pressed OK!"; } else { x = "You pressed Cancel!"; } document.getElementById("demo").innerHTML = x;}</script> I know that this is a simple js function.. Do I need make some changes here (write an AJAX into this js code)???

You want to reverse an accidental submission to a database, correct? That's what my suggestion is intended to address.The code above does not interact with the server. Most likely, it will be helpful in confirming form submission. If the user clicks 'ok', the request proceeds, else it fails. And the buttons aren't what I meant: they're JavaScript dialog buttons, not HTML.You can do it without AJAX.Did you understand my suggestion?
Link to post
Share on other sites

The problem is the insert is carried out before JavaScript even loads.

 

What you want to do is place the submitted information in a form with disabled inputs or hidden fields, the php should be prevented from running UNTIL this form been submitted by checking for form name or hidden input that will confirm this has been submitted by conformation form.

This is how it will work

(1) Retrieves $_POST but this $POST does NOT contain $_POST of specific name saying this current form has not been submitted. so it displays confirmation details or just confirm button but these must be within a form.

(2)The confirm button is pressed, IF 'OK' you force the form to be submitted, the form submits to itself, the specific $_POST[] named field tells us it has been submitted from itself , the form is hidden, and the insert php code is allowed to proceed.

(3)The confirm button is pressed, IF 'Cancel' you receive message alert() or display that insert of current details has been cancelled, the form does not submit and you do redirect or whatever.

Link to post
Share on other sites

Single page

<?php$con=mysqli_connect("localhost","root","","");// Check connectionif (mysqli_connect_errno()) {    echo "Failed to connect to MySQL: " . mysqli_connect_error();}?><!DOCTYPE html><html>    <head>        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">        <meta name="viewport" id="viewport" content="target-densitydpi=high-dpi,initial-scale=1.0,user-scalable=no" />        <title>http://w3schools.invisionzone.com/index.php?showtopic=53472</title>         <script type="text/javascript">            function myFunction() {                var x = document.getElementById('myform');                if (confirm("Da li želite da sačuvate promjene?") == true) {                    x.action = "http://localhost/web_testing/php_test/submittoself.php?success=true"   /*enter url to this form with query string at end*/                    return true;                } else {                    window.location = "http://localhost/web_testing/php_test/submittoself.php?success=false"  /*enter url to this form with query string at end*/                    return false;                }            }        </script>        <style type="text/css">        </style>    </head>    <body>        <?php        if (isset($_POST['insert_form']) && !empty($_POST['naziv_artikla']) && !empty($_POST['cijena_artikla']) && !empty($_POST['na_stanju'])) {            $naziv_artikla = mysqli_real_escape_string($con, $_POST['naziv_artikla']);            $cijena_artikla = mysqli_real_escape_string($con, $_POST['cijena_artikla']);            $na_stanju = mysqli_real_escape_string($con, $_POST['na_stanju']);            $sql = "INSERT INTO artikli (naziv_artikla, cijena_artikla, na_stanju)VALUES ('$naziv_artikla', '$cijena_artikla', '$na_stanju')";            if ($con->query($sql) === TRUE) {                echo "New record created successfully";            } else {                echo "Error: " . $sql . "<br>" . $con->error;            }            $con->close();        }        ?>        <form name="myform" id="myform" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" onsubmit="return myFunction();">            naziv_artikla: <input type="text" value="" name="naziv_artikla"><br/>            cijena_artikla: <input type="text" value="" name="cijena_artikla"><br/>            na_stanju: <input type="text" value="" name="na_stanju"><br/>            <input type="submit" name="insert_form" value="Submit and add record">        </form>        <?php        if (isset($_GET['success']) && $_GET['success'] === 'true') {            echo "You pressed OK!";        } elseif (isset($_GET['success']) && $_GET['success'] === 'false') {            echo "You pressed Cancel!";        }        ?>    </body></html>
Link to post
Share on other sites

Single page

<?php$con=mysqli_connect("localhost","root","","");// Check connectionif (mysqli_connect_errno()) {    echo "Failed to connect to MySQL: " . mysqli_connect_error();}?><!DOCTYPE html><html>    <head>        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">        <meta name="viewport" id="viewport" content="target-densitydpi=high-dpi,initial-scale=1.0,user-scalable=no" />        <title>http://w3schools.invisionzone.com/index.php?showtopic=53472</title>         <script type="text/javascript">            function myFunction() {                var x = document.getElementById('myform');                if (confirm("Da li želite da sačuvate promjene?") == true) {                    x.action = "http://localhost/web_testing/php_test/submittoself.php?success=true"   /*enter url to this form with query string at end*/                    return true;                } else {                    window.location = "http://localhost/web_testing/php_test/submittoself.php?success=false"  /*enter url to this form with query string at end*/
Won't this code perform the database insert even if success=false?It seems testing for success before the connection to database satisfies his request.Maybe by adding && $_GET['success'] == 'true'to the if condition in the first segment of php will be good.
Link to post
Share on other sites

No! Because the form never gets submitted, when not submitted as POST it never recieves specific $_POST['insert_form'] to allow it to INSERT, it would only have permission to only show form, the INSERT part is never accessed. It does a redirect with get query string with false to show no insert mezsage

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...