Reputation: 684
Cant work out how to send results csv back as an object from Ajax , Its simple enough, the search works as expected but the results are sent back as a string i gather...
CSV
header1 , header2 , header3, header4, header5
Foo , age-20 , male , city NY , Cars
Bar , age-32 , female , city FL , Clothes
etc...
PHP
$search = $_POST['search'];
$row = 0;
$handle = fopen("items/data.csv", "r");
$complete = array();
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if ($row == 0) {
$row++;
}else {
for ($x=0; $x < 4; $x++) {
$se = $data[$x];
if ($se == $search){
$num = count($data);
$row++;
for ($c=0; $c < $num; $c++) {
$complete[] = $data[$c] ;
}
}
}
}
}
fclose($handle);
echo json_encode($complete);
AJAX
$.ajax({
url:'search.php',
type: 'POST',
data: {search: $('#search').val()},
success: function(data) {
console.log(data);
},
error: function (error ,xml){
console.log(error);
}
})
}
Im having a hard time trying to use this information that is returning, I deally i would like it as an array();
**Returned String Output**
["Bar","Age-32","Female","city FL","Clothes"]
Thanks
Upvotes: 0
Views: 678
Reputation: 1268
In your ajax request set data type to json
$.ajax({
url:'search.php',
type: 'POST',
dataType: "json",
data: {search: $('#search').val()},
success: function(data) {
console.log(data);
},
error: function (error ,xml){
console.log(error);
}
});
And in php file you need to set header
header('Content-Type: application/json');
Upvotes: 1
Reputation: 2221
The first thing that comes to mind is $.ajax
having a dataType
attribute that allows you to force an expected data type, in this case json
.
Note that - as per the documentation - you don't need to define
dataType
if the MIME type is set correctly on the server side. You can use PHP'sheader
function to achieve this:header('Content-Type: application/json')
.
Read the official documentation here.
$.ajax({
url: 'search.php',
type: 'POST',
dataType: 'json',
data: { search: $('#search').val() },
success: function(data) {
console.log(data);
},
error: function (error, xml) {
console.log(error);
}
});
Upvotes: 1