简体   繁体   中英

How can I make my jQuery database ajax request more efficient and flexible?

I have an jQuery ajax database query and Im wondering how I can maybe make it more flexible, or if anyone can shed some light on a better approach as I am just beginning to learn ajax and need a little advice.

Heres what I have so far:

        <form method="post" name="sc_ajax" onsubmit="checkDB(document.sc_ajax.sc_voucher_code.value); return false;">
     ...
        </form>

The form is set so on submit it runs the following ajax function (on same page):

function checkDB(code)
{

  $.ajax({
  type: "POST",
  url: "<?php bloginfo('template_url'); ?>/profile/check_code.php",
  data: 'code='+code,
  datatype: "html",
  success: function(result){

       if(result == 0)
        {
            $('#success').html( code + ' already exists and has not been redeemed...');
            // alert('success');//testing purposes
        }
        else if(result == 2)
        {
            $('#err').html(  code + ' already exists and has already been redeemed....');
            //alert('fail');//testing purposes
        }else if(result == 1){
            $('#err').html(  code + ' redeem code doesnt exist');      
        }

        alert(result);      
      }
  })

}

So this gets result from a seperate file called "check_code.php":

    $code = mysql_real_escape_string($_POST['code']);  

$resultcode = mysql_query('select * from wp_scloyalty where code = "'. $code .'"' ) or die(mysql_error());  


$redeemed=array();
while($info = mysql_fetch_array( $resultcode )) 
{ 

    $redeemed[$info["code"]] = $info["redeemed"];

} 

if(mysql_num_rows($resultcode)>0 && $redeemed[$code] == 0){
    //Exists so change redeemed code to 1 
    echo 0;   

}elseif(mysql_num_rows($resultcode)>0 && $redeemed[$code] == 1){
    //Exists but already redeemed, so throw error
    echo 2;

}else{  
    //Doesnt Exist
    echo 1;  
}  

The code works perfectly by the way... but my question is... I am currently running a bunch of "if statements" from the check_code.php file, but is there a better way to do this as I have been looking round for tips on using ajax and other peoples approaches seem a lot more confusing and cluttered with code. Am I doing something wrong here?

Thanks people!

Number of rows should be calculated first because if the query returns zero rows, fetch array will raise an error. As you can see, you're fetching result array more than once. No need to do that. Store it before you fetch the result array and use it for comparison later on. Relating to your ajax, use cache:true in jQuery for speed up .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM