using array push in jquery by accessing php array variable - php

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?

Related

Jquery Scroll Loading All The Rows At Once And Should Only Load 5 At A Time

I am using the following script to load more, 5 rows at a time from the database, on scroll. All the rows are loading at once on scroll after the initial loads correctly. In realtime, the first 5 load. Then on scroll the last 14 load at once. Like it rushes to the end instead of incrementally loading 5 at a time. I use the same code for a load more button and it works fine. Same PHP file for both. No issue with that. Can anyone see why all the rows are being loaded on scroll instead of 5 at a time.
<script>
//SET NUMBER OF ROWS TO DISPLAY AT A TIME
rowsPerPage = 5;
$(document).ready(function() {
// GETTING DATA FROM FUNCTION BELOW
getData();
window.onscroll = function() {
if ($(window).scrollTop() >= $('#load-container').offset().top + $('#load-container').outerHeight() - window.innerHeight) {
$('#load-more').html('Loading...');
var rowID = Number($("#row-id").val());
var allCount = Number($("#count").val());
rowID += rowsPerPage;
if (rowID <= allCount) {
$("#row-id").val(rowID);
getData();
} else {
$('#load-more').html('End Of Data');
//$('#load-more').html('');
}
}
}
/* REQUEST DATA */
function getData() {
var rowID = $("#row-id").val();
var allCount = $("#count").val();
$('#load-more').html('Loading...');
$.ajax({
url: 'promotions/newest-load-scroll-data-invalid.php',
type: 'post',
data: {
rowID: rowID,
rowsPerPage: rowsPerPage
},
dataType: 'json',
success: function(response) {
setTimeout(function() {
loadData(response)
}, 1000);
},
});
}
/* LOAD DATA TO PAGE */
function loadData(data) {
var dataCount = data.length;
for (var i = 0; i < dataCount; i++) {
if (i == 0) {
var allCount = data[i]['allcount'];
$("#count").val(allCount);
} else {
var promoID = data[i]['promoid'];
var promoNameNewest = data[i]['promoname'];
var promoNameNewestVideo = data[i]['promoname'];
var promoRefNum = data[i]['promorefnum'];
var promoType = data[i]['promotype'];
var theBanner = data[i]['thebanner'];
var email = data[i]['email'];
var customerType = data[i]['customerType'];
if (email == "") {
if (promoType == "Banner") {
$('#load-container').append('<div class="row-center-center padding-top-5 padding-bottom-2"><div>' + promoNameNewest + '</div></div>');
$('#load-container').append('<div><div class="wrap-content"><img class="mobile-banner-scale" id="visitor-banner-click" src=' + theBanner + '></div></div>');
}
if (promoType == "Video Banner") {
$('#load-container').append('<div class="row-center-center padding-top-5 padding-bottom-2"><div>' + promoNameNewestVideo + '</div></div>');
$('#load-container').append('<div><video class="mobile-video-size" id="visitor-banner-click" src=' + theBanner + ' autoplay muted loop></video></div>');
}
}
if (customerType == "p") {
if (promoType == "Banner") {
$('#load-container').append('<div class="row-center-center padding-top-5 padding-bottom-2"><div>' + promoNameNewest + '</div></div>');
$('#load-container').append('<div><div class="wrap-content"><img class="mobile-banner-scale" id="advertiser-banner-click" src=' + theBanner + '></div></div>');
}
if (promoType == "Video Banner") {
$('#load-container').append('<div class="row-center-center padding-top-5 padding-bottom-2"><div>' + promoNameNewestVideo + '</div></div>');
$('#load-container').append('<div><video class="mobile-video-size" id="advertiser-banner-click" src=' + theBanner + ' autoplay muted loop></video></div>');
}
}
}
$('#load-more').html('Loading...');
}
}
});
</script>
I was able to utilize flags to make it work right with a couple other small changes. Appreciate the input, Taplar.

passing parameters to a php from javascript

