GhostRider
GhostRider

Reputation: 2170

Passing a string in a jQuery Ajax function not working, but no problems for an integer

I have a quick and likely easy question. I am new to jQuery and I have researched the stackoverflow files on this for answer that works without success. The function below takes an argument 'search_term', does some stuff on a success page and then reloads a file, on which $_POST['id'] is meant to return the value of search_term. This works perfectly if the search_term is an integer......but on my site it will always be a string. If I set $search_term = "hi", the error in the console is:

ReferenceError: hi is not defined

I have tried quotes around both the data parameters. Clearly it is an issue with my syntax if this is a string (I am assuming). Any suggestions would be helpful. I tried the jQuery documentation but there didn't seem to be an example that was exactly like mine, so no luck. Keep in mind I am pretty green.

function most_recent_search(search_term){
    $.ajax({
    url: '../ajax/success_page.php',
    type: 'post',
    data: {
          'search_term':search_term,
          },
    success: function(html) {
                   $('.thread_holder').load('search_thread_holder.php', {id: search_term});
              }
    });
    return false;
}

HTML:

<ul>        
    <li>
        <a href="#tabs-2" onclick="most_recent_search(<?php echo $search_term;?>)">Most recent</a>
    </li>
</ul>

Upvotes: 0

Views: 130

Answers (2)

charlietfl
charlietfl

Reputation: 171689

Look at the generated html source and you would see something like:

<a href="#tabs-2" onclick="most_recent_search(hi)">Most recent</a>

Where what you really want is:

<a href="#tabs-2" onclick="most_recent_search('hi')">Most recent</a>

So you are missing a set of quotes wrapping your echo statement

<a href="#tabs-2" onclick="most_recent_search('<?php echo $search_term;?>')">Most recent</a>

Upvotes: 1

user1299518
user1299518

Reputation:

Probably you missed quotes:

<li><a href="#tabs-2" onclick="most_recent_search('<?php echo $search_term;?>');">Most recent</a></li>

Otherwise it called like:

most_recent_search(hi);

so hi is undefined

Upvotes: 4

Related Questions