JSON values not showing properly - php

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.

Related

PHP - JSON to HTML

I am trying to display json_encode data from my back end controller to view using together with AJAX. The AJAX runs successfully and received the response that I needed. However, i am unable to display out on my HTML.
I have double-checked that there is certainly a response coming from the back end. Please do help me.
AJAX jQuery
$.ajax({
type: 'post',
url: 'index.php/Status/facility',
dataType: "json",
data: {id:id},
success: function (response) {
var len = response.length;
console.log(len);
for(var i=0; i<len; i++){
var id = response[i].facility_id;
var username = response[i].name;
var tr_str = "<li class='pointer' id='" + (i+1) + "' onclick='changeClass(this.id)'><a>" + name +"</a></li>";
$("#tabAjax").append(tr_str);
}
$('#exampleModalCenter').modal('show');
}
});
HTML
<ul class="nav nav-pills" id="tabAjax"></ul>
Controller
public function facility(){
echo json_encode($data);
//$this->load->view('templates/student/footer');
}
Response
{"facility_list":[{"facility_id":"1","name":"Table 1","facility_category":"1"}]}
I believe you need to access the data within facility_list so to do so firstly get a reference to that level of the response data and then iterate through it's child objects
var json=response.facility_list;
for( var n in json ){
var obj=json[n];
var id=obj.facility_id;
var name=obj.name;
var cat=obj.facility_category;
var tr_str = "<li class='pointer' data-category='"+cat+"' id='" + (n+1) + "' onclick='changeClass(this.id)'><a>" + name +"</a></li>";
$("#tabAjax").append( tr_str );
}
The best way to implement this handle it at backend. You can prepared html at backend and send prepared html in response(in any key of array) and append according that. That will be more easy to handle response and no need to reload page every time.
$response = array(array('facility_id' => 1, 'facility_category' => 2, 'name' => 'abc'));
$returnResponse = array('status' => 'false', 'data' => '');
$str = '';
foreach ($response as $key => $resp) {
$str .= '<li class="pointer" data-category="' . $resp['facility_category'] . '" id="' . ($key+1) . '" onclick="changeClass(this.id)"><a> ' . $resp['name'] . ' </a></li>';
}
$returnResponse['status'] = true;
$returnResponse['data'] = $str;
Now in js file you can use:-
var html = response.data;
and append above html where you want.

How to pass an array from PHP using AJAX

