Link to home
Start Free TrialLog in
Avatar of Yuri Boyz
Yuri BoyzFlag for Uganda

asked on

Unable to fetch data from jQuery data attribute which holds array data

I am using Ajax to request the data. I am making an array and send it with json_encode so that I will receive the data in my Ajax Success function.
Now, here is my code:

$sql = "SELECT * FROM  mydata where id=15";		
			$rst = mysqli_query($conn,$sql) or die(mysqli_error($conn));					
			if (mysqli_num_rows($rst) > 0)
			{				
				while( $proj_gall_img = mysqli_fetch_array($rst) )
				{							
					$project_gallery_images[] = $proj_gall_img['img_name'];
					//$project_gallery_images.= $proj_gall_img['img_name']."|";
				}
				
			}
			
$projects_name[] = '<span data-id="' . $projects_row['id'].'" data-title="' . $projects_row['project_title'].'" data-detail="' . $projects_row['project_detail'].'" data-mimage="' . $projects_row['project_image'].'" data-mgallery="' . @$project_gallery_images.'"  class="li-txt" style="color:#ff0000;"><a id="myAnc" href="#">'.$projects_row['project_title'].'</a></span>';

Open in new window


The Problem:
I am easily fetched the value of following data attributes, data-id, data-title, data-detail, data-mimage but I am unable to get the value of data-mgallery in my ajax success function because this is an array.

In my this function I need to fetch this data:
jQuery('body').on('click', 'span.li-txt, span.li-txt2', function() {

var pid = jQuery(this).data('id');
var title = jQuery(this).data('title');
var detail = jQuery(this).data('detail');
var mimage = jQuery(this).data('mimage');	

var gallery = jQuery(this).data('mgallery');	
alert('length='+gallery.length);

Open in new window

The value of pid, title, detail and mimage retrieve successfully, but the value of gallery is Array. How to retrieve it?

Alternatively, how can I fetch the data in Ajax Success method?

Need help in this regard.

Thanks
ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Yuri Boyz

ASKER

thanks. let me check
Shano,

When I click on a project, the console shows a 404 Page Not Found error, so I can't see what you're trying to do.

Have you tried doing it the way I suggested earlier, and if so, what happened ?
The link is working fine

Then why does the console show a 404 Page Not Found Error when a project is clicked on!

Looking at your code, and you don't seem to have implemented my previous suggestion. You have this:

while( $proj_gall_img = mysqli_fetch_array($rst_galleries) )
{
    $count_map++;
    $project_gallery_images[] = $proj_gall_img['img_name'];
}

and then you have this:

$projects_name[] = '<div class="isotope">...
data-mapgallery="' . $project_gallery_images.'"

Nowhere in that code are you json_encoding the array like I've suggested.

Also, the code in the 2 files you've shown is different from the original code posted, so I don't know which code you're actually using.

The bottom line is that if you want to store an array of information in a data attribute, then you must json_encode it.
the 404 are due to missing images. Let me add json encode then I will update,.
When you cick on a Project link, the 404 is in response to a request for this page:

http://science-emporium.com.pk/map-seperate/sites/default/files/map/undefined
Here is the code with json_encode:                   
                  
			$projects_name[] = '<div class="isotope"><li class="color-shape isotope_selector '. $filter_class2.'" id="project-id-5a01bffbcfbeb40a008b458a" data-id="5a01bffbcfbeb40a008b458a">
			 <span data-id="' . $projects_row['id'].'" data-title="' . $projects_row['project_title'].'" data-detail="' . $projects_row['project_detail'].'" data-mapimage="' . $projects_row['project_image'].'" data-mapgallery="' . json_encode($project_gallery_images).'"  class="li-txt" style="color:#ff0000;"><a id="myAnc" href="#">'.$projects_row['project_title']."---".$projects_row['id'].'</a></span>
			 <span class="thumb-container">'.$filter_icons_all.'</span>
			 </li></div>';			
			

Open in new window


Sending it back                  
echo json_encode(array("message1" =>$projects_name,'message_2'=>$message_2, "message3" =>$projects_image,"project_title"=>$project_title,"project_detail"=>$project_detail,"project_image"=>$project_image,"project_gallery_image"=>$project_gallery_images));		

Open in new window

                 

jQuery Handler code:
var gallery  = JSON.parse( jQuery(this).data('mgallery') );

Open in new window


  I am receiving this error when I click project: Uncaught SyntaxError: Unexpected end of JSON input
  In my query i have set limit of 2 but this error still occur
Yeah - in my original comment, I did say that you'd need to wrap your data attibutes in single quotes - you've not done that!

Currently, you have this:

$projects_name[] = '<div class="isotope"><span data-id="' . $projects_row['id'].'" data-title="' . $projects_row['project_title'].'" ...

Open in new window

You'll see that your data attributes are wrapped in double quotes:

data-id="someValue" data-title="someValue"

Open in new window

They need to be wrapped in single quotes, so you'll need to do this:

$projects_name[] = "<div class='isotope'><span data-id='" . $projects_row['id']. "' data-title='" . $projects_row['project_title']. "' ...

Open in new window

Now you'll end up with

data-id='someValue' data-title='someValue'

Open in new window

Which will allow you to correctly send a JSON string through.
OK Shano,

This will be a lot clearer if you use the vsprintf() function:

$string = <<< STRING
<div class='isotope'>
    <li class='color-shape isotope_selector %s' id='project-id-5a01bffbcfbeb40a008b458a' data-id='5a01bffbcfbeb40a008b458a'>
        <span data-id='%s' data-title='%s' data-detail='%s' data-mapimage='%s' data-mapgallery='%s' class='li-txt' style='color:#ff0000;'>
            <a id='myAnc' href='#'>%s --- %s</a>
        </span>
        <span class='thumb-container'>%s</span>
    </li>
</div>
STRING;

$data = array(
    $filter_class2,
    $projects_row['id'],
    $projects_row['project_title'],
    $projects_row['project_detail'],
    $projects_row['project_image'],
    json_encode($project_gallery_images),
    $projects_row['project_title'],
    $projects_row['id'],
    $filter_icons_all,
);

$projects_name[] = vsprintf($string, $data);

Open in new window

It allows you to build the string in a clear way. Instead of trying to concatenate the values with quotes and dots, you can use placeholders - %s. Then you just pass the string, and an array of your data into the vsprintf() function.
I have converted string into single quote and add json_encode Now it works fine.,
Just one issue:

In my selector I am retrieving it in this way:
var gallery = jQuery(this).data('mapgallery');	

Open in new window

This one not works
var gallery  = JSON.parse( jQuery(this).data('mapgallery') );

Open in new window


Now this variable holds multiple file names. I need to append all images in a DIV. How is it possible?
                  I use this but this one holds all filenames
                  
			jQuery('.mydiv').html('<img src=http://localhost/proj/images'+gallery+' width=200px>');
			

Open in new window

OK. You may not need to call JSON.Parse on the data attribute as it should already be an array.

var gallery  = jQuery(this).data('mapgallery');

Now gallery will contain an array of your filenames, so you'll need to loop over that array and deal with each entry. Something like this:

jQuery.each( gallery, function(i, image) {
    jQuery('.mydiv').append('<img src="http://localhost/proj/images/' + image + '" style="width:200px">');
});

Open in new window

There is one issue. If the data from mysql contain single quote or double quote characters then my data is truncated after that character. While inserting the data I have also used addslashes and mysqli_real_escape_string functions but still it truncate the data. Any solution?