Solved

Json result print in html

Posted on 2016-09-27
31
74 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
ID: 41817547
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
ID: 41817554
$('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
ID: 41817565
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 52

Expert Comment

by:Julian Hansen
ID: 41817628
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 52

Expert Comment

by:Julian Hansen
ID: 41817630
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
ID: 41817637
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 33

Expert Comment

by:ste5an
ID: 41817638
What client-side frameworks do you use?
0
 
LVL 52

Expert Comment

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

Author Comment

by:Amita Singh
ID: 41817640
i use core php and mysql.
0
 
LVL 2

Author Comment

by:Amita Singh
ID: 41817643
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
ID: 41817664
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 52

Expert Comment

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

Expert Comment

by:ste5an
ID: 41817745
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
ID: 41818166
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 52

Expert Comment

by:Julian Hansen
ID: 41818241
What typeahed library are you using - please post so we can compare.
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 33

Expert Comment

by:ste5an
ID: 41818268
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
ID: 41819162
use  typeahead.min.js file.
typeahead.min.js
0
 
LVL 52

Expert Comment

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

Expert Comment

by:ste5an
ID: 41819280
Why not using custom templates?
0
 
LVL 2

Author Comment

by:Amita Singh
ID: 41819328
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 52

Expert Comment

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

Author Comment

by:Amita Singh
ID: 41819366
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 33

Expert Comment

by:ste5an
ID: 41819369
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
ID: 41819450
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 33

Expert Comment

by:ste5an
ID: 41819460
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 52

Accepted Solution

by:
Julian Hansen earned 500 total points
ID: 41819461
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
ID: 41819466
yes i want that which you are thing.
0
 
LVL 2

Author Closing Comment

by:Amita Singh
ID: 41819477
Thank you. thanks a lots. :)
0
 
LVL 52

Expert Comment

by:Julian Hansen
ID: 41819496
You are welcome.
0
 
LVL 2

Author Comment

by:Amita Singh
ID: 41821265
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 52

Expert Comment

by:Julian Hansen
ID: 41821275
This is starting to sound like a Gigs project.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

895 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

11 Experts available now in Live!

Get 1:1 Help Now