al_alb
al_alb

Reputation: 39

Issue with using ajax to update without refresh

I have this code here which is supposed to help me update a phone number. It doesn't do it though, well, i get the successfully changed message but no insertion on the database.

Here is my code: index.php

<script type="text/javascript" >
$(function() {
    $(".submit").click(function() {
        var phone = $("#phone").val();

        var dataString = 'phone='+ phone ;

        if(phone=='') {
            $('.success').fadeOut(200).hide();
            $('.error').fadeOut(200).show();
        } else {
            $.ajax({
                type: "POST",
                url: "update-phone.php",
               data: dataString,
               success: function() {
                   $('.success').fadeIn(200).show();
                   $('.error').fadeOut(200).hide();
               }
           });
       }
       return false;
   });
});
</script>
<div class="modal" style="display: none;">
<?php
if (empty($phone)) {
?>
<form method="post" name="form">
    <input id="phone" name="phone" type="text" />
    <div>
        <input type="submit" value="Submit" class="submit"/>
        <span class="error" style="display:none"> Please Enter Valid Data</span>
        <span class="success" style="display:none"> Registration Successfully</span>
    </div>
</form>

update-phone.php

<?php 
require_once('db.php'); 

if($_POST) {
    $phone = $_POST['phone'];
    mysql_query("UPDATE users SET phone = '$phone' WHERE ID = 5884 ");
}else {}

?>

What am i missing? Thanks

Upvotes: 1

Views: 181

Answers (2)

Pank
Pank

Reputation: 14268

Try this..

<?php 
require_once('db.php'); 

if($_POST) {
    $phone = $_POST['phone'];
    mysql_query("UPDATE `users` SET `phone` = '$phone' WHERE `ID` = 5884 ");
}else {}

?>

Upvotes: 2

ohej
ohej

Reputation: 243

Have you tried inspecting the ajax request with firebug/developer tools/etc? Try adding echo mysql_error(); right after your mysql_query.

Not 100% sure but it could be the if ($_POST) should be replaced with if (isset($_POST['phone']))

Try the following php:

<?php
require_once('db.hp');
if (isset($_POST['phone']))
{
  $phone = $_POST['phone'];
  mysql_query("UPDATE users SET phone = '$phone' WHERE ID = 5884 ");
  echo mysql_error();
} 
else
{
  echo "Failed";
}
?>

EDIT: Have you confirmed if it actually updates the DB? Also you should also sanitise your input and consider rolling with mysqli instead of mysql_*

Upvotes: 0

Related Questions