1

I'm trying to update the two locked textboxes with information that I get from my database. I enter a phone number in the "Telefon" checkbox, and I want it to get the firstname and lasttname for that phone number. Which works by the way, but it's not the way I want it. I want the information to be automatically put into the textboxes without refreshing the page. and for some odd reason my code got split in two here. I've tried to look for a solution for hours. I'm very new to coding, and I would love some help!

<?php
SESSION_START();


$output = NULL;


if(isset($_POST['btn_checkTelefon'])) {

    require 'connectdb.php';

    $telefon_Search =  $connect_DB->real_escape_string($_POST['telefon_Search']);
    $sql = "SELECT * FROM elever WHERE Telefon = '$telefon_Search'";
    $resultSet = $connect_DB->query($sql); 

    if($resultSet->num_rows > 0) {
        while($rows = $resultSet->fetch_assoc()) {
            $fornavnoutput_Database = $rows['Fornavn'];
            $etternavnoutput_Database = $rows['Etternavn'];

        }   

    echo '<script type = "text/javascript">';

        echo 'function sayHi() {';
        echo 'val1 = document.getElementById("telefon_Input").value;';
        echo 'if(val1 == "") {';
        echo '  alert("Vennligst skriv inn ditt telefon nummer!");';
        echo '}';
        echo 'if(val1 !== "") { ';
        echo '  document.getElementById("check_Fornavn").value = "<?php echo $fornavnoutput_Database?>";';
        echo '  document.getElementById("check_Etternavn").value = "<?php echo $etternavnoutput_Database?>";';
        echo '}';
        echo '}';

    echo '</script>';
    } else {
        $output = "No results";
    }
}

$fornavnoutput_Database2 = "Fornavn";
$etternavnoutput_Database2 = "Etternavn";
?> 



  <!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="style2.css?<?php echo time(); ?>" />
        </script> 
    <script type = "text/javascript"></script>
    <title></title>

</head>
<body>
    <?php
        include 'connectdb.php';
    ?>
     <form name="form1" action="">


        <table id="valgt_skap_tabell" class="bokssvartabell">
            <tr>
                <td>Valgt skap</td>
            </tr>
            <tr>
                <td>
                    <input class="bokssvarskjema" type="text" name="Valgt skap" disabled value= <?php
                        if(isset($_POST["radios"])){
                            echo $_POST["radios"];
                        } else {
                            //header('location: index.php');
                        }   ?>>
                </td>
            </tr>
        </table>

        <table id="telefon_tabell" class="bokssvar_tabell">
            <tr>
                <td>Telefon:</td>
            </tr>
            <tr>
                <td><input type="text" name="telefon_Search" id="telefon_Input" maxlength=8"><br></td>
            </tr>
            <tr>
                <td><button type="button" name ="btn_checkTelefon" id="sjekkTelefon" onclick = "sayHi()">Sjekk</button></td>
            </tr>
            <div id="d1"></div>
        </table>

        <table id="opplysninger_tabell" class="bokssvartabell">
            <tr>
                <td>Fornavn:</td>
                <td>Etternavn:</td>
            </tr>
            <tr>
                <td><input type="text" name="Fornavn" disabled id="check_Fornavn"></td>
                <td><input type="text" name="Etternavn" disabled id="check_Etternavn"></td>
            </tr>
        </table>
    </form>

    <?php echo $output; ?>


</body>

NIDOIT
  • 45
  • 6
  • U have to use `jQuery $.post ()` function – JuZer Mar 04 '16 at 11:44
  • 1
    You have to use ajax to achieve this.. – Divyesh Savaliya Mar 04 '16 at 11:45
  • Possible duplicate of [Submit form without page reloading](http://stackoverflow.com/questions/2866063/submit-form-without-page-reloading) –  Mar 04 '16 at 12:30
  • try getting values with ajax. – yogihosting Mar 04 '16 at 12:35
  • Alright, so I believe I have to use jQuery, but I have no idea how to implement that in my code. Can anyone help me? Preferably with the names that I use for easier understanding – NIDOIT Mar 04 '16 at 13:11
  • You have all the info you need in the link provided. This question was asked over 9000 times. What you have to do is send your form via ajax call, it will result in sending your form without leaving the page where the form is. You have scripts ready waiting for you to copy paste them. What more do you need? Copy, paste, change ids/elements name and adapt it to your needs. If you have problems with code not working post it but please don't expect someone will write the code for you (although there are people who do that so you might get lucky). –  Mar 04 '16 at 13:38

2 Answers2

1

You need to use AJAX for this. Example $.ajax() -> shortcuts $.post(), $("id").load("url"), ... Look it up a lot in depth explanation about these on stackoverflow.

Please never mix JavaScript with php. Use it in separate file.

Edit: So have you fixed it yet? The easier way to load paged dynamicaly is with load method + actions. $.post is used if you need to do something with returned data from php. I will give you example of load.

I will give a proper example how to code.

Universal function for a link that look at href value and load HTML parts (form in this case) from PHP dynamicaly to your page, you do need to implement actions or just call your ordinary page if you have only one default action there. I use jQuery library here. This script must be in separate file else it will work but you will get a sync warning in your console.

$(function() {

        $('a').on("click", function(e) {
            e.preventDefault();
            e.stopPropagation();
            var URL = $(this).attr('href');
            $('body').load(URL, 'form');
        })

})

php example prefered showsomethingfunction in separate file like showfunctions.php

function myLinks() {
    echo "<a href='index.php?action=showsomething'>showsomething</a>"
}

index.php + included showfunctions.php

<?php
    myLinks();
    if(isset($_GET["action"]){
     // do your ordinary thing like open connection with database.
    switch($_GET["action"]))
    {
    case "showsomething":
     //show showsomething() function with html
    break;

//further you can add more action instead of showsomething if you have several links

    }
    //close database.
    }
?>

You need to separate your code else it will be a mess if it gets even more complicated. HTML code must be ONLY in showfunctions.php for example in function to call for actions.

Code is not tested but I think it will work. This code will also work without javascript but then it will just reload pages.

PVL
  • 577
  • 1
  • 3
  • 12
  • Do I have to remove all the echoed javascript in my code? Or can i keep everything as it is, and just add AJAX? – NIDOIT Mar 04 '16 at 11:53
  • @Nniouz You will need to use json_encode in order to send that data to javascript. or You can just use load instead of post and leave how it's – PVL Mar 04 '16 at 11:54
  • One second I will try to make universal function for for php – PVL Mar 04 '16 at 11:56
  • Would you have time to look over my code and edit it so it would be simpler for me to understand? Because I honestly have no clue what to do here. I've been stuck for several days, haha – NIDOIT Mar 04 '16 at 11:57
  • I leave it to ZeJur :P you could use load instead of post if you had actions in your code for particular snipets of code like this if($_GET["index.php?action"]). – PVL Mar 04 '16 at 12:08
  • @PVL, very interesting approach ) – JuZer Mar 05 '16 at 06:52
