简体   繁体   中英

MySQL/PHP: Update MySQL with Ajax

I am a beginner and I am trying to learn how to add, delete, retrieve and update a database using PHP and Ajax.

At this time I have accomplished how to retrieve and delete so I am trying to update some values. For retrieving data, I just pass the selected ID I want, so I can retrieve the data. Same goes for delete, I just assign which ID I want to delete. Now to update there are more things going on, its where I cant find the solution.

This is my Form:

<form onsubmit="updateuser()">

   ID Number: <input name="ud_id"><br>
   First Name: <input type="text" name="ud_first"><br>
   Last Name: <input type="text" name="ud_last"><br>

<input type="Submit" value="Update">
</form>

and this is my javascript:

    function updateuser() {
    var str = $('.ud_id').attr('value');

   if (window.XMLHttpRequest) {
      xmlhttp = new XMLHttpRequest();
   }
   xmlhttp.onreadystatechange = function () {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
         document.getElementById("txtuser").innerHTML = xmlhttp.responseText;
      }
   }
   xmlhttp.open("GET", "ajaxupdate.php?q=" + str, true);
   xmlhttp.send();
}

I think the problem comes because my form ajaxupdate.php file doesn't retrieve the First and Last name values from the form. It's like I am not passing them (?).

Here is my ajaxupdate.php file:

<?php   include("connection.php");

$id=$_GET['ud_id'];
$first=$_GET['ud_first'];
$last=$_GET['ud_last'];


$query="UPDATE contacts SET first='$first', last='$last' WHERE id='$id'";


mysql_query($query);
mysql_close();
?>

What I'm I doing wrong so that I can update the value first and last of database for a specific ID ?

In your javascript, do this

function updateuser() {
    var ud_id = $('input[name="ud_id"]').val();
    var ud_first = $('input[name="ud_first"]').val();
    var ud_last = $('input[name="ud_last"]').val();

    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    }
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("txtuser").innerHTML = xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET", "ajaxupdate.php?ud_id=" + ud_id + "&ud_first="+ud_first+"&ud_last="+ud_last, true);
    xmlhttp.send();
}

Try this code

<script type="text/javascript">
function updateuser() {
    var ud_id = document.getElementById('ud_id').value;
    var ud_first = document.getElementById('ud_first').value;
    var ud_last = document.getElementById('ud_last').value;

    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    }
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("txtuser").innerHTML = xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET", "ajaxupdate.php?ud_id=" + ud_id + "&ud_first="+ud_first+"&ud_last="+ud_last, true);
    xmlhttp.send();
}
</script>

HTML

<form name="test">

   ID Number: <input name="ud_id"><br>
   First Name: <input type="text" name="ud_first"><br>
   Last Name: <input type="text" name="ud_last"><br>

<input type="button" onClick="updateuser()" value="Update">
</form>

If you want to use the updateuser() function on submit, then it must prevent the form from actually submitting. Make it return false , otherwise the form gets submitted by the browser before the function has time to execute.

The browser runs the function before submitting the form (that's how on submit works). If the function doesn't return false , then it interprets that as "everything is OK, you can safely submit the form". The form then gets submitted as usual.

In the mean time, the function initiates the asynchronous request. But since the browser has already submitted the form, now you're on a totally different page, thus the connection and the asynchronous request get disconnected and most likely ignored (unless of course the request made it before the page was changed, in which case both requests are processed).

As an alternative, you could execute the function without placing it in the on submit event. See sam_13's answer .

Check this it will work as expected

    ud_id = document.getElementById('ud_id').value;
    ud_first = document.getElementById('ud_first').value;
    ud_last = document.getElementById('ud_last').value;
    xmlhttp.open("GET", "ajaxupdate.php?ud_id=" + ud_id +"&ud_first=" +ud_first+ "ud_last="+ud_last, true);



<form onsubmit="updateuser()">

   ID Number: <input name="ud_id" id="ud_id"><br>
   First Name: <input type="text" name="ud_first" id="ud_first"><br>
   Last Name: <input type="text" name="ud_last" id="ud_last"><br>

<input type="Submit" value="Update">
</form>

I came accross this example because i am also running into a similar issue. however I couldnt help but notice that you do not specify a method for your form and your AJAX is assuming it should use the GET method. just food for thought... cheers

This code is tested and works. I needed to do the same thing, update MySql with ajax and combining the above with a wider research I got this to work. The php file is called ajaxupdate.php:

<?php
$id= $_GET['ud_id'];
$first= $_GET['ud_first'];
$last= $_GET['ud_last'];
require_once ('mysqli_connect.php'); //connection to the database
$sql = "UPDATE contacts SET FirstName ='$first', LastName='$last' WHERE id='$id'";
$result = mysqli_query($dbc,$sql);
mysqli_close($dbc);
?>

The Html file called anyNameYouWish.html:

<html>
<head>
</SCRIPT>
<script language="javascript" type="text/javascript">
//Browser Support Code
function ajaxFunction(){
    var ajaxRequest;  // The variable that makes Ajax possible!
    try{
        // Opera 8.0+, Firefox, Safari
        ajaxRequest = new XMLHttpRequest();
    } catch (e){
        // Internet Explorer Browsers
        try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try{
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                // Something went wrong
                alert("Your browser broke!");
                return false;
            }
        }
    }
function MsgBox (textstring) {
alert (textstring) }
    // Create a function that will receive data sent from the server
    ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4){
            var ajaxDisplay = document.getElementById('ajaxDiv');
            ajaxDisplay.innerHTML = ajaxRequest.responseText;
        }
    }
    var ud_id = document.getElementById('ud_id').value;
    var ud_first = document.getElementById('ud_first').value;
    var ud_last = document.getElementById('ud_last').value;
    var queryString = "?ud_id=" + ud_id + "&ud_first="+ud_first+"&ud_last="+ud_last;
    ajaxRequest.open("GET", "ajaxupdate.php" + queryString + "&random=" + Math.random(), true);
    ajaxRequest.send(null); 
}
</script>
</head>
<body>
<form method="post" name="test" onsubmit="ajaxFunction()">  
   ID Number: <input id="ud_id" name="ud_id"><br>
   First Name: <input id="ud_first" type="text" name="ud_first"><br>
   Last Name: <input id="ud_last" type="text" name="ud_last"><br> 
<input type="submit"  value="Update">
</form>
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM