I am adding input field with JQuery, when given condition is fulfilled.That input field should serve as a live search, so i attached on it on keyup event which must send through ajax the value of field in php side page, which page should check in database results which matching the given word or letter, and return the results in form of json object.
But problem is there that my explode is giving PHP Notice: Undefined offset: 0 in ... And from there my Ajax returns No conversion from text to object. And nothing is printed as result in the DOM or console,but in network tab i get what i want ... Its really confusing there is all step by step:
$('#intake_goal_main').after('<input type = "text" name = "intake-search-field " class = "intake-search-field"/>');
$('.intake-search-field').on('keyup',function(){
var intake_search_product_name = $(this).val();
$.ajax({
type: "POST",
data: {'product_name':intake_search_product_name},
cache: false,
url: '/ajax/intake/intake_search.php',
dataType: JSON,
success: function(result){
$('.intake-food-result').remove();
// $('.intake-search-field').after('<div class = "intake-food-result"></div>').html(result);
},
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.status);
alert(textStatus);
alert(errorThrown);
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="intake_goal_main"><select id="intake-pick-goal"><option>-- Изберете цел --</option><option value="intake-bulk">Покачване на килограми</option><option value="intake-cut">Сваляне на килограми</option><option value="intake-maintenance">Поддържане на килограми</option></select> </section>
<?php
if(!empty($_POST['product_name'])) {
$product_name =$_POST['product_name'];
$req = ("SELECT * FROM food_data_bg WHERE ");
$term = explode(" ",$product_name); //here is the problem...!!!!
$i=0;
foreach($term as $form){
$i++;
if($i == 1){
$req .= "title LIKE '%".$form."%'";
}else{
$req .= "OR title LIKE '%".$form."%'";
}
}
require_once $_SERVER['DOCUMENT_ROOT'].'/inc/connection.php';
$req = mysqli_query($connect,$req);
$num_rows = mysqli_num_rows($req);
if($num_rows == 0){
$no_result = 'Няма резултати';
echo json_encode($no_result);
exit();
}
else{
$result = array();
while($row = mysqli_fetch_assoc($req)){
$title= $row["title"];
$myID= $row["id"];
$image = $row["fimage"];
$state = $row["state"];
$result[] = array(
'title' => $title,
'id' => $myID,
'image' => $image,
'state' => $state
);
}
echo json_encode($result);
exit();
}
}
?>
There is also my network tab:
I am really sorry for long question, i am pretty confused why isn't my ajax working.So in short:
-Why does Explode returns Undefined Index : 0 in... ? If you need any more information, ask ! Thank you!