dsmvovm27249 2013-10-02 04:03
浏览 18

too long

I have a simple jQuery AJAX request that submits user input from a text box to a PHP file. Here's the code for it:

$.ajax({
    url: url,
    type: type,
    data: data,
    dataType: 'json',
    success: function(response){
        console.log(response);
    }
});

The PHP file basically logs the user in. Everything worked fine until I added "dataType: 'json'" to my AJAX request. Now, whenever I click my submit button, nothing logs. Here is my PHP file:

<?php
include 'dbcon.php';

if ( isset( $_POST['text_login_username'], $_POST['text_login_password'] ) ) {
    $loginResult = array();
    $dbcon = getConnection();
    $userName = mysqli_real_escape_string( $dbcon, $_POST['text_login_username'] );
    $password = mysqli_real_escape_string( $dbcon, $_POST['text_login_password'] );
    $loginQuery = "SELECT * FROM userData WHERE userName='$userName' AND userPassword='$password'";
    $queryResult = mysqli_query( $dbcon, $loginQuery );
    $legalRows = mysqli_num_rows( $result );
    if ( $legalRows == 1 ) {
       $loginResult['allClear']=0;  
    } else {
       $loginResult['allClear']=1;
    }

    echo json_encode( $loginResult );
}
?>

AJAX file

$(document).ready(function(){

$('form.loginSubmit').on('submit',function(){


    var that = $(this),
        url=that.attr('action'),
        type=that.attr('method'),
        data={};

    that.find('[name]').each(function(index,value){ 
        var that=$(this), 
            name=that.attr('name'); 
            value=that.val(); 
            data[name]=value;
    });


    $.ajax({
        url: url,
        type: type,
        data: data,
        contenType:'application/json; charset=utf-8',
        dataType:'json',
        success: function(response){
            console.log(response);
        },
        error: function(error)
        {
            console.log("test");
        }


    });

return false;

});


});

I can assure that the proper links to files, posts, etc. are set up properly, because this works until I try to send out the json_encode variable. Any help would be much appreciated!

Thanks!

~Carpetfizz

UPDATE: I added an error: setting to my AJAX call, and it runs whenever I submit.

UPDATE: Check out my answer. This was the solution for me.

  • 写回答

5条回答 默认 最新

  • duanben1909 2013-10-02 04:47
    关注

    Check this code

    demo.php

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="initial-scale=1, maximum-scale=1" />
    <title>jQuery AJAX Call to PHP Script with JSON Return</title>
    <style type="text/css">
    body {font-family: Helvetica, Arial, sans-serif; font-size: 13px}
    .the-return {background: #f0f0f0; padding: 10px; margin-top: 15px}
    </style>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
    <script type="text/javascript">
    $("document").ready(function(){
        $(".js-ajax-php-json").submit(function(){
            var data = {
                "action": "test"
            };
            data = $(this).serialize() + "&" + $.param(data);
            $.ajax({
                type: "POST",
                dataType: "json",
                url: "response.php",
                data: data,
                success: function(data) {
                    $(".the-return").html(
                        "Favorite beverage: " + data["favorite_beverage"] + "<br />Favorite restaurant: " + data["favorite_restaurant"] + "<br />Gender: " + data["gender"] + "<br />JSON: " + data["json"]
                    );
    
                    alert("Form submitted successfully.
    Returned json: " + data["json"]);
                }
            });
            return false;
        });
    });
    </script>
    </head>
    <body>
    <p><b>jQuery AJAX Call to PHP Script with JSON Return</b></p>
    <form action="return.php" class="js-ajax-php-json" method="post" accept-charset="utf-8">
      <input type="text" name="favorite_beverage" value="" placeholder="Favorite restaurant" />
      <input type="text" name="favorite_restaurant" value="" placeholder="Favorite beverage" />
      <select name="gender">
        <option value="male">Male</option>
        <option value="female">Female</option>
      </select>
      <input type="submit" name="submit" value="Submit form"  />
    </form>
    <div class="the-return">
      [HTML is replaced when successful.]
    </div>
    
    </body>
    </html>
    

    return.php

    <?php
    if (is_ajax()) {
        if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
            $action = $_POST["action"];
            switch($action) { //Switch case for value of action
                case "test": test(); break;
            }
        }
    }
    
    //Function to check if the request is an AJAX request
    function is_ajax() {
        return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
    }
    
    function test(){
        $return = $_POST;
    
        //Do what you need to do with the info. The following are some examples.
        //if ($return["favorite_beverage"] == ""){
        //  $return["favorite_beverage"] = "Coke";
        //}
        //$return["favorite_restaurant"] = "McDonald's";
    
        $return["json"] = json_encode($return);
        echo json_encode($return);
    }
    ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题