2014-06-15 1 views
0

js 파일에서 PHP로 POST 호출을 시도합니다. mySQL 데이터베이스에 변수를 추가하려면이 스크립트가 필요합니다.

1 ° PHP 파일 전송 전화 recever의

<html> 

    <head> 
     <script src="../js/jquery.js"></script> 
     <script src="../js/ajax-call.js"></script> 

    </head> 

    <body></body> 

</html> 

파일 JS

$(document).ready(function() { 

    $.ajax({ 
     url: 'http://localhost/json/html/j.php', 

     contentType: 'application/json', 
     dataType: 'json', 
     type: 'post', 
     data: { 
      "variable":"foo" 
     }, 

     success: function() { 
      console.log("ok"); 

     }, 
     error: function() { 
      console.log("error"); 
     } 
    }); 
}); 

PHP 코드를 사용 :

<?php 
    function connect(){ 
     $connect = mysql_connect('127.0.0.1','root','') or die("ERROR"); 
     $connect2Database = mysql_select_db('ajax', $connect); 
     return $connect; 
    } 

    if(isset($_POST)){ 
     if($connect = connect()){ 
      $query = "INSERT INTO `table`(`name`) VALUES ('".$_POST['variable']."');"; 
      $completeQuery = mysql_query($query, $connect); 
     } 
    } 
?> 

내 간단한 파일이 있습니다

변수 $ _P OST [ '변수']가 정의되지 않았습니다. 쉬운 문자열로 $ _POST [ 'variable']를 설치하려고 시도하고 데이터베이스에 추가되었습니다.

답변

0

contentType'application/json'으로 설정하면 원시 JSON 문자열이 서버로 전송됩니다. 대신 해당 부분을 제거하고 일반 POST을 수행해야합니다.

$.ajax({ 
    url: 'http://localhost/json/html/j.php', 
    type: 'post', 
    data: { 
     "variable":"foo" 
    }, 

    success: function() { 
     console.log("ok"); 

    }, 
    error: function() { 
     console.log("error"); 
    } 
});