0

You have to use jQuery $.post() for that.

first You have to create php file which will process Your data.

For example lets create file query.php with the following content:

<?php
if(isset($_POST['telefon_Search'])) {
    require 'connectdb.php';
    $telefon_Search =  $connect_DB->real_escape_string($_POST['telefon_Search']);
    $sql = "SELECT * FROM elever WHERE Telefon = '$telefon_Search'";
    $resultSet = $connect_DB->query($sql);

    if($resultSet->num_rows > 0) {
        $row = $resultSet->fetch_assoc();
        echo json_encode($row);
    }
}

next on Your page You have to create function which will send phone number to our query.php file and which will return Name and Surname if they exist.

$('#sjekkTelefon').click(function (){    
        $.post('query.php', { telefon_Search : $('#telefon_Input').val() }, function (data){
            var user = $.parseJSON(data);
            $('#check_Fornavn').val(user.Fornavn);
            $('#check_Etternavn').val(user.Etternavn);
        });
    });

and complete html will looks like:

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="style2.css?<?php echo time(); ?>" />
    <title></title>
</head>
<body>
    <table id="telefon_tabell" class="bokssvar_tabell">
        <tr>
            <td>Telefon:</td>
        </tr>
        <tr>
            <td><input type="text" name="telefon_Search" id="telefon_Input" maxlength=8"><br></td>
        </tr>
        <tr>
            <td><button name ="btn_checkTelefon" id="sjekkTelefon">Sjekk</button></td>
        </tr>
        <div id="d1"></div>
    </table>
    <table id="opplysninger_tabell" class="bokssvartabell">
        <tr>
            <td>Fornavn:</td>
            <td>Etternavn:</td>
        </tr>
        <tr>
            <td><input type="text" name="Fornavn" disabled id="check_Fornavn"></td>
            <td><input type="text" name="Etternavn" disabled id="check_Etternavn"></td>
        </tr>
    </table>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
    $('#sjekkTelefon').click(function (){    
        $.post('query.php', { telefon_Search : $('#telefon_Input').val() }, function (data){
            $('#check_Fornavn').val(data.Fornavn);
            $('#check_Etternavn').val(data.Etternavn);
        });
    });
</script>
</body>
</html>
JuZer
  • 775
  • 2
  • 7
  • 14
  • It has to be a button type, not submit. Otherwise my other elements do not work. Anyway, where do I put this code? – NIDOIT Mar 04 '16 at 12:06
  • I'm sorry, but I'm absolutely hopeless.. Where do I put all this? And if possible, could you use the same format and names, that I use? – NIDOIT Mar 04 '16 at 12:18
  • Thanks for your effort, but I have no idea where to put all this. If you'd like I could archive all my files, and post a link? – NIDOIT Mar 04 '16 at 13:42
  • In 10 min I'll give u complete solution. – JuZer Mar 04 '16 at 13:50
  • Sorry for late reply. But have you tested this? And it works for you? I cant get it to work. I get no errors, but absolutely nothing is happening when i click the button. I've read through the code multiple times, but I cant seem to understand what is wrong. – NIDOIT Mar 08 '16 at 08:18
  • @Nniouz, yes it's working example. Ok, u can share the link with ur files. I'll check where is ur mistake. – JuZer Mar 08 '16 at 13:25
  • Thank you, I honestly have no Idea what's wrong..http://www.filedropper.com/submitformwithoutpagereloading – NIDOIT Mar 11 '16 at 07:37
  • @Nniouz, I've updated my answer. I forgot to `parse json` that's why it was not working! Sorry for that! – JuZer Mar 11 '16 at 16:47