0

I'm traying to update data into mysql database using a javascript function.When I click on a label, this function would call an other function in php to do updating this data. if I click on a label the code would do the stuff. Can you help me please?

I've tried to insert data in my sql table phone by calling publicatePhone php function but no data inserted. here is my code:

**Javascript function:

function answer1yes(clicked) {

    var s = document.getElementById("answer1oui").checked;

    if (s = "true"){

    <?php include('functions.php'); ?>

    var x="<?php publicatePhone(); ?>";

    alert(x);

    return false;

    }else{

        alert('not checked');

    }
}

** The file functions.php:

<?php function publicatePhone(){

$con=mysql_connect("localhost","root","hihi51978");

mysql_select_db("script_database2");

//$publicate = "INSERT INTO phone (phone_number, publicate_number) VALUES 
('212661132084', 'yes')";

$publicate = "UPDATE phone SET publicate_number = 'yes' WHERE 

phone_number='212661132084'";

$publicate_result = mysql_query($publicate);

if ($publicate_result==true){echo 'request executed successfelly';} 

else {echo 'request not executed';}

}

?>

**The form:

<div id="answer1"style="margin: 20%;">

Show my phone number on website's result:

<form action="<?php $_SERVER['PHP_SELF'];?>" method="post" />

<p><label name="labelyes" style="background-color: #035d54; padding: 6px 

30px 6px 30px; border-radius: 35px;" onclick="Javascript:answer1yes()" > 

<input style="display: none;" type="radio" id="answer1oui" name="question1"

value="yes">Yes</label><p>

</form>

</div>

The code show "request executed successfelly" but the request not updating my phone table

H.mo
  • 11
  • 7
  • Possible duplicate of [What is the difference between client-side and server-side programming?](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – Robin Zigmond Dec 22 '18 at 11:07

3 Answers3

0

So, your problem is that $publicate_result seems to be true but it didn't update the SQL-table correctly (or not at all)?

If that's the case: What id the actual value of $publicate_result? Maybe it has an error value in it, which PHP type converts into true, because the variable is not empty.

What's does it say when you echo your variable $publicate_result?

(You can try

echo var_dump($publicate_result);

to get more information about the variable's value)

Senfti
  • 16
  • 2
  • no thing saying when I add echo var_dump($publicate_result); – H.mo Dec 22 '18 at 11:53
  • Please whey when the page loaded I see that the Function php publicatePhone executed automatically without clicking on the label "labelyes" and than without calling the Javascript function "answer1yes(clicked)" ? – H.mo Dec 22 '18 at 12:16
0

I mean I think the most common practise to call a PHP function via Javascript is to use XMLHttpRequests and that's also that I would recommend.

It works like that:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       // Typical action to be performed when the document is ready:
       document.getElementById("demo").innerHTML = xhttp.responseText;
    }
};
xhttp.open("GET", "filename", true);
xhttp.send();

Source: https://www.w3schools.com/xml/xml_http.asp

Of if you want to use jQuery (which i recommend when using XMLHttpRequests) the syntax to perform an XMLHttpRequest is a lot simpler:

$.ajax({
    type: 'POST',
    url: 'yourfile.php',
    data: {
        // someData
    },
    success: (data) => {
        // Code that will be executed after a successful
        // finish of the request

        // data: stuff that was echoed in PHP
    },
    error: (xhr, status, error) => {
        // Code that will be executed after a non successful
        // finish of the request

        // This line will display an error to your console,
        // which holds the PHP-error-code
        console.error(xhr.responseText);
    }
});

Source: https://jquery.com/

Note that when you are perfoming an XMLHttp- or Ajax-Request (which is basically the same in simple terms) it is asynchronous which means, that the code after the $.ajax() command will be executed right afterwards, even if the request has not finished yet.

So if you want to execute code right after the request has finished, you have to place the code inside of the success or error callback-function.

If you would like to see a more specific example of how to use Ajax-requests in your case, just ask.

Kind regards

Senfti
  • 16
  • 2
  • Yes I would like to see a more specific example of how to use Ajax-requests in my case please. – H.mo Dec 22 '18 at 12:32
0

Alright, so that's how I would aproach something like that:

form.html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script src="form.js"></script>
    <title>Form</title>
</head>
<body>
    <div id="answer1" style="margin: 20%;">
        Show my phone number on website's result:
        <!-- You only need a "post" and "action" attribute when you are -->
        <!-- submitting this form with an: <input type="submit" value=""> -->
        <form>
            <button onclick="showPhoneNumberOnResults(true)">yes</button>
            <button onclick="showPhoneNumberOnResults(false)">no</button>
        </form>
</body>
</html>

form.js:

function showPhoneNumberOnResults(answer) {
    if (answer) {
        alert('Show number');
        $.ajax({
            type: 'POST',
            url: 'process_answer',
            data: { answer: answer },
            success: (date) => console.log(data),
            error: (xhr, status, error) => console.error(xhr.responseText)
        });
    } else {
        alert('Don\'t show number');
    }
}

This (parameter) => { statements } thing is something called "lambda expression", which is just a short form of writing functions.

process_answer.php:

<?php

require_once 'database_connect.php';

$dbConnection->query(/* insert your UPDATE statement */);

database_connect.php:

<?php

$HOST = 'localhost';
$DATABASE = 'script_database2';
$USER = 'root';
$PASSWORD = 'hihi51978';

try {
    $dbConnection = new PDO('mysql:host='.$HOST.';dbname='.$DATABASE, $USER, $PASSWORD);
    // set the PDO error mode to exception
    $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

What I'm using here is PDO. It simply provides an interface where you can work with every different databases, not just mysql. You can read more about it here: http://php.net/manual/en/intro.pdo.php.

Yea and btw, I think the word you want to use is "publish" instead of "publicate". :P

Christmassy regards.

Senfti
  • 16
  • 2