I'm having some issues displaying an array which I created in a PHP file. The response data in question is data["vessel"]
I have some jQuery:
j$('select[name=vessel]').change(function(e) {
var tour_ID = j$('select[name=tour]').val();
var trip_Date = j$('input[name=trip_Date]').val();
var data = {
"action": "Count_Vessels",
"trip_Date": trip_Date,
"tour_ID":tour_ID
};
data = j$(this).serialize() + "&" + j$.param(data);
j$.ajax({
type: "POST",
dataType: "json",
url: "../include/booking_Modify.php",
data: data,
success: function(data) {
//console.log("vessel stack: " + data["vessel"][0]);
var arr=JSON.parse(data["vessel"]);
console.log("vessel stack: " + arr[0]);
console.log("Form submitted successfully.\nReturned json: " + data["json"]);
},
error: function (request) {
console.log(request.responseText);
}
});
});
The PHP:
function count_Vessels(mysqli $conn, $trip_Date, $tour_ID){
$return = $_POST;
$vessel_Stack = array();
$vessel_Query = "SELECT * FROM Vessel";
if(!$vessel_Results = $conn->query($vessel_Query)){
die('There was an error running the query [' . $conn->error . ']');
}
while( $vessel_Row = $vessel_Results->fetch_assoc() ){
$vessel_Stack[$vessel_Row['ve_ID']] = $vessel_Row['vessel_Name'];
}
$return['vessel'] = $vessel_Stack;
$return["json"] = json_encode($return);
echo json_encode($return);
}
when I display data["json"] in console, I get Returned json: {"vessel":{"1":"Thriller","2":"Jammin","3":"Thunderstruck","4":"Wildthing","6":"Joyride"}
Which is awesome, but I don't know how to do that using the data["vessel"] Any help would be greatly appreciated.
I solved my own riddle. Because data["vessel"] is an array, I had to loop through it. Doing so like this worked:
j$.each(data["vessel"], function(key, val) {
console.log('index ' + key + ' value ' + val);
});

Image AJAX search not working in Safari

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.

Ajax function is not finding the right data

I have created an AJAX function and wondered why my JS was giving errors.
$(document).ready(function() {
$('#more').click(function() {
var tag = $(this).data('tag'),
maxid = $(this).data('maxid'),
url = $(this).data('root'),
id = $(this).data('id'),
count = $(this).data('count');
$.ajax({
type: 'GET',
url: '/ajax',
data: {
tag: tag,
max_tag_id: maxid
},
dataType: 'json',
cache: false,
success: function(data) {
// Output data
$.each(data.images, function(i, src) {
$('section#images').append('<img src="' + data[src].images.standard_resolution.url + '">');
});
// Store new maxid
$('#more').data('maxid', data.next_id);
}
});
});
});
I have created a page that takes data from the instagram API and stores the data in an array so when I click more it loads more images into a container div.
Edit:
Below is the code on the php ajax page that encodes the array into json output:
$instagram = new Instagram\Instagram;
$instagram->setAccessToken($_SESSION['instagram_access_token']);
$token = $_SESSION['instagram_access_token'];
//$clientID = $_SESSION['client_id'];
$current_user = $instagram->getCurrentUser();
$tag = $instagram->getTag('folkclothing');
$media = $tag->getMedia(isset($_GET['max_tag_id']) ? array( 'max_tag_id' => $_GET['max_tag_id'] ) : null);
// Collect everything for json output
$images = array();
foreach ($media as $data) {
/* $collection = array($data->images->standard_resolution->url,$data->link,$data->getId(),$data->likes->count); */
/*
$images[] = $data->images->standard_resolution->url;
$images[] = $data->link;
$images[] = $data->getId();
$images[] = $data->likes->count;
*/
/*
$data_url[] = $data->images->standard_resolution->url;
$data_link[] = $data->link;
$data_id[] = $data->getId();
$data_likes[] = $data->likes->count;
$images[] = array($data_url);
*/
$images[] = array($data->images->standard_resolution->url,$data->link,$data->getId(),$data->likes->count);
}
echo json_encode(array(
'next_id' => $media->getNextMaxTagId(),
'images' => $images
));
The above code creates an array and then it gets converted to a json object but I am unsure how to split it into nested arrays for the image url, image id, likes and the image link. Is this possible to get nested arrays?
End of edit
It did work but I want to find specific elements inside this array so I created the AJAX function above.
The error I get is:
Uncaught TypeError: Cannot read property 'images' of undefined
Any help would be great.
try to replace
$.each(data.images, function(i, src) {
$('section#images').append(
'<img src="' + data[src].images.standard_resolution.url + '">'
);
});
with
$.each(data.images, function(i, src) {
$('section#images').append(
'<img src="' + src.standard_resolution.url + '">'
);
});
For the answer to this I ended up building my array up properly and using the json_encode
to get it all listed properly so I could pull the right data out like so.
ajax.php:
foreach ($media as $data) {
$images[] = array(
"data_url"=>$data->images->standard_resolution->url,
"data_link"=>$data->link,
"data_text"=>$data->getCaption(),
"data_id"=>$data->getId(),
"data_likes"=>$data->likes->count
);
}
echo json_encode(array(
'next_id' => $media->getNextMaxTagId(),
'images' => $images
));
This created the correct array of data.
I then corrected the js for it to work.
JS code:
$(".loading").hide();
$(document).ready(function() {
$('#more').click(function() {
var tag = $(this).data('tag'),
maxid = $(this).data('maxid');
$.ajax({
type: 'GET',
url: '/ajax',
data: {
tag: tag,
max_tag_id: maxid
},
dataType: 'json',
cache: false,
success: function(data) {
// Output data
$.each(data.images, function(i, src) {
var $content = $('<article class="instagram-image"><form class="forms" action="/image" method="post"><a class="fancybox" href="'+ data.images[i].data_link +'"><img alt="' + data.images[i].data_text + '" src="' + data.images[i].data_url + '" alt="' + data.images[i].data_text + '" /></a><button class="ajax instabtn like icon-heart" type="submit" name="action" value="Like"></button><input type="hidden" name="id" value="'+ data.images[i].data_id +'"><p>'+ data.images[i].data_likes +'</p></form></article>');
$('section#images').append($content).fadeIn(1000);
});
// Store new maxid
$('#more').data('maxid', data.next_id);
}
});
});
});
I hope this helps people out who need that extra bit of information.
try this
....
success: function(data) {
// Output data
$.each(data.images, function(i, src) {
$('section#images').append(
'<img src="' + data[i].images.standard_resolution.url + '">'
//----^----here
);
});
// Store new maxid
$('#more').data('maxid', data.next_id);
}
Change data access in image tag
from
data[src].images.standard_resolution.url
^^^
to
data[i].images.standard_resolution.url
^
Here you are using Array of data.images, so you should use index of data.images
Try it like,
if(data.images)// check if data.images found, otherwise it will give error
{
$.each(data.images, function(i, src){
$('section#images').append(
'<img src="' + data.images[i].standard_resolution.url + '">'
// use i ----^----here
// or use src.standard_resolution.url directly
);
});
}

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