Solved

Json result print in html

Posted on 2016-09-27
31
67 Views
Last Modified: 2016-09-29
json response ( PHP,Photoshop,Javascript,Wordpress,Drupal,PHP Developer ) i want result print in ul li.
example :
 <ul>
<li>PHP</li>
<li>Photoshop</li>
</ul>
0
Comment
Question by:Amita Singh
  • 13
  • 10
  • 6
  • +1
31 Comments
 
LVL 35

Expert Comment

by:Terry Woods
Comment Utility
Something like this, provided the JSON is valid and stored in $json_string:
$list = json_decode($json_string);
print "<ul>\n";
foreach ($list as $item) {
  print "<li>$item</li>\n";
}
print "</ul>\n";

Open in new window

0
 
LVL 2

Author Comment

by:Amita Singh
Comment Utility
$('input.typeahead').typeahead([{  
                        name: 'typeahead',
                        valueKey: 'skill',
                        remote: {
                              url: 'ajax_search.php?key=%QUERY',
                              filter: function (parsedResponse) {
                                    // parsedResponse is the array returned from your backend
                                    console.log(parsedResponse);
                                     // do whatever processing you need here
                                    
                                    return parsedResponse;
                              }
                        },                                            
                                                                                       
                  }]);


ajax_search.php code is

require 'admin/conn/MySQL.php';
$dbcon =  new MySQL();
    $key=$_GET['key'];
      $type=$_GET['jobSeeker'];
    $array = array();
    $query=mysql_query("select * from skills_admin where skill LIKE '%{$key}%' limit 0,15");
      while($row=mysql_fetch_assoc($query)){
        $array[] = $row['skill'];
    }
      echo json_encode($array);

its print only echo json_encode($array). if i use print_r or anyting else its none results.
sorry for my poor english and thanx help me.
0
 
LVL 35

Expert Comment

by:Terry Woods
Comment Utility
Ok, the code you're after will need to be written in javascript then. I've added the AJAX topic to the question, as I've run out of time to help tonight.
0
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
Can you post your exact JSON response. You can get this from the console (F12) - the GET entry can be expanded the Response tab should have the raw JSON string. Can you post that so we can see exactly what we are dealing with.

In principle though you will want something like this
var ul = $('<ul/>');
for(var r in parsedResponse) {
   ul.append($('<li/>').html(parsedResponse[r]));
}
// Change to the element you want to add the <ul> to
$('#someid').append(ul);

Open in new window

0
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
As a matter of interest - any particular reason you not rendering the list on the server and just sending back the html?
0
 
LVL 2

Author Comment

by:Amita Singh
Comment Utility
i used typeahead js.
Html is
<input type="text" id="skills" name="skills" class="col-md-12" value="<?php echo $userData['key_skills']; ?>" readonly style="width:100      %; background-color:#ccc;padding:1px 3px; margin-left:3px; cursor:pointer; float:right; margin-left:5px;">
                               <span style="float:right; margin-top:-25px; font-weight:bold;font-size:15px; cursor:pointer; position: relative;" id="clear_skills" title="Clear Skills">&nbsp;X&nbsp;</span>
                        <br/><br/>
                           <input type="text" name="typeahead" value="" class="typeahead tt-query form-control col-md-12" autocomplete="off" placeholder="Add More Skills" style="width:200px;">
this result i get

but i need 1.png this. the record exits database or not it show this type and delete one by one. please help me i spend more than3 days .
0
 
LVL 32

Expert Comment

by:Stefan Hoffmann
Comment Utility
What client-side frameworks do you use?
0
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
Please send your JSON as requested in my earlier post.
0
 
LVL 2

Author Comment

by:Amita Singh
Comment Utility
i use core php and mysql.
0
 
LVL 2

Author Comment

by:Amita Singh
Comment Utility
Julian Hansen can u please send me your email address i will send u site link and user name password
0
 
LVL 2

Author Comment

by:Amita Singh
Comment Utility
Json response

["PHP","Photoshop","Javascript","Wordpress","Drupal","PHP Developer","Pharmacy","SAP ABAP","SAP COnsultant"
,"ABAP Consultant","Wordpress CMS","Graphics Designer","Computer Operator","iOS Developer","Android Developer"
]
0
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
I am not familiar with the filter function in typeahead / bloodhound - where is your reference for that?
0
 
LVL 32

Expert Comment

by:Stefan Hoffmann
Comment Utility
Well, then you should consider using some. Like jQuery and knockoutjs:

E.g.
<!-- saved from url=(0016)http://localhost -->
<!DOCTYPE html>
<html>
    <head>
        <meta charset='utf-8'>
        <meta http-equiv='X-UA-Compatible' content='IE=edge'>
        <script src='jquery-3.1.0.min.js' type='text/javascript'></script>
        <script src='knockout-3.4.0.min.js' type='text/javascript'></script>
        <script>
            $(document).ready(function() {
                ViewModelContainer = new ViewModel();
                ko.applyBindings(ViewModelContainer);
                $.getJSON('/some/url', function(data) {
                    ViewModelContainer.Jobs(data);
                })
                .done(function() {
                    console.log('success: got data from AJAX.');
                    console.log(ko.toJSON(data, null, 2));
                })
                .fail(function() {
                    console.log('error: AJAX call failed.');
                    console.log('error: running with simulated data.');
                    ViewModelContainer.Jobs([
                        'PHP',
                        'Photoshop',
                        'Javascript',
                        'Wordpress',
                        'Drupal',
                        'PHP Developer',
                        'Pharmacy',
                        'SAP ABAP',
                        'SAP COnsultant',
                        'ABAP Consultant',
                        'Wordpress CMS',
                        'Graphics Designer',
                        'Computer Operator',
                        'iOS Developer',
                        'Android Developer'
                        ]);
                });
            });
        </script>
        <script>
            var ViewModelContainer;
            function ViewModel() {
                var self = this;
                self.Jobs = ko.observable(null);
            }
        </script>
    </head>
    <body>
        <p>Jobs
        <ul data-bind="foreach: Jobs">
            <li data-bind="text: $data"></li>
        </ul>
    </body>
</html>

Open in new window


As jsfiddle.
0
 
LVL 2

Author Comment

by:Amita Singh
Comment Utility
This is a code i m using for key skill.

HTML code

<div class="form-group">
      <input type="text" id="skills" name="skills" class="col-md-12" value="<?php echo $userData['key_skills']; ?>" readonly style="width:100      %; background-color:#ccc;padding:1px 3px; margin-left:3px; cursor:pointer; float:right; margin-left:5px;">
      <span style="float:right; margin-top:-25px; font-weight:bold;font-size:15px; cursor:pointer; position: relative;" id="clear_skills" title="Clear Skills">&nbsp;X&nbsp;</span>
<br/><br/>
   <input type="text" name="typeahead" value="" class="typeahead tt-query form-control col-md-12" autocomplete="off" placeholder="Add More Skills" style="width:200px;">
</div>

ajax_search.php

<?php
require 'admin/conn/MySQL.php';
$dbcon =  new MySQL();
    $key=$_GET['key'];
      $type=$_GET['jobSeeker'];
    $array = array();
    $query=mysql_query("select * from skills_admin where skill LIKE '%{$key}%' limit 0,15");
      while($row=mysql_fetch_assoc($query)){
        $array[] = $row['skill'];
    }
      echo json_encode($array);
      
      
?>

my js code

$('input.typeahead').typeahead([{  
      name: 'typeahead',
      valueKey: 'skill',
      remote: {
            url: 'ajax_search.php?key=%QUERY',
            filter: function (parsedResponse) {
                  var html = "<p>({parsedResponse})</p>";
                  var html1 = "<span><a href='#'>X</a></span>";
                  alert(html+html1);
                  // parsedResponse is the array returned from your backend
                  console.log(parsedResponse);
                   // do whatever processing you need here
                  
                  return parsedResponse;
            }
      },                                            
                                                                                                   
}]);

$(".typeahead").focusin(function(){
      console.log(this.value);
      if(this.value!='') {
            var skills = $("#skills").val();
            
            var ifSkillAlreadyExist = skills.indexOf(this.value + ",");   // ifSkillAlreadyExist ending till , comma
            //console.log((checkString.match(/,/g) || []).length);       // Check Occurance count of , (comma)
            if(ifSkillAlreadyExist == '-1') {
            
                        $("#skills").val(skills + this.value + ", " );
            
            counter ++;
            } else { alert('You have already selected this skill.');}
      }
      this.value = "";
});
0
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
What typeahed library are you using - please post so we can compare.
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 32

Expert Comment

by:Stefan Hoffmann
Comment Utility
And a) please use the CODE button to embed code in your post and b) post concise and complete examples.
0
 
LVL 2

Author Comment

by:Amita Singh
Comment Utility
use  typeahead.min.js file.
typeahead.min.js
0
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
Ok I have that working with my sample - now what is it you are trying to achieve?
0
 
LVL 32

Expert Comment

by:Stefan Hoffmann
Comment Utility
Why not using custom templates?
0
 
LVL 2

Author Comment

by:Amita Singh
Comment Utility
i want this type
1.png
every skill delete one by one.  either it will be exits in our database or not. their should be a option to delete the data.

for ex. like this
 http://www.jqueryscript.net/demo/jQuery-jQuery-UI-Plugin-For-Simle-Tokenized-Autocomplete-Autocomplete-Multiselect/http://www.jqueryscript.net/demo/jQuery-jQuery-UI-Plugin-For-Simle-Tokenized-Autocomplete-Autocomplete-Multiselect/

