Image AJAX search not working in Safari - php

I have a live image search that uses AJAX and an SQL query to find images with a name the same as the users input on a text field. I thought it was working fine until I tested in Safari, and it does literally nothing.
I'm not too sure why not even an error is returned in Safari, does anyone know of an issue in Safari that might be stopping it from working?
jQuery:
var input = $('.image-search');
var value;
var append = $(".results-append");
var loadUrl = '/stock-image-search.php';
var results = $('.results');
var resultsDiv = '<div class="results-heading"><h2>Results for "<span class="results-for"></span>"</h2></div>';
var resultsFor;
var nothingFound = '<div class="nothing-found"><br /><span>No results found.</span></div>'
// on keyup
input.on("keyup", function() {
// remove everything that was there
$('.results-append').remove();
results.empty();
$("#temp_load").remove();
value = input.val();
append.prepend(resultsDiv);
resultsFor = $('.results-for');
resultsFor.html($(this).val());
// ajax the results!
$.ajax({
type: "GET",
data: {
nameLike: value
},
dataType: "html",
url: templateDir + loadUrl,
beforeSend: function() {
append.hide().append('' +
'<div id="temp_load" class="search-loader">' +
'<img src="' + templateDir + '/img/load.GIF" />' +
'</div>'
).fadeIn(200);
},
success: function(data) {
$("#temp_load").fadeOut(200);
// fix for fast typers
results.empty();
var data = $(data);
if (data.length) {
results.append(data);
} else {
results.append(nothingFound);
}
},
error: function(jqXHR, textStatus, errorThrown) {
$("#temp_load").fadeOut(200).remove();
console.log(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
});
PHP function:
<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/wp-load.php' );
global $wpdb;
if( isset($_GET['nameLike']) && strlen($_GET['nameLike']) > 1 ) :
$search = $_GET['nameLike'];
$results = $wpdb->get_results( $wpdb->prepare("
SELECT ID
FROM $wpdb->posts
WHERE $wpdb->posts.post_status = 'inherit'
AND $wpdb->posts.post_mime_type != ''
AND ( $wpdb->posts.post_author = 1 OR $wpdb->posts.post_author = 3 )
AND $wpdb->posts.post_title LIKE %s
", '%' . like_escape($search) . '%'
), ARRAY_A);
foreach ($results as $result) : ?>
<?php
$image = wp_get_attachment_image( $result[ID], array(200, 150) );
?>
<div class="grid-1-4 clearfix">
<div class="stock-image-select clearfix" data-id="<?php echo $result[ID]; ?>">
<?php echo $image; ?>
</div>
</div>
<?php endforeach;
else : ?>
<div class="grid-10">Your search needs to be at least 2 characters long.</div>
<?php endif; ?>
If anyone can see a glaring error, please let me know :)

Try something like this
$(document).ready(function() {
$('input[name="search_field"]').keyup(function(e){
$(this).text;
//process your search
});
});
When you detect a key was raised then take the text and do the search.

Related

Product didn't diplay on ecommerce website

i created the e-commerce website. category and brands both are displayed successfully.
my problem is if I click the category. the product should display based on the category what I clicked. Example: if I click Tv as a category all tv product should display.like that
what i tried so far. i attached the code below.when i running the programming and click the category i got the error as "Uncaught ReferenceError: cid is not defined"
This code I wrote for display category but all category displayed successfully.
$('#categories').append('' + '<b>'+ data[i].catname + '<b>' + '');
Full code for category
Category
function getCategory(){
$.ajax({
type: 'GET',
url: 'get_category.php' ,
dataType: 'JSON',
success: function (data)
{
for (var i = 0; i < data.length; i++)
{
var catname = data[i].catname;
var id = data[i].id;
$('#categories').append('' + '<b>'+ data[i].catname + '<b>' + '');
}
},
error: function (xhr, status, error)
{
console.log(xhr.message)
}
});
}
}
when i click the category the relevant product should be displayed I wrote the code below
$("#categories").click(function ()
{
$.ajax({
type: 'post',
url: 'get_product.php' ,
data: {cid:cid},
dataType: 'JSON',
success: function (data) {
console.log(data);
for (var i = 0; i < data.length; i++)
{
var price = data[i].price;
var image = data[i].image;
var description = data[i].description;
$("#Products").append("<div class='col-md-4'> " +
"<div class='panel panel-info' id='Products'>" +
"<div class='card-body'>" +
"<div class='panel-heading'>" + "<h4> " + description + "</h4> " +
"<p class='panel-body'>"+ "<h3> " + price + "</h3>" +
"<p class='panel-body'> <img class='card-img-top' style='width:250px' height='250px' id='theImg' src='images/" + image + "' /> </p>" +
" <a href='#' class='btn btn-primary'>View More</a> </div> </div></div> </div>");
}
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});
});
get_product.php page
<?php
include("db.php");
$stmt = $conn->prepare("select id,cat_id,brand_id,price,description,image,keywords from products where id = ? order by RAND() LIMIT 0,6");
$stmt->bind_result($id,$cat_id,$brand_id,$price,$description,$image,$keywords);
$cid = $_POST["cid"];
$stmt->bind_param("s", $cid);
if ($stmt->execute()) {
while ( $stmt->fetch() ) {
$output[] = array ("id"=>$id, "cat_id"=>$cat_id,"brand_id"=>$brand_id,"price"=>$price,"description"=>$description,"image"=>$image,"keywords"=>$keywords);
}
echo json_encode($output);
}
$stmt->close();
?>
I think this gives you error, you need to get clicked category id
var cid = $(this).attr('cid'); // Use this and try
data: {cid:cid},
You are calling click event on categories; you should call click event on a tag;
Replace you click event;
$("#categories").click(function ()
{
// You code here
}
with this code;
$("a.list-group-item").click(function ()
{
var cid = $(this).attr('cid');
// You code here
}
Hope this will be useful for you!

JSON values not showing properly

I wrote a php script which accept POST request from ajax and give the response back. All working fine. But the receiving string split letter by letter I can't understand what is the reason.
Here is my AJAX code,
$("#btn").click(function(){
console.log($("#search_bar").val());
var dataV;
var htmlText = '';
var containerbootsrap = '';
var filename = '';
var index_no;
$.ajax({
type: "POST",
crossDomain: true,
url: "http://localhost:8090/ontology/setText",
data: $("#search_bar").val(),
contentType: 'text/plain',
// dataType: "json",
success: function( data, textStatus, jQxhr ){
console.log('data');
console.log(data);
for( var item in data) {
console.log ("item: " + item);
console.log ("data: " + data[item]);
index_no = data[item];
// htmlText += '<div class="div-conatiner">';
// htmlText += '<p class="p-name"> Name: ' + data[item] + '</p>';
// htmlText += '<img class="imageload" src="' + data[item] + '" />';
// htmlText += '</div>';
// filename = data[item].replace(/^.*[\\\/]/, '')
$.ajax({
data: 'index_no=' + index_no,
url: 'retrivedata.php',
method: 'POST', // or GET
dataType: 'json',
success: function(msg) {
console.log(msg);
for(var item in msg){
console.log ("item: " + item);
console.log ("data: " + msg[item]);
}
$('#home').hide();
containerbootsrap += '<div class = "container" id="search_container">';
containerbootsrap += '<div class = "row homepage">';
containerbootsrap += '<div class = "col-md-5 col-md-offset-3">';
containerbootsrap += '<a href="#" class="thumbnail">';
containerbootsrap += '<img class="imageload" src="' + msg + '" />';
containerbootsrap += '<h3 id="video_name"> ' + filename + ' </h3>'
containerbootsrap += '</a>';
containerbootsrap += '</div>';
containerbootsrap += '</div>';
containerbootsrap += '</div>';
$('body').append(containerbootsrap);
}
});
// $.post('retrivedata.php', { num: 5 }, function(result) {
// alert(result);
// });
// $('#home').hide();
}
// $('body').append(containerbootsrap);
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( jqXhr );
alert(jqXhr)
}
});
});
php code is below
<?php
$index_no = $_POST["index_no"];
// echo $index_no * 2;
include('dbConnection.php');
$query = mysql_query("SELECT * FROM video_data WHERE index_no = $index_no");
while ($row = mysql_fetch_assoc($query)) {
$imagePath = $row['thumbnail_url'];
$videoPath = $row['video_url'];
// echo $imagePath;
// echo $videoPath;
echo json_encode($imagePath);
}
?>
I need the output as : 'imagepath'
but it is giving the output as split letter by letter.
here is the real output
Output
but i need the output in one line. like /video_frames/bb/frame136.jpg
please help me to figure out where I am going wrong.
Well, in the php code where you're returning the value you need to specify an array not an string. The variable there $imagePath seems to be a string. You can do something like this.
echo json_encode(array('result' => $imagePath));
This will give you your result in the 'result' key. You can parse it and use it.
You need to parse the returned JSON string into an array. One way to do it is by adding data = $.parseJSON(data) in the ajax success callback (highlighted below). I was able to recreate the same thing you're seeing and adding this line fixed it. Hope this helps. parseJSON()
...
success: function( data, textStatus, jQxhr ){
console.log('data');
console.log(data);
data = $.parseJSON(data);
for( var item in data) {
console.log ("item: " + item);
console.log ("data: " + data[item]);
index_no = data[item];
...
Better way to check the type of value in variable you are getting first like
data = '{"name": "Bhushan"}' //string value
data = {name: "Bhushan"} //object value
//for testing you can use either, this will make it unbreakable for this context
if(typeof(data) == 'string')
{
data = JSON.parse(data)
}
//rest of code
This will give your module good stability otherwise you may get json parse unexpected token o.

Display new row inserted after ajax callback

Here there is my code which insert a row in ajax, it's working perfectly.
I need to display the new row that the user inserted inside my select multiple without reload the page but i don't know how to do ..
Thank you for you help
Ajax call :
$('#insertForm').on('click', function(){
var form_user = $('input[name=form_user]').val();
var form_intitule = $('input[name=form_intitule]').val();
var form_organisme = $('input[name=form_organisme]').val();
var form_date = $('input[name=form_date]').val();
var form_benefice = $('textarea[name=form_benefice]').val();
var form_dispositif = $('#form_dispositif').val();
var form_entpro_ActionAutre = $('input[name=entpro_ActionAutre]').val();
$.ajax({
type: "GET",
url: "lib/function.php?insertForm="+insertForm+"&form_user="+form_user+"&form_intitule="+form_intitule+"&form_organisme="+form_organisme+"&form_date="+form_date+"&form_benefice="+form_benefice+"&form_dispositif="+form_dispositif+"&form_entpro_ActionAutre="+form_entpro_ActionAutre,
dataType : "html",
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest + '--' + textStatus + '--' + errorThrown);
},
success:function(data){
}
});
});
My select multiple in function.php :
$displayFormation = $bdd->prepare('SELECT * FROM FORMATION WHERE form_id_user = :idSalarie ORDER BY form_date DESC');
$displayFormation->bindParam(':idSalarie', $_POST['idSalarie']);
$displayFormation->execute();
$data['formation'] .='
<div class="form-group">
<label for="nomSalarie" class="col-sm-1 control-label" id="nameSelect">Formations</label>
<div class="col-sm-11">
<select name="listeFormation[]" id="listeFormation" class="form-control" multiple>';
while($ligne = $displayFormation->fetch()){
$data['formation'] .='<option value="'. $ligne['form_id'].'">'.$ligne['form_intitule']. " [" . $ligne['form_organisme'] . "]". " [Année : " . dateAnglaisVersFrancaisAnnee($ligne['form_date']) . "]" . " [Bénéfices : " . $ligne['form_benefice'] . "]" . " [Dispositif : " . $ligne['form_dispositif'] . "]".'</option>';
}
$data['formation'] .='
</select>
</div>
</div>';
I am going to make some guesses and also some suggestions. Without knowing what your resulting data is going to be, it's hard to answer fully.
My working example and tests: https://jsfiddle.net/Twisty/053q24dh/
Here is the JQuery I would advise:
$('#insertForm').on('click', function() {
var form_user = $('input[name=form_user]').val();
var form_intitule = $('input[name=form_intitule]').val();
var form_organisme = $('input[name=form_organisme]').val();
var form_date = $('input[name=form_date]').val();
var form_benefice = $('textarea[name=form_benefice]').val();
var form_dispositif = $('#form_dispositif').val();
var form_entpro_ActionAutre = $('input[name=entpro_ActionAutre]').val();
$.ajax({
type: "GET",
url: "lib/function.php",
data: {
"insertForm": insertForm,
"form_user": form_user,
"form_intitule": form_intitule,
"form_organisme": form_organisme,
"form_date": form_date,
"form_benefice": form_benefice,
"form_dispositif": form_dispositif,
"form_entpro_ActionAutre": form_entpro_ActionAutre,
},
dataType: "html",
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest + '--' + textStatus + '--' + errorThrown);
},
success: function(data) {
// Asumming the page returns the following HTML, or something similar:
// <option value="9">Title [Organize] [Année : 02/02/16] [Bénéfices : 1] [Dispositif : 1]</option>
$("#listeFormation").append(data);
}
});
});
Again, this assumes that the HTML that is being returned to data is a single option tag to be appended to the select object. It looks like your PHP in the Post is looking for POST and your ajax is making a GET, so I am assuming they are different PHP Scripts. If they are not, you need to make sure the PHP knows how to respond properly and is not sending back too much data.
Also, I noticed that insertForm is not defined in this code snippet. If it's defined globally, that's fine, otherwise you need to define it within the scope of this function.

PHP - variable from GET is changing

I have a svg.php file with some shapes.
<rect onclick="window.location='search.php?filter=1'" width="50" height="50">
<rect onclick="window.location='search.php?filter=2'" width="50" height="50">
Search.php
div class="container">
<textarea class="search" id="search_id"></textarea>
<div id="result"></div>
<?php include("svg.php"); ?>
</div>
//This is for a autocomplete search, took it from http://www.2my4edge.com/2013/08/autocomplete-search-using-php-mysql-and.html
<script type="text/javascript">
$(function(){
$(".search").keyup(function() {
var search_id = $(this).val();
var dataString = 'search='+ search_id;
if (search_id=='') {
$.ajax({
type: "POST",
url: "search_database.php",
data: dataString,
cache: false,
success: function(html) {
$("#result").html(html).hide(); }
});
};
if(search_id!='') {
$.ajax({
type: "POST",
url: "search_database.php",
data: dataString,
cache: false,
success: function(html) {
$("#result").html(html).show(); }
});
}return false;
});
jQuery("#result").live("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find('.name').html();
var decoded = $("<div/>").html($name).text();
$('#search_id').val(decoded);
});
jQuery(document).live("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search")){
jQuery("#result").fadeOut();
}
});
$('#search_id').click(function(){
jQuery("#result").fadeIn();
});
});
</script>
Then a search_database.php
$search = isset($_GET['filter']) ? $_GET["filter"] : 1;
echo $search; //echos "2".
if ($search=="1") {
echo $search; //enters if, and it's not supposed to, and echos "1"
Select * from table;
}
Search_database.php
$search = isset($_GET['filter']) ? $_GET["filter"] : "1";
echo $search //echos "2";
if ($search=="1") {
$q = $_POST['search'];
$q_length = strlen($q);
$sql = <<<SQL
SELECT * FROM table
LIMIT 6
SQL;
if(!$result = $con->query($sql)){
die('There was an error running the query [' . $con->error . ']');
}
while($row = $result->fetch_array()) { ?>
<div class="show_search">
<?php echo $row['name'] ?> </a>
</div>
<?php } } ?>
I'm on search.php?filter=2 and the first echo is correct ("2") but for some reason it keeps entering the If Clause and echos that $search is "1".
I'm not defining the $search variable anywhere else. Thank you for your help.
Your code is a bit too complicated.
$search = isset($_GET['filter']) ? $_GET["filter"] : 1;
if($search == 1) {
echo $search;
}
Thats enough, you don't need the check if $_POST is available. That make not so much sense because you don't send a form and you don't have post data in that case when you it with window.location.
If there is no other code between following two lines:
echo $search; //echos "2".
AND
if ($_POST AND $search=="1") { ... }
Then, its not possible to go inside if condition. its only possible if your if condition is like if($_POST AND $search=1). Check that, whether you have single = or double == in comparing $search variable.
If there is some php code in between, then show us, whatever it is, so that we can help you.