I've done this before but for some reason the parameters are being passed oddly.
I have a javascript function that I've used to pass parameters, I've ran some tests and in the function the variables are correct.
These are just a few snippets of the js that relate to the issue:
var tdes = document.getElementById("taskDescription1").value;
var tnam = document.getElementById("taskName1").value;
var shif = document.getElementById("shift1").value;
var ttyp = document.getElementById("taskType1").value;
var date = document.getElementById("datepicker").value;
var ooc = document.getElementById("ooc1").value;
var dateSplit = date.split('/');
var deadlineDate = "";
for( var i = 0; i < dateSplit.length; i++){
deadlineDate = deadlineDate + dateSplit[i];
}
xmlhttp.open("GET","subTask.php?q="+ encodeURIComponent(tdes) + "&w=" + encodeURIComponent(tnam) +"&e=" +encodeURIComponent(shif) + "&y=" + encodeURIComponent(ttyp) + "&b=" + encodeURIComponent(deadlineDate) + "&u=" + encodeURIComponent(ooc),true);
I ran a web console and this is what is actually getting passed...
http://***************/****/********/subTask.php?taskName1=test+taskname+works&taskDescription1=test+des&shift1=All&ooc1=Open&taskType1=normal&datepicker=06%2F28%2F2013
I'm not sure what's going on in between the xmlhttp.open and the GET method in php. None of these variables are getting passed.
Why not use jQuery - very straightforward format (I prefer POST...):
$(document).ready(function() {
var tdes = $("#taskDescription1").val();
var tnam = $("#taskName1").val();
var shif = $("#shift1").val();
var ttyp = $("#taskType1").val();
var date = $("#datepicker").val();
var ooc = $("#ooc1").val();
var dateSplit = date.split('/');
var deadlineDate = "";
for( var i = 0; i < dateSplit.length; i++){
deadlineDate = deadlineDate + dateSplit[i];
}
$.ajax({
type: "POST",
url: "subTask.php",
data: "q="+ encodeURIComponent(tdes) + "&w=" + encodeURIComponent(tnam) +"&e=" +encodeURIComponent(shif) + "&y=" + encodeURIComponent(ttyp) + "&b=" + encodeURIComponent(deadlineDate) + "&u=" + encodeURIComponent(ooc),true),
success: function(whatigot) {
alert('Server-side response: ' + whatigot);
} //END success fn
}); //END $.ajax
}); //END document.ready()
Notice how easy the success callback function is to write... anything returned by subTask.php will be available within that function, as seen by the alert() example.
Just remember to include the jQuery library in the <head> tags:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
Also, add this line to the top of your subTask.php file, to see what is happening:
<?php
$q = $_POST["q"];
$w = $_POST["w"];
die("Value of Q is: " .$q. " and value of W is: " .$w);
The values of q= and w= will be returned to you in an alert box so that (at least) you can see what values they contained when received by subTask.php
Following script should help:
function ajaxObj( meth, url )
{
var x = false;
if(window.XMLHttpRequest)
x = new XMLHttpRequest();
else if (window.ActiveXObject)
x = new ActiveXObject("Microsoft.XMLHTTP");
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
var ajax = ajaxObj("POST", "subTask.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
console.log( ajax.responseText )
}
}
ajax.send("u="+tdes+"&e="+tnam+ ...... pass all the other 'n' data );

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

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

Very basic PHP array issue

