2

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 ?

7
  • Always escape strings with mysql_real_escape_string() before appending them to an SQL query. Use mysql_real_escape_string($first) instead of $first. Commented Mar 3, 2012 at 5:05
  • Do you mean replace $first=$_GET['ud_first']; with mysql_real_escape_string($first)=$_GET['ud_first']; ?. Im fairly new. Thank you Commented Mar 3, 2012 at 5:09
  • 1
    I mean that the value of $first should never be included directly in the query, without any processing. If you do that, the user that sends you the value by submitting the form, can write whatever they want inside it, including other SQL statements that you didn't intend to execute. This is called SQL injection. To prevent that, PHP has mysql_real_escape_string(), which returns the string that you send it, but in a way that you can safely append it to the query. Thus, use something like $first = mysql_real_escape_string($_GET['ud_first']). Commented Mar 3, 2012 at 5:13
  • May I ask though why you're not using something like jQuery? It could save you a lot of trouble and could make that AJAX request a lot easier to write and a lot more error-proof. Commented Mar 3, 2012 at 5:23
  • Because I know jQuery inside out and I just started learning MySQL so I'm sticking with the basics (tutorials) and trying to built something I know inside out. Then I turn everything to jQuery. I like when learning, to know exactly everything what its suppose to do and why its there etc. Maybe that is the way I learn (?) Commented Mar 3, 2012 at 5:28

6 Answers 6

2

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>
Sign up to request clarification or add additional context in comments.

3 Comments

It would be great to explain why this works. Just "try this, it will work" is not helping that much.
I have done this in past thats why, if any error then tell me
That's great, I'm sure you understand why it works. What I'm saying is that the asker would benefit more if you explained why it works, so he can understand too.
2

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();
}

11 Comments

That is the concept I was looking for. I got the idea now although it doesn't work. Does my ajaxupdate.php has to be POST or GET?
@JohnyBryne, use print_r($_GET) and see what gets passed. Also, the request doesn't technically have to be POST, but it should be POST.
Noticed your ajaxupdate.php was requesting ud_id and not q. Look at my edited answer
@Radu print_r($_GET) gives me an empty string. Tried your way and it doesn't work. There is something that has to be wrong. Is it because mysql is set on localhost? Becuase I get on my URL Bar: ?ud_id=25&ud_first=joe&ud_last=doe
@JohnyBryne, it can't give you an empty string... At the very least, it should show an empty array...
|
2

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.

6 Comments

I really appreciate your effort in making this work and I feel ashamed that still is not working but I am very sure the problem comes from the reason that everything is locale. I have changed from pure js to jquery just to see if that was the problem, and still this doesnt work. Obviously I used return false; on the jquery side. As for sam's answer, well its wrong since he is not assigning the ID's in the form, however I have tried that way few hours before I come here. I think I tried every possible way I can imagine
@JohnyBryne, alright, do this: instead of using the function in the onsubmit form event, make a plain button and use the function on the button's onclick event and remove all <form> tags. That's all. This should prevent any default browser behavior.
Ok I've set the ID manually inside my ajaxupdate.php file and it works. Changed few things. I'm really close to the solution
Bingo. 2 errors. First the <form> thing doesn't work. Only with the OnClick on the button. Second error: Had to change my MySQL code from WHERE id='$ud_id'"; to WHERE id = '".$ud_id."'";
@JohnyBryne, that change in SQL shouldn't be necessary. Do not forget though to escape values as you insert them in the query. Always use mysql_real_escape_string().
|
1

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>

2 Comments

var str = $('.ud_id').attr('value');he called only this ,,and expects all the parameters,, in my post that is rectified....
@JohnyBryne ,, your way of setting query string gets only one parameter ,don't worry make your query string as posted above and it will work fine
0

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

Comments

0

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.