Using AJAX to return query results based on drop down box

后端 未结 3 1387
抹茶落季
抹茶落季 2021-01-07 05:11

I know that this is a popular question and I have looked at many examples trying to get my head around AJAX and jQuery.

I have a simple sit

3条回答
  •  说谎
    说谎 (楼主)
    2021-01-07 05:46

    I remember doing my first Ajax request with Jquery and found it hard to find a good complete example as well, especially something with error handling (how can I tell the user if something goes wrong in the backend, e.g. the database is not available?).

    Here's your code rewritten using PDO and Jquery including some error handling (I did not use the Mysql extension as it is removed from recent PHP versions (btw, your code is open to sql injection, it is very easy to drop your database):

    
    
    
        Selectbox Ajax example
        
    
    
    
    Teacher names

    PHP part

    setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
        // note the quote thing - this prevents your script from sql injection
        $data = $db->query("SELECT teacherName FROM departments where departmentName = " . $db->quote($_GET["q"]));
        $teacherNames = array();
        foreach ($data as $row) {
            $teacherNames[] = $row["teacherName"];
        }
    
        // note that we are wrapping everything with json_encode
        print json_encode(array(
                "teacherNames" => $teacherNames,
                "anotherReturnValue" => "just a demo how to return more stuff")
        );
    
    } catch (PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }
    

提交回复
热议问题