-2

I want my database to be updated when a button on my webpage is pressed without the page being refreshed. I used an AJAX function to do so, but I noticed that it also executes whenever I reload the page.

What I've done so far: I created an ajax function inside script code to execute whenever the button is clicked and it works just fine. But when I reload the page same thing happens as if I pressed the button.

Here's the script:

$(document).ready(function() {
   $('#delAddress').click(function() {
     <?php
       $sql = "UPDATE billinginfo SET 
       fullname = '',
       address1 = '',
       address2 = '',
       zip = '',
       city = '',
       country = ''
       WHERE username = '$usernameProfile';";
       $result = mysqli_query($dbProfile, $sql);
       ?>
    return false;
   });
});

I want it to execute just as it does right now but without it executing when I reload the page.

Bassam
  • 57
  • 8

1 Answers1

-1

You're mixing 2 different concepts here, the code that sends your ajax call and the code that processes this ajax call in the server. They're different things.

Code to make the ajax call:

On one side, you should have your front-end code, which makes an ajax call. Something like this:

$(document).ready(function() {
   $('#delAddress').click(function() {
    $.ajax({
      url: 'file.php',
      method:'POST',
      data: parameters,
      success: function(msg) {
         //code to execute in the browser when your ajax request has been processed
      }
    })
   });
});


Code to process the ajax call in the server:

On the other side, the code that processes this request and executes your SQL query on the server. Something like this:

<?php

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

    $usernameProfile = $_POST['usernameProfile'];

    $con = mysql_connect("localhost","username","password"); //replace with your DB credentials
    if (!$con) {
      die('Could not connect: ' . mysql_error());
    }

    $sql = "UPDATE billinginfo SET 
    fullname = '',
    address1 = '',
    address2 = '',
    zip = '',
    city = '',
    country = ''
    WHERE username = $usernameProfile";

    $result = mysql_query($sql,$con);
    echo $result;

    mysql_close($con);
  }
?>
ludovico
  • 2,103
  • 1
  • 13
  • 32