1

When I use some characters like / in the textbox I get returned an empty string in response. I can easily make a check for empty string in my html but my question is how can I avoid having that empty string from being sent over in my php code?

$("#search").keyup(function(){
    var newVal = $(this).val();
    if(!newVal==""){
         $.ajax({
              type : 'get',
              dataType: 'html',
              url : '/searchpost/' + newVal , 
              success : function(response) {
                   console.log(response);
              }
         });
    }
});

public function searchpost() {

        $q = $this->uri->segment(3);
        if(!$q) die();

        $string = trim(strip_tags($q));
        $db_string = urldecode($string);

        $this->db->select("postID, post_title, post_url, post_status");
        $this->db->like("post_title", $db_string);
        $this->db->or_like("post_url", $db_string);

        $posts = $this->db->get('posts', 10);

        if(!count($posts->result())) {
            die('Nothing to display');
        }

        ?>

        <ul>
        <?php 
        foreach($posts->result() as $m) : 
            if($m->post_status != 'active' OR empty($m->post_title)) continue;
        ?>
        <li>
            <a href="<?php echo '/posts/'.$m->postID.'/'.url_title($m->post_title); ?>" class="url-post-title" style="font-size:14px;"><?php echo $m->post_url; ?></a>
            </a>
        </li>
        <?php endforeach; ?>
        </ul>

        <?php 

    }
4
  • / is used as an escape character, use console log and var_dump to check what you're sending and recieving. Commented Oct 4, 2016 at 3:43
  • @Aschab console printing out "(an empty string)" Commented Oct 4, 2016 at 3:46
  • console.log($(this).val()) gives you empty string? Commented Oct 4, 2016 at 3:47
  • @Aschab nope... the response. The input value is correct Commented Oct 4, 2016 at 3:50

1 Answer 1

1

You could change your js function and use encodeURIComponent to encode the value before sending the request:

$("#search").keyup(function(){
    var newVal = $(this).val();
    if(newVal !== undefined && newVal.length > 0){
         $.ajax({
              type : 'get',
              dataType: 'html',
              url : '/searchpost/' + encodeURIComponent(newVal) , 
              success : function(response) {
                   console.log(response);
              }
         });
    }
})

Then you may have to handle the now url encoded value in your php function.

So instead of:

$db_string = urldecode($string);

Use rawurldecode

$db_string = rawurldecode($string);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.