How to pass a php array with json to jquery function, ajax - php

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

Related

Can't read json elements from mysql query via ajax

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);

using array push in jquery by accessing php array variable

this is my php code:
if (($_SERVER["REQUEST_METHOD"] == "POST")&&(isset($_POST["btn_save"]))) {
$schoolsInput=$_POST['schoolsInput'];
echo $schoolsInput[0];
}
this is my jquery code:
<script type="text/javascript">
$(document).ready(function()
{
var counter=1;
var max_fields=5;
var add_button = $("#btn_addTxt");
var save_btn= $("#btn_save");
var wrapper= $("#prevSchoolTable");
$(add_button).click(function(e){
e.preventDefault();
if (counter == max_fields) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
$(wrapper).append('<tr><td><input type="text" name="schoolsInput' + counter + '" id="schoolsInput' + counter + '" class="textbox" style="width:400px;">'
+ '</td></tr>');
counter++;
}
});
var arrayFromPHP = <?php echo json_encode($schoolsInput); ?>;
$("#btn_save").click(function () {
var msg = '';
for(i=1; i<counter; i++){
msg += "\n " + $('#schoolsInput' + i).val();
}
alert(msg); \\array push must go here
});
});
</script>
I've search how can i access PHP variable and they say to use:
var obj = <?php echo json_encode($schoolsInput); ?>;
But everytime i put this on my jquery, the ADD function is not working.
any suggestion?

How to access part of an array in ajax

In my ajax, the PHP side contains an array with 3 values. I'd like to put these 3 values into separate input fields. How can I do this? How do I access the array sent from PHP?
My code so far:
PHP
$total['tot1'] = $numwelds + $numconwelds + $mpcountrys ;
$total['tot2'] = $numwelds + $numconwelds + $fortot2 ;
$total['tot3'] = $numwelds + $numconwelds + $fortot2 / $fortot3;
$response = json_encode($total);
header("Content-Type: application/json");
echo $response;
exit;
Jquery
jQuery(document).ready( function($) {
(function($) {
$(document).ready(function(){
$('#formsubmit').click(function(){
$.post(
PT_Ajax.ajaxurl,
{
action : 'ajax-inputtitleSubmit',
numberofwelds : $('input[name=numberofwelds]').val(),
numberofconwelds : $('input[name=numberofconwelds]').val(),
nextNonce : PT_Ajax.nextNonce
},
function( response ) {
$("#totalone").val(response);
$("#totaltwo").val(response);
$("#totalthree").val(response);
}
);
return false;
});
});
})(jQuery);
});
You can use JSON.parse to convert json to object:
var obj = JSON.parse(response);
$("#totalone").val(obj.tot1);
$("#totaltwo").val(obj.tot2);
$("#totalthree").val(obj.tot3);
Or you can also use $.parseJSON() of jQuery.
use like
$("#totalone").val(response["tot1"]);
$("#totaltwo").val(response["tot2"]);
$("#totalthree").val(response["tot3"]);

how to get result from mysql and display using jquery when radio button is clicked?

I would like to make a bus seating plan. I have seating plan chart using javascript function.I have two radio button named Bus_1 and Bus_2 queried from databases. When I clicked one of radio button, I would like to get available seats to show on the seating plan. Problem is I can't write how to carry radio value and to show database result on seating plan. Please help me.
<SCRIPT type="text/javascript">
$(function () {
var settings = { rowCssPrefix: 'row-', colCssPrefix: 'col-', seatWidth: 35, seatHeight: 35, seatCss: 'seat', selectedSeatCss: 'selectedSeat', selectingSeatCss: 'selectingSeat' };
var init = function (reservedSeat) {
var str = [], seatNo, className;
var shaSeat = [1,5,9,13,17,21,25,29,33,37,41,'#',2,6,10,14,18,22,26,30,34,38,42,'#','$','$','$','$','$','$','$','$','$','$',43,'#',3,7,11,15,19,23,27,31,35,39,44,'#',4,8,12,16,20,24,28,32,36,40,45];
var spr=0;
var spc=0;
for (i = 0; i<shaSeat.length; i++) {
if(shaSeat[i]=='#') {
spr++;
spc=0;
}
else if(shaSeat[i]=='$') {
spc++;
}
else {
seatNo = shaSeat[i];
className = settings.seatCss + ' ' + settings.rowCssPrefix + spr.toString() + ' ' + settings.colCssPrefix + spc.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) { className += ' ' + settings.selectedSeatCss; }
str.push('<li class="' + className + '"' +'style="top:' + (spr * settings.seatHeight).toString() + 'px;left:' + (spc * settings.seatWidth).toString() + 'px">' +'<a title="' + seatNo + '">' + seatNo + '</a>' +'</li>');
spc++;
}
}
$('#place').html(str.join(''));
}; //case I: Show from starting //init();
//Case II: If already booked
var bookedSeats = [2,3,4,5]; //**I don't know how to get query result in this array.This is problem for me **
init(bookedSeats);
$('.' + settings.seatCss).click(function () {
// ---- kmh-----
var label = $('#busprice');
var sprice = label.attr('pi');
//---- kmh ----
// var sprice= $("form.ss pri");
if ($(this).hasClass(settings.selectedSeatCss)){ alert('This seat is already reserved'); }
else {
$(this).toggleClass(settings.selectingSeatCss);
//--- sha ---
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) { item = $(this).attr('title'); str.push(item); });
var selSeat = document.getElementById("selectedseat");
selSeat.value = str.join(',');
//var amount = document.getElementById("price");
// amount.value = sprice*str.length;
document.getElementById('price').innerHTML = sprice*str.length;
return true;
}
});
$('#btnShow').click(function () {
var str = [];
$.each($('#place li.' + settings.selectedSeatCss + ' a, #place li.'+ settings.selectingSeatCss + ' a'), function (index, value) {
str.push($(this).attr('title'));
});
alert(str.join(','));
})
$('#btnShowNew').click(function () { // selected seat
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) { item = $(this).attr('title'); str.push(item); });
alert(str.join(','));
})
});
</SCRIPT>
You can use the onclick to tell AJAX to get your information and then what to do with it using jQuery.
<input type="radio" name="radio" onclick="ajaxFunction()" />
function ajaxFunction()
{
$.ajax({
type: "POST",
url: "you_script_page.php",
data: "post_data=posted",
success: function(data) {
//YOUR JQUERY HERE
}
});
}
Data is not needed if you are not passing any variables.
I use jQuery's .load() function to grab in an external php page, with the output from the database on it.
//In your jQuery on the main page (better example below):
$('#divtoloadinto').load('ajax.php?bus=1');
// in the ajax.php page
<?php
if($_GET['bus']==1){
// query database here
$sql = "SELECT * FROM bus_seats WHERE bus = 1";
$qry = mysql_query($sql);
while ($row = mysql_fetch_assoc($qry)) {
// output the results in a div with echo
echo $row['seat_name_field'].'<br />';
// NOTE: .load() takes this HTML and loads it into the other page's div.
}
}
Then, just create a jQuery call like this for each time each radio button is clicked.
$('#radio1').click(
if($('#radio1').is(':checked')){
$('#divtoloadinto').load('ajax.php?bus=1');
}
);
$('#radio2').click(
if($('#radio1').is(':checked')){
$('#divtoloadinto').load('ajax.php?bus=2');
}
);

jQuery is stripping out HTML, I don't know why

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 );

Categories