0

I am trying use ajax in phonegap. When I post data - php always take null array. And it is not wrong code. I wonder if something with url is wrong. Is it possible? Or maybe I should add some more access? I have really no idea what i do incorrectly.

incorrectly..

Here is my code: html:

    <!DOCTYPE html>

<html>

<head>
    <meta charset="utf-8" />
    <meta name="format-detection" content="telephone=no" />
    <meta name="msapplication-tap-highlight" content="no" />
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width" />
    <meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline'; style-src 'self' 'unsafe-inline'; media-src *" />
    <link rel="stylesheet" type="text/css" href="css/index.css" />



</head>
<body>
<form id="foo">
    <label for="bar">A bar</label>
    <input id="bar" name="bar" type="text" value="" />
    <input type="submit" value="Send" />
</form>

<div id="result"></div>


    <script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
    <script type="text/javascript" src="js/bootstrap.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
 var values = $(this).serialize();

 $.ajax({
        url: "http://localhost/inne/phonegap_test/agregar.php",
        type: "post",
        data: values ,
        success: function (response) {
          console.log("okey");         

        },
        error: function(jqXHR, textStatus, errorThrown) {
           console.log(textStatus, errorThrown);
        }


    });
</script>


</body>

</html>

php:

    <?php


header('Access-Control-Allow-Origin: *'); 
header('Access-Control-Allow-Methods: POST, GET, OPTIONS'); 

 var_dump($_POST);
workhard
  • 3
  • 1
  • 2

1 Answers1

0

It is because script sends request immediately page is loaded. You should use this code:

 
 
 $("#foo").submit(function(e){
   var values = $(this).serialize();

   $.ajax({
        url: "http://localhost/inne/phonegap_test/agregar.php",
        type: "post",
        data: values ,
        success: function (response) {
          console.log("okey");         

        },
        error: function(jqXHR, textStatus, errorThrown) {
           console.log(textStatus, errorThrown);
        }


    });

    e.preventDefault();
    return false;
 });
Dmitriy Buteiko
  • 624
  • 1
  • 6
  • 14