Jquery Ajax Each function returns double

I have a Jquery Function that basically retrieves a list of users from the data base and inserts the information into divs. The problem is that im getting double reults, this is my first time retrieving from the database, Ive only ever sent to the database.. Any Help will be Greatly appreciated.
Thanks :)
Heres the Jquery Code:
$(function () {
$.ajax({
url: 'data.php',
data: "",
dataType: 'json',
success: function(rows) {
for (var i in rows) {
var row = rows[i];
var id = row[0];
var name = row[1];
var mobile = row[2];
var address = row[3];
var email = row[4];
$.each(rows, function() {
$('#contain').append('<div id="name">' + '<span>' + name + '</span>' + '</div>' + '<div id="id">' + id + '</div>' + '<div id="mobile">' + mobile + '</div>' + '<div id="address">' + address + '</div>' + '<div id="email">' + email + '</div>');
});
}
}
});
});
and the PHP:
$result = mysql_query("SELECT * FROM $tableName");
$data = array();
while ( $row = mysql_fetch_row($result) )
{
$data[] = $row;
}
echo json_encode( $data );
I think the problem is here:
$.each(rows, function (){
$('#contain').append('<div id="name">'+'<span>'+name+'</span>'+'</div>'+'<div id="id">'+id+'</div>'+'<div id="mobile">'+mobile+'</div>'+'<div id="address">'+address+'</div>'+'<div id="email">'+email+'</div>');
});
you should do just
$('#contain').append('<div id="name"><span>'+name+'</span></div><div id="id">'+id+'</div><div id="mobile">'+mobile+'</div><div id="address">'+address+'</div><div id="email">'+email+'</div>');

Categories