AJAX/PHP send values to server

2019-03-05 10:39发布

问题:

I'm trying to use AJAX to send values to PHP file, which then updates mysql database on the server. But for some reason the values are not transferred to PHP file.

This is the JS I use:

function send_message()
{

 var number = localStorage.getItem("number");
  var message = prompt("Message:", "");
   jQuery.ajax({ type: "POST", 
url: serviceURL + "message.php", 
data: 'number='+number+'&message='+message,
cache: false, 
success: function(response) 
{
alert("message sent");
}
});


}

And this is the message.php

    <?php
include 'config.php';

// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);

// new data

$number = $_GET['number'];
$message = $_GET['message'];
// query
$sql = "INSERT into table
        SET condition=0, change=1, change_time=NOW(), recieve=999, 
        number=?, message=?";
$q = $conn->prepare($sql);
$q->execute(array($number, $message));


?>

Everything else is inserted to mysql except the number and message are NULL. What could be the reason for this?

回答1:

You're posting data with AJAX using POST. In order to listen for those values in PHP you need to...

Replace:

$number = $_GET['number'];
$message = $_GET['message'];

With:

$number = $_POST['number'];
$message = $_POST['message'];


回答2:

To make things simpler just use a convenience method like $.post or $.get for ajax calls in jQuery:

function send_message()
{

  var number = localStorage.getItem("number");
  var message = prompt("Message:", "");
  $.post(serviceURL + "message.php", {'number' : number, 'message' : message},
         function(response){
           alert("message sent");      
         }
  );

}

Then in your php:

// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);

//if you used $.get you will also have to use $_GET here
$number = $_POST['number'];   
$message = $_POST['message'];

// query
$sql = "INSERT into table
        SET condition=0, change=1, change_time=NOW(), recieve=999, 
        number=?, message=?";
$q = $conn->prepare($sql);
$q->execute(array($number, $message));


?>

I can see that you're using prepared statements in PDO. But you may also want to add:

Filter Vars and Filter Input for additional security.



回答3:

Use $_POST instead of $_GET. Also, you can try to use $_REQUEST global array to forget about it. It has all the data you have sent to script.



回答4:

You may change your php file to;

<?php
include 'config.php';
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// new data
$number = $_POST['number'];
$message = $_POST['message'];
// query
$sql = "INSERT into table
        SET condition=0, change=1, change_time=NOW(), recieve=999, 
        number=?, message=?";
$q = $conn->prepare($sql);
$q->execute(array($number, $message));
?>