1

I'm using an AJAX form to feed the code something to lookup in db. Separate table, not WP options.

I'm getting the result from AJAX, but when I try to do the sql it just returns 0.

This is the function:

   function myajax_inputtitleSubmit_func() {
    // check nonce
    $nonce = $_POST['nextNonce'];   
    if ( ! wp_verify_nonce( $nonce, 'myajax-next-nonce' ) )
        die ( 'Busted!');

    $zipcode = $_POST['zip'];
    // generate the response
    global $wpdb;
    $tablename  = "{$wpdb->prefix}levering";

    $sql    = "SELECT Levering FROM {$tablename} WHERE Zip LIKE %s";
    $result = $wpdb->get_var($wpdb->prepare($sql, $zipcode));
    return $result;
    while($row = mysql_fetch_array($result)) { 
        $response = $row['Levering'];
        }

    // response output
    header( "Content-Type: application/json" );
    echo $response;
    die();
    // IMPORTANT: don't forget to "exit"
    exit;
}
  • 1
    A couple of questions - why there is a return statement? You have used get_var() which returns a single variable as result, so why looping has been done? – WisdmLabs Jul 27 '14 at 17:18
  • It's from another attempt to solve the problem, has no meaning anymore - and has been deleted since this was posted with no change in result. – Morten Ellegaard Larsen Jul 30 '14 at 4:52
1

I have made some changes to your code. See now if this works -

function myajax_inputtitleSubmit_func() {
    // check nonce
    $nonce = $_POST['nextNonce'];   
    if ( ! wp_verify_nonce( $nonce, 'myajax-next-nonce' ) )
        die ( 'Busted!');

    $zipcode = $_POST['zip'];
    // generate the response
    global $wpdb;
    $tablename  = "{$wpdb->prefix}levering";

    $sql    = "SELECT Levering FROM {$tablename} WHERE Zip LIKE %s";
    $result = $wpdb->get_col($wpdb->prepare($sql, $zipcode));

    $response = array();

    foreach($result as $res){
        $response[] = $res;
    }
    // response output
    echo json_encode($response);
    die();
    // IMPORTANT: don't forget to "exit"
    exit;
}
|improve this answer|||||
  • Turn out there was a couple of other mistakes, but your code did the trick. Now I get the result ["Mandag, onsdag og fredag"] - how do I get this down to the raw string? – Morten Ellegaard Larsen Jul 30 '14 at 5:12
  • I managed to remove the [], now I just need to remove the qoutes. But I also need to handle the situation where the sql call doesn't return an answer - how is this done? – Morten Ellegaard Larsen Jul 30 '14 at 9:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.