I am creating a form where the user selects check boxes of "services" that they might be interested in, then the form gets emailed to me. The problem is weather a box is checked or not, all of the results are being filled in. How do I properly do this?
There are about 25, but here is just a few:
$services = array();
if($_POST['master_planning']) {$services[] = "Master planning";}
if($_POST['snow_plowing']) {$services[] = "Snow plowing";}
if($_POST['fine_gardening']) {$services[] = "Fine Gardening";}
if($_POST['deer_protection']) {$services[] = "Deer Protection";}
$interested = implode(", ", $services);
I know it is a very basic thing, but I can't seem to solve it on my own
HTML is like:
<li><label for="planting"><input type="checkbox" name="planting" id="planting" value="x" /> Planting</label></li>
Ok, I figured (I think) out why all the values are returning true, even if the checkboxes arent clicked, now how do I solve it....
I guess I should of mentioned that this is page 2 of the form (process.php), the actual form is index.php, and I am using an ajax script to pass values.
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function () {
var name = $('input[name=name]');
var phone = $('input[name=phone]');
var email = $('input[name=email]');
var master_plan = $('input[name=master_plan]');
var front_foundation = $('input[name=front_foundation]');
var backyard_plan = $('input[name=backyard_plan]');
var specialty_garden = $('input[name=specialty_garden]');
var lawn_cutting = $('input[name=lawn_cutting]');
var lawn_plant_health_care = $('input[name=lawn_plant_health_care]');
var organic_property_care = $('input[name=organic_property_care]');
var seasonal_clean_ups = $('input[name=seasonal_clean_ups]');
var pruning = $('input[name=pruning]');
var fine_gardening = $('input[name=fine_gardening]');
var deer_protection = $('input[name=deer_protection]');
var snow_plowing = $('input[name=snow_plowing]');
var planting = $('input[name=planting]');
var walk = $('input[name=walk]');
var terrace = $('input[name=terrace]');
var wall = $('input[name=wall]');
var outdoor_kitchen = $('input[name=outdoor_kitchen]');
var fireplace = $('input[name=fireplace]');
var driveway = $('input[name=driveway]');
var fencing = $('input[name=fencing]');
var pergola = $('input[name=pergola]');
var swimming_pool = $('input[name=swimming_pool]');
var irrigation = $('input[name=irrigation]');
var lighting = $('input[name=lighting]');
var grading_drainage = $('input[name=grading_drainage]');
var newsletter = $('input[name=newsletter]');
var comments = $('textarea[name=comments]');
if (name.val()=='') {
name.addClass('hightlight');
return false;
} else name.removeClass('hightlight');
if (email.val()=='') {
email.addClass('hightlight');
return false;
} else email.removeClass('hightlight');
var data =
'name=' + name.val() +
'&phone=' + phone.val() +
'&email=' + email.val() +
'&master_plan=' + master_plan.val()+
'&front_foundation=' + front_foundation.val()+
'&backyard_plan=' + backyard_plan.val()+
'&specialty_garden=' + specialty_garden.val()+
'&lawn_cutting=' + lawn_cutting.val()+
'&lawn_plant_health_care=' + lawn_plant_health_care.val()+
'&organic_property_care=' + organic_property_care.val()+
'&seasional_clean_ups=' + seasional_clean_ups.val()+
'&pruning=' + pruning.val()+
'&fine_gardening=' + fine_gardening.val()+
'&deer_protection=' + deer_protection.val()+
'&snow_plowing=' + snow_plowing.val()+
'&planting=' + planting.val()+
'&walk=' + walk.val()+
'&terrace=' + terrace.val()+
'&wall=' + wall.val()+
'&outdoor_kitchen=' + outdoor_kitchen.val()+
'&fireplace=' + fireplace.val()+
'&driveway=' + driveway.val()+
'&fencing=' + fencing.val()+
'&pergola=' + pergola.val()+
'&swimming_pool=' + swimming_pool.val()+
'&irrigation=' + irrigation.val()+
'&lighting=' + lighting.val()+
'&grading_drainage=' + grading_drainage.val()+
'&newsletter=' + newsletter.val() +
'&comments=' + encodeURIComponent(comments.val());
$('.text').attr('disabled','true');
$('.loading').show();
$.ajax({
url: "process.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
if (html==1) {
$('.form').fadeOut('slow');
$('.done').fadeIn('slow');
} else alert('Sorry, unexpected error. Please try again later.');
}
});
return false;
});
});
</script>
Could this be why every result is displaying?
The check you have is incorrect. Lets assume you have this HTML code for the checkbox inside your form:
<input type="checkbox" name="master_planning" value="yes" />
Then on your PHP you want do the check like this:
if(isset($_POST['master_planning']) && $_POST['master_planning'] == 'yes'){
array_push($services, "Master planning"];
}
The function array_push adds the given element or elements at the end of the array, so that would be an easy way to "dynamically" populates an array.

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

Categories