it's all record come to data base but i want i also add my custom keyword like i add Amita.
0
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
Why are you not just using the Autocomplete Multiselect plugin that site uses?
0
 
LVL 2

Author Comment

by:Amita Singh
Comment Utility
i used but client say i want also add custom data. in autocomplete we don't add any custom data.
for ex. in my db 3 records (php , joomla, wordpress). client say if i want add magento, its add is autocomplete filed and also delete option in this like autocomplete.
(sorry for  my poor english )
0
 
LVL 32

Expert Comment

by:Stefan Hoffmann
Comment Utility
It sounds like your customer wants to add a lookup entry to your database. Thus you need imho a management view to handles this values.

Can post your sketch-up (wireframe) of this process?
0
 
LVL 2

Author Comment

by:Amita Singh
Comment Utility
3.png
In this image you see php and mysql its exits data base. amita is my name its not add in data base but when i enter amita its add and delete option is available. i want this.
0
 
LVL 32

Expert Comment

by:Stefan Hoffmann
Comment Utility
So it is:

- User enters partial topic.
- Search completion uses existing JS array for auto-complete. Array is prefilled from database.
Input box should not be restricted to auto-complete array.
- Entered topic should be displayed.

?

This means: that you need only to change your submit function to add new values to the auto-completion array and to store it in your database.
0
 
LVL 51

Accepted Solution

by:
Julian Hansen earned 500 total points
Comment Utility
This sort of works - you need to massage it
1. Create a container for the display of the items
<div class="skills-container"></div>

Open in new window

2. Modify typeahead filter
  $('input.typeahead').typeahead([{  
      name: 'typeahead',
      valueKey: 'skill',
      remote: {
        url: 't1638.php?key=%QUERY',
        filter: function (parsedResponse) {
          $('#errorvv').hide();
            // hide error here
            return parsedResponse;
        }
      },                                            
  }]);

Open in new window

3. Modify your focus code
  $(".typeahead").focusin(function(){
    if(this.value!='') {
      var skills = $("#skills").val();
      var ifSkillAlreadyExist = skills.indexOf(this.value + ",");   // ifSkillAlreadyExist ending till , comma
      //console.log((checkString.match(/,/g) || []).length);       // Check Occurance count of , (comma)
      if(ifSkillAlreadyExist == '-1') {
        $('.skills-container').append(
        $('<div/>', {
          class: 'skill-item',
          html: this.value
          }).append(
            $('<a/>', {
              class: 'skill-remove glyphicon glyphicon-remove'
            })
          )
        );
        
        if (skills.length > 0) skills += ', ';
        $("#skills").val(skills + this.value);
      } 
      else { 
        // Don't do this - rather add an error to the page
        //alert('You have already selected this skill.');
        $('#error').html('You have already selected this skill.').show();
      }
    }
    this.value = "";
  }); 

Open in new window

The above code adds a styled box to the new container.
CSS for the above is
<style type="text/css">
.skill-item {
  background-color: #f6f6f6;
  border: 1px solid #ccc;
  border-radius: 4px;
  color: #333;
  display: inline-block;
  margin-bottom: 3px;
  margin-right: 2px;
  padding: 1px 3px;
}
.skill-item a:hover {
  cursor: pointer;
}
</style>

Open in new window

Now you need to add an onclick handler for the x in the box
  $('body').on('click', '.skill-remove', function() {
    var val = $(this).parent().text();
    $(this).parent().remove();
    var inp = $('#skills').val().split(',');
    var res = [];

    while(inp.length > 0) {
      var top = inp.pop().trim();
      if (top != val) {
        res.push(top);
      }
    }

    $('#skills').val(res.join(', '));
  });

Open in new window


Sample here
1
 
LVL 2

Author Comment

by:Amita Singh
Comment Utility
yes i want that which you are thing.
0
 
LVL 2

Author Closing Comment

by:Amita Singh
Comment Utility
Thank you. thanks a lots. :)
0
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
You are welcome.
0
 
LVL 2

Author Comment

by:Amita Singh
Comment Utility
Hi Julian,
code is working fine  but i have faced 2 issue.

5.png
custom record show 2 times and than show error msg in 3rd time.

2nd point is i want to add a  button to submit a skill because when  i add custom skill i have click 2 and 3 times than its add.
6.png
and i want same skill format when i edit my profile.
0
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
This is starting to sound like a Gigs project.
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

jQuery is a JavaScript library that greatly simplifies JavaScript programming. AJAX is an acronym formed from "Asynchronous JavaScript and XML."  AJAX refers to any communication between client and server, when the human client does not observe a…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now