This code works perfectly, but when I will put the final HTML, only appears the values, but the HTML not. What is happening??
$('[role=query-username]').live( 'click', function() {
var output = "<table>";
$.post(
'/action/jsonUserInformation.php',
'username=' + $('#username').val(),
function(data) {
$('#user_results').html('');
var data_json = $.parseJSON( data );
$.each( data_json, function() {
$.each( this, function(i, v)
{
output = output + "<tr><td>" + i + "</td><td>" + v + "</td></tr>";
});
output = output + "</table>";
});
$('#user_results').html( output );
});
});
Result Output is:
code37username_code41account_passwordfb8465e62c8b2bd01d1d14965748b3e4account_status2account_type1creationdate2008-10-23mail_code39confirmedbb022e5a2419271daa2764f9cad5500crecoveryenabledreferrertimezonepreferred_currencycomission_plan1basemoney0privileges5paywaypersonal_info37last_update2008-10-23 00:00:00nameslastnamessexaddressphonemobilezipcitystatecountryidbusinessnameprofessionbirthdateaccount37usernamecjimenezhkemailyoyo#cjimenezhk.com
I'm not sure what you mean by "put the final HTML", but you should definitely move the
output = output + "</table>";
outside of your outer each loop.
Move it just before $('#user_results').html( output );
Related
I have a Jquery function that is using getJson. I am trying to form something like www.mysite.com/?state=oregon. According to Jquery ("Data that is sent to the server is appended to the URL as a query string..."), but I get all the values in the json data. What I am doing wrong.
Here is my code
function changeLine(line){
$('#table_lines').html('');
$.getJSON("../index.php", {, line}, function(data){
var line_data = '';
$.each(data, function(key, value){
line_data += '<tr id="' +value.line_id+'">';
line_data += '<td>' + otherValueTime(value.MatchTime)+'</td>';
line_data += '<td>' + value.home+'</td>';
line_data += '<td>' + value.away+'</td>';
for(i=0; i < value.Cases.length; i++){
console.log(value.Cases[i].CaseType + ' ' + value.Cases[i].CaseAway + ' ' + value.Cases[i].CaseHome);
if(value.Cases[i].CaseType === "Game"){
line_data += '<td>' + value.Cases[i].CaseAway +'</td>';
line_data += '<td>' + value.Cases[i].Total +'</td>';
line_data += '<td>' + value.Cases[i].Over +'</td>';
}
}
});
$('#table_lines').append(line_data);
});
}
On the line with this code "{, line}", I tried putting the key value from the json array, like {id: line}. What I want to do is to get a group of cases according to the key.
I would like to know how you do that. I want to change it according to the option value. I do get data from the server, but I get all the data. Here is how I call that function
$( "select" )
.change(function () {
var str = "";
$( "select option:selected" ).each(function() {
str = $( this ).val();
$.ajax({
method: "POST",
url: "../index.php",
data: { 'id' : str }
})
});
changeLinea(str);
})
.change();
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.
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.
I need to add some geo-marker to my map.
the markers are in my mysql table on altervista.org
but my JavaScript says [object Object] every time i try...
here my php code:
require('connect.php');
$query = "SELECT latit, longit FROM segnalazioni";
$result = mysql_query($query);
$rows = array();
while ($row = mysql_fetch_assoc($result)){
$rows[] = $row;
}
echo json_encode($rows);
it returns:
[{"latit":"12.34","longit":"12.34"},{"latit":"56.78","longit":"56.78"},...]
here my JavaScript:
function addMarker(mapobj) {
$.getJSON( "http://####.altervista.org/map.php", function( data ) {
var items = [];
$.each( data, function( key1 , val1 ) {
items.push( "<li id='" + key1 + "'>" + val1 + "</li>" );
//next todo:
//mapobj.marker([latit, longit]).addTo(map).bindPopup("hi");
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
}
and on the end of my [body] i can see only:
[object Object]
[object Object]
[object Object]
...
According to jquery.each the parameters are
indexInArray , value and NOT key, value
So the code is:
$(function () {
var data = [{"latit": "12.34", "longit": "12.34"}, {"latit": "56.78", "longit": "56.78"}];
var items = [];
$.each(data, function(indexInArray , value) {
items.push( "<li id='" + indexInArray + "'>latit: " + value.latit + ' longit:' + value.longit + ' OR '+ JSON.stringify(value) + "</li>" );
//next todo:
//mapobj.marker([latit, longit]).addTo(map).bindPopup("hi");
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
Use this
$.each(result, function(key, value){
$.each(value, function(key, value){
console.log(key, value);
});
});
I would also encourage to use header before sending JSON stream. It is always good to tell the content type sent in HTTP response. Use
header('Content-Type: application/json');
Before using
echo json_encode($rows);
How to pass my php array to this jquery code ?
i have tried json_encoding but couldnt use it in my jquery function.
my json string looks like this:
{"1":{"id":"1","league":"england","team1":"Arsenal","team2":"Chelsea"},"2":{"id":"2","league":"spain","team1":"Deportivo","team2":"Real Madrid"}}
JS:
<script type="text/javascript">
$(document).ready(function(){
var shownIds = new Array();
setInterval(function(){
$.get('livescore_process.php', function(data){
for(i = 0; i < data.length; i++){
if($.inArray(data[i]["id"], shownIds) == -1){
if(data[i]["league"]=="england"){
$("#eng").append("id: " + data[i]["team1"] + " [ "+data[i]["team1"]+ " - "+data[i]["team1"]+" ]"+ data[i]["team2"] +"<br />");
}
shownIds.push(data[i]["id"]);
}
}
});
}, 3000);
});
</script>
try $.getJSON instead of $.get and use php json_encode:
$.getJSON('livescore_process.php', function(data){...
however the response data is not an array but a json object, so to handle it you can try:
$.each(data, function (index, item) {
if (item.hasOwnProperty('id')) {
if (item.league == "england") {
$("#eng").append("id: " + item.team1 + " [ " + item.team1 + " - " + item.team1 + " ]" + item.team2 + "<br />");
}
shownIds.push(item.id);
}
});
jsfiddle