Reputation: 3247
I'm new to jQuery and would like to know how I can fetch Array keys from a php file into jQuery.
I have this jQuery code to post input to file.php
and exexute a query on every keyup.
file.php
echoes the result with the help of an Array what will look like:
echo '<li>'.$row["name"].' '.$row["place"].' '.$row["year"].'</li>';
The jQuery code is:
$(document).ready(function() { //changes are possible when the page has fully loaded
$('.inp').keyup(function() { //executes keyup function to the field class "inp"
var inp = $(this).attr('value'); //sets a variable with the value of input from class="inp"
$.post('ajax/file.php', {inp:inp}, function(data) { //posts that value to file.php as variable inp and executes the function (data) to this
$('.result').html(data); //adds the returned result into HTML content as a first element in the set of class="result" => <li>
$('.result li').click(function() { //executes click function when clicking li element
var result_value = $(this).text(); //sets a variable and prepares something as text
$('.inp').attr('value', result_value); //fills value attribute of field class "inp" with the variable result_value
$('.result').html(''); //clears li to ul class to hide the lists of results
});
});
});
});
So when I click onto the li
result it will be converted into text and the value attribute of the input field is filled with that.
To give an example:
echo '<li>'.$row["name"].' '.$row["place"].' '.$row["year"].'</li>';
will output:
<li>ExAmpLE Home 2013</li>
So when I click on li
the new value of the input field is:
ExAmpLE Home 2013
My question is how can I exlude specific Array keys like $row["name"]
or $row["year"]
from converting the result value into text from that click function so that the new value of the input field is:
ExAmpLE Home
Upvotes: 1
Views: 347
Reputation: 664
You can use json :
file.php
json_encode(array('name' => $row["name"], 'place' => $row["place"], 'year' => $row["year"]));
In your javascript use jQuery data() function to store your data in the DOM to retrieve it later:
$.post('ajax/file.php', {inp:inp}, function(data) {
$('.result').html(
$('<li>').text(data.name + ' ' + data.place + ' ' + data.year)
.data('name', data.name)
.data('place', data.place)
.data('year', data.year)
.click(function() {
$('.inp').attr('value', $(this).data('name') + ' ' + $(this).data('place'))
$(this).empty();
})
);
}, 'json');
Upvotes: 2
Reputation: 5878
Putting the stuff you need into a span should work:
echo '<li><span>'.$row["name"].' '.$row["place"].'</span> '.$row["year"].'</li>';
I assume you already know how to get at the li element. Then do:
var $li= $(this);
var text= $li.find('span').text();
Upvotes: 0