I need your help I am using Onchange in a form to submit a dropdown data to the database, but something boring when i select the data the page get refreshed, so if i was down the page then after selecting the page takes me up again before i finish the next stage on my process. So i need the help if anyone knows how can i do to stop that, that when i will select the dropdown data the page should remain without refresh it will be well and good! I think Ajax does this but im not that much aware on AJAX
Here is my codes

<html> <form action="" method="post" style="height:1px;"> 
<input name="key" type="hidden" value="<?php echo $id; ?>" /> 
<select name="Idadi"style="width:65px;" onchange="this.form.submit();"> 
<option value="1" <?php if($Idadi=="1") { echo "selected"; } ?> >1</option> 
<option value="2" <?php if($Idadi=="2") { echo "selected"; } ?> >2</option> 
<option value="3" <?php if($Idadi=="3") { echo "selected"; } ?> >3</option> 
<option value="4" <?php if($Idadi=="4") { echo "selected"; } ?> >4</option> 
<option value="5" <?php if($Idadi=="5") { echo "selected"; } ?> >5</option> 
</select> 
</form> <?php

include('dbconnection.php');
if(isset($_POST['key'])){ 
$idlogin=$_POST['key'];     
$idadi=$_POST['Idadi'];   
$idadiquery="update `itemreg` set `Idadi` = '$idadi' where `id` ='$idlogin'";
$idadiresult = mysql_query($idadiquery);
if($idadiresult){
echo ""; // print massage
}  
} 
?> </html> 

Recommended Answers

All 6 Replies

The reason the page is loaded because you are using this.form.submit() which means you submit the form to the server, and then reload the page. What you need is AJAX function in place of form.submit(). Do you know much about AJAX?

Hi Taywin
As i said, I'm not good in AJAX that's why i posted for the help. If you can facilitate me on this i will be much happy!
Thanks for your time.
I appriciate you a million!

OK, you need to do 2 things.

Front End (client side)

First you need to replace onchange="this.form.submit();" to another function on the game (i.e. onchange="reloadMyForm(__YourFormObject__)" where YourFormObject is whatever form you are sending in). If you don't want to send any object in, make sure that your form has an ID, so that you can retrieve the form object from the page using document.getElementById or $().

Second, wrap the display area area inside a HTML element, such as a div. Give the element an ID for you to use once you get the information back from your server.

Third implement the function you use in onchange on the page. The function will use Ajax (XMLHTTPRequest and such) to send the data you collect from the form. The script should send the data to your server as asynchronous. Then wait for the result to come back (using onreadystatechange or similar).

Fourth, once you retrieve the response from your server (i.e. respondText or anything similar), manipulate the result and display it out on the display element you have on your page.

Back End (server side)

It could be another PHP file, but you have to make sure that the data sending method from your AJAX matches what you are retrieving from the back end (i.e. sending GET from ajax must use $_GET to retrieve). Another part is that when you return the data, return it as a format that your AJAX can retrieve (i.e. text, xml, etc.). One more thing, you need to be careful on this part that your script won't take too long to process, or the client side would be waiting.

A simple AJAX tutorial can be found here. In their simple example, you need to specify the file on the server side where the send(GET, ...) is. You will manipulate the respond inside the if (xmlhttp.readyState==4 && xmlhttp.status==200) { ... } scope.

Hi Tay
I was implementing what you directed me, unfortunately I succeeded to update data on database as I wished But I fail to update in reference to the id of item on database.
What I mean is, if I specify (manual) let’s say update where id=31 it works fine. So my failure now is to fetch the id of a specific item where I want to update the data.
How do I do also with AJAX because have tried to combine with a normal html & PHP it doesnt works.
Take I look on the code here may be you can get me more what is my issue

AJAX

<script>
        function showUser(str) {
            if (str == "") {
                document.getElementById("txtHint").innerHTML = "";
                return;
            } else {
                if (window.XMLHttpRequest) {
                    // code for IE7+, Firefox, Chrome, Opera, Safari
                    xmlhttp = new XMLHttpRequest();
                } else {
                    // code for IE6, IE5
                    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                }
                xmlhttp.onreadystatechange = function() {
                    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                        document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
                    }
                }
                xmlhttp.open("GET","?q="+str,true);
                xmlhttp.send();
            }
        }
</script>

WITH THIS CODE IT WORKS

 <?php
include('dbconnection.php');
      $q = intval($_GET['q']); 
$idadiquery="update `itemreg` set `Idadi` = '$q' where `id` ='151'";  //update selected query
$idadiresult = mysql_query($idadiquery);  // mysql_query close
?>

<form style="height:0.5px;">
<label style="height:6px;">
<select style="width:65px;" onchange="showUser(this.value)">
  <option value="3">3</option> 
  <option value="5">5</option> 
  <option value="10">10</option>
  <option value="20">20</option>
  <option value="30">30</option>
  <option value="40">40</option>
  <option value="60">60</option>
  <option value="70">70</option>
  <option value="80">80</option>
  <option value="90">90</option>
  <option value="100">100</option>
  </select>
</form>

WITH THIS IT DOESNT WORK

include('dbconnection.php');
  $idi=$_GET['key'];
      $q = intval($_GET['q']); 
$idadiquery="update `itemreg` set `Idadi` = '$q' where `id` ='$idi'";  //update selected query
$idadiresult = mysql_query($idadiquery);  // mysql_query close
?>

<form method="get" action="" style="height:0.5px;">
<input name="key" type="hidden" value="<?php echo $id; ?>" />
<label style="height:6px;">
<select style="width:65px;" onchange="showUser(this.value)">
  <option value="3">3</option> 
  <option value="5">5</option> 
  <option value="10">10</option>
  <option value="20">20</option>
  <option value="30">30</option>
  <option value="40">40</option>
  <option value="60">60</option>
  <option value="70">70</option>
  <option value="80">80</option>
  <option value="90">90</option>
  <option value="100">100</option>
  </select>
</form>

I've been in some position like you.
and i found that the easy way to submit that using Ajax is use jquery then the native Xhr.
I've no much time now to write the solution for what you need, but have something can help, with drop down. if you ready it you can get the solution.
js code

$(document).ready(function () {
    get_user_list();
    $('#datepicker').datepicker({dateFormat: "yy-mm-dd"});

    $('#call_back_btn').click(function () {
        save_user();
    });
    $('#subscriber').change(function () {
        get_user();
    });

});


function get_user()
{
    $.post("ajax.php",
            {   
                id : $('#subscriber').val(),
                task: "get_user"
            },
    function (data)
    {
        var person = jQuery.parseJSON( data );
        $('#firstname').val(person.first_name);
        $('#lastname').val(person.last_name);
        $('#datepicker').val(person.date);
        $('#responseText').val(data);
    }
    );
}
function get_user_list()
{
    $.post("ajax.php",
            {
                task: "get_user_list"
            },
    function (data)
    {
        $('#responseText').val(data);
        var people = jQuery.parseJSON(data);
        for (var i in people)
        {
            var opt = "<option value='" + people[i].id + "'>" + people[i].first_name + people[i].last_name + "</option>";
            $('#subscriber').append(opt)
        }
    }
    );
}


function save_user()
{
    $.post("ajax.php",
            {
                firstname: $('#dirstname').val(),
                lastname: $('#lastname').val(),
                dob: $('#datepicker').datepicker( ).val( ),
                id : $('#subscriber').val(),
                task: "save_user"
            },
    function (data)
    {
        $('#responseText').val(data);
    }
    );
}

php

function connect()
{
    $conn = mysql_connect('localhost', 'root', 'live@me2013');
    $db = mysql_select_db('demo');
    return $conn;

}

function get_user($id) {
    connect();
    $sql = "select * from tbl_people where id = $id";
    $query = mysql_query($sql);
    if ($query) {
        if (mysql_num_rows($query) == 1) {
            $row = mysql_fetch_object($query);

            return $row;
        }
    }
    return null;
}
function get_user_list()
{
    connect();
    $sql = "select * from tbl_people order by id asc";
    $query = mysql_query($sql);
    if($query)
    {
        if(mysql_num_rows($query) > 0)
        {
            $peple = array();
            while ($row = mysql_fetch_object($query))
            {
                $peple[] = $row;
            }
            return $peple;
        }
    }
    return null;
}
$method = $_SERVER['REQUEST_METHOD'];
if (strtolower($method) == 'post') {

    if (isset($_POST['task']) && $_POST['task'] == 'get_user_list') {
       $people = get_user_list();
       echo json_encode($people);
    } 
    else if (isset($_POST['task']) && $_POST['task'] == 'get_user')
    {
     $user = get_user($_POST['id']);
     echo json_encode($user);
    }
    else if (isset($_POST['task']) && $_POST['task'] == 'save_user') {
        $firstname = addslashes($_POST['firstname']);
        $lastname = addslashes($_POST['lastname']);
        $dob = addslashes($_POST['dob']);
        $id = addslashes($_POST['id']);
        $conn =  connect();

        if ($conn) {

            if($id == 0)
            {
               $sql = "insert into tbl_people (first_name,last_name,date) values('$firstname','$lastname','$dob')";
            $query = mysql_query($sql);
            if ($query) {
                $id = mysql_insert_id();
                $user = get_user($id);
                echo json_encode($user);
            } 
            }
 else {
     $sql  = "update tbl_people set first_name = '$firstname', lastname = '$lastname', date = '$dob' where id = '$id'";
    $query = mysql_query($sql);

     if($query)
     {
         echo '1';
     }
 else {
         echo '0';    
     }
 }

        } 
    }
}

and the html code.

<div class="container">
  <h2>Vertical (ajax) Form</h2>
  <div class="col-lg-7">
      <div class="form-group">
      <label for="email">Subscriber:</label>
      <select id="subscriber" name="" class="form-control">
          <option value="0">select subscriber</option>

      </select>
      </div>
    <div class="form-group">
      <label for="email">First Name:</label>
      <input type="text" class="form-control" id="firstname" placeholder="Enter email">
    </div>
    <div class="form-group">
      <label >Last Name: </label>
      <input type="text" class="form-control" id="lastname" placeholder="Enter password">
    </div>
      <div class="form-group">
      <label >Birth day</label>
      <input type="text" class="form-control" id="datepicker" name="date" placeholder="date of birth">
    </div>
      <div class="form-group">
      <label for="message">Message</label>
      <textarea class="form-control" id="responseText"></textarea>
    </div>
      <button type="submit" class="btn btn-default" id="call_back_btn">Submit</button>

</div>
</div> 

you can see there secting the drop down, and then i populate for the inputs, this is really easy way i found making Ajax with Jquery.
Because your write less js code, then with Xhr.

let me know if you can move forward with this code,if you can't i can write a solution based exactly on your desire.

The script doesn't work because the value of variable $idi is not defined. The reason it is not defined because it is not being sent from your Ajax to the script. You need to extend your string in xmlhttp.open(...) a little bit.

What is your key variable to send to the script? If you know what it is, you need to extend the string from "?q="+str to "?q="+str+"&key=".... I may need to see your HTML part that includes the key value you want to pass in.

PS: JQuery is just a wrapper of JavaScript. It could make your life easier, but it is bloated. If you have a concern on speed (in both viewing from a desktop or mobile), you should not use it. Yes, it is easy on you who are a developer, but it is not a good experience on viewers/users.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.