Sm00rf9000
Sm00rf9000

Reputation: 541

Submit data to PHP using AJAX issue

I have a site on which I have two values of which I want to submit to a PHP script. I would like this to happen whenever a specific action is done by the user. It has to be "silent", as in it has to just run in the background, hence the reason I want to submit it from AJAX to PHP. I have a code, which seems right, but somehow doesn't work. I have used the line

success: function () {
                        alert('data was submitted');
                    }

To check whether it even submits the data and it doesn't reach this, as the alert isn't showing up.

HTML / Ajax

<!DOCTYPE html>
<html lang="en">

  <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
        <script>
        function ch() {

            var customID = document.getElementById('hiddenCustomerValue').innerHTML;    
            var customEmail = document.getElementById('customerEmail').innerHTML;   
            var dataString = 'customID='+customID+'&customEmail='+customEmail;

            $.ajax({
                    type:"POST",
                    url: "testSilence.php",
                    data:dataString,
                    cache: false,
                    success: function () {
                        alert('data was submitted');
                    }
            });
            return false;
        }
    </script>

  </head>

  <body>

       <p id="hiddenCustomerValue" style="color:white;">customerKeyID</p>
       <p id="customerEmail" style="color:white;">test</p>
       <button id="send_btn" onclick="ch()">Submit</button>

 </body>

PHP

<?php

$customerID = $_POST['customID'];
$customerEmail = $_POST['customEmail'];

?>

Upvotes: 2

Views: 48

Answers (1)

Script47
Script47

Reputation: 14530

For sake of marking this as answered, as suggested in my comment, remove the spaces in your data string that is being passed as that changes what the keys will represent on the server side.

As suggested in my earliest comment too, it would be better to use an object instead:

data: {
    'key' : 'val',
    'key2' : 'val-2'
}

In your instance it would be:

data : {
    'customID' : customID,
    'customEmail' : customEmail
}

Note: Regarding your PHP code, I'd definitely do some validation there to ensure that data is being passed by using isset, empty and trim along with other validation that you feel would be suitable. Remember, requests can be spoofed.

Upvotes: 1

Related Questions