MethodNotAllowedHttpException [AJAX]! - php

I have some problems with routes.
Code: MethodNotAllowedHttpException in RouteCollection.php line 219.
I use ajax and laravel 5.1. I try use google, but I do not understand, I try method "path", and in ajax change "type" to "method". I try GET, but no work.
My ajax:
$.ajax({
type: 'POST',
url: '/placeBet',
dataType: 'json',
data: {
ammount: ammount,
color: color
},
headers: {
'X-CSRF-TOKEN': $('#_token').val()
},
success: function (data) {
if (data['color'] == 'red') {
var currentPlaced = parseInt($('.user_red').html());
currentPlaced = currentPlaced + parseInt(data['ammount']);
$('.user_red').html(currentPlaced);
}
if (data['placedMuch']) {
alertify.error('Max 4 bets in round!');
}
if (data['color'] == 'purple') {
var currentPlaced = parseInt($('.user_black').html());
currentPlaced = currentPlaced + parseInt(data['ammount']);
$('.user_black').html(currentPlaced);
}
if (data['color'] == 'gold') {
var currentPlaced = parseInt($('.user_gold').html());
currentPlaced = currentPlaced + parseInt(data['ammount']);
$('.user_gold').html(currentPlaced);
}
if (data['color'] == 'green') {
var currentPlaced = parseInt($('.user_green').html());
currentPlaced = currentPlaced + parseInt(data['ammount']);
$('.user_green').html(currentPlaced);
}
if (data['baaad'] == true) {
alertify.error('Niu niu!');
return;
}
if (data['improvements'] == true) {
alertify.error('We are working on improvements.');
return;
}
if (data['toLow'] == true) {
alertify.error('Minimum bet is 200 diamonds!');
return;
}
if (data['can_bet'] == false) {
alertify.error('You have withdraw request pending, you cannot bet!');
return;
}
if (data['placed'] != false && data['coins'] != false) {
var coins = data['coins'];
var htmlo = '<div class="chat_message"><div class="top"><div class="right_info">Info Bot</div></div><div class="message">You spent ' + ammount + ' diamonds on ' + data['color'] + '.</div></div>';
$('#chatmessages').append(htmlo);
$('.recents_box').mCustomScrollbar("scrollTo", 'bottom');
$({countNum: $('#currentBallance').html()}).animate({countNum: coins}, {
duration: 1000,
easing: 'linear',
step: function () {
$('#currentBallance').html(parseFloat(this.countNum).toFixed(0))
},
complete: function () {
$('#currentBallance').html(parseFloat(this.countNum).toFixed(0))
}
});
} else if (data['placed'] != false && data['coins'] == '0') {
var coins = data['coins'];
var htmlo = '<div class="chat_message"><div class="top"><div class="right_info">Info Bot</div></div><div class="message">You spent all your diamonds on ' + data['color'] + '.</div></div>';
$('#chatmessages').append(htmlo);
('.recents_box').mCustomScrollbar("scrollTo", 'bottom');
$({countNum: $('#currentBallance').html()}).animate({countNum: coins}, {
duration: 1000,
easing: 'linear',
step: function () {
$('#currentBallance').html(parseFloat(this.countNum).toFixed(0))
},
complete: function () {
$('#currentBallance').html(parseFloat(this.countNum).toFixed(0))
}
});
// swal('Yea', 'You placed a bet to ' + color + '. Your current coins are : ' + coins + '!', 'success');
// $('#betammount').val(0);
} else {
if (data['logged'] == false) {
alertify.error('You need to be log in to use this option!');
} else if (data['coins'] == false) {
alertify.error('You are not that rich!');
// $('#betammount').val(0);
} else if (data['coins'] == '0') {
alertify.error('You are empty!');
//$('#betammount').val(0);
}
}
}
});
My routes:
Route::post('/placeBet', ['as' => 'placeBet', 'uses' => 'RouletteController#placeBet']);
My RoulleteController:
public function placeBet(Request $request)
{
$info = [];
if (Auth::check()) {
$lastID = DB::select("SELECT * FROM roulette_history ORDER BY id DESC LIMIT 1");
$roundID = $lastID[0]->id;
$steamID = Auth::user()->steamId64;
$ammount = $request->All()['ammount'];
$getCountPlaced = \App\placedBets::where('gameID', $roundID)->where('userID64', Auth::user()->steamId64)->count();
if($getCountPlaced > 3) {
$info['placedMuch'] = true;
$info = json_encode($info);
return $info;
}
if($ammount < 1 || !is_numeric($ammount)) {
$info['baaad'] = true;
$info = json_encode($info);
return $info;
}
if ($ammount < 200) {
$info['toLow'] = true;
$info = json_encode($info);
return $info;
}
if(Auth::user()->global_banned > 0) {
$info['baaad'] = true;
$info = json_encode($info);
return $info;
}
$color = $request->All()['color'];
if($color == 'black') {
$color = 'purple';
}
$user_info = \App\User::where('steamId64', Auth::user()->steamId64)->first();
$active_ofer = \App\ofers::where('userID', Auth::user()->steamId64)->count();
$info['active_ofer'] = $active_ofer;
$user_coins = $user_info->coins;
if ($user_coins < $ammount) {
$info['coins'] = false;
$info['placed'] = false;
} else {
$user_coins = $user_coins - $ammount;
$siteProfit = \App\profit::first();
$siteProfitTotal = $siteProfit->siteProfit;
$siteProfitTotal = intval($siteProfitTotal) + intval($ammount);
$updateProfit = DB::update("UPDATE siteProfit SET siteProfit='$siteProfitTotal'");
$user_update = \App\User::where('steamId64', Auth::user()->steamId64)->update(['coins' => $user_coins]);
$info['coins'] = $user_coins;
$active_bet = DB::select("SELECT * FROM roulette_history ORDER BY id DESC LIMIT 1");
$game_id = $active_bet[0]->id;
$placed = DB::insert('insert into placed_bets (color, userID64, ammount, gameID, avatar,url,nick,isStreamer,streamLink) values (?, ?, ?, ?,?,?,?,?,?)', [$color, $steamID, $ammount, $game_id, $user_info->avatar, $user_info->url, $user_info->nick,$user_info->isStreamer,$user_info->steamLink]);
$info['placed'] = true;
$info['ammount'] = $ammount;
$info['color'] = $color;
$info['count'] = $getCountPlaced;
}
$info['logged'] = true;
} else {
$info['coins'] = 0;
$info['logged'] = false;
$info['placed'] = false;
}
$info = json_encode($info);
return $info;
}
If u need source, i can get for us!

In your ajax call, change
$.ajax({
type: 'POST',
to
$.ajax({
method: 'POST',

Related

Can you help me to correct this "net::ERR_TOO_MANY_REDIRECTS" Chrome error?

I have a problem with ajax POST when my website is integrated in iframe. Only some users have the error in Chrome. I put a screenshot of the console error (send by user).
Screenshot
The concerned javascript is in /js/open.min.js :
/* (c) 2019 Lockee.fr */
function openLock(){
if($("#inputcode").val() != ""){
$.ajax({
type: 'POST',
async: false,
cache: false,
url: homeURL + 'ajax-open.php',
dataType: "json",
data: {id : $("#inputid").val(), code : $("#inputcode").val(), top : $("#inputtop").val()},
timeout: 3000,
success: function(data){
console.log(data);
if(data.open == 0){
$("#wrongcode").fadeIn(0).delay(1500).fadeOut(0);
} else {
if(data.redirect == 1){
if(data.top == 1){
top.location.href = data.content;
} else {
location.href = data.content;
}
} else {
$("#contentlock").html(data.content);
$("#isclose").hide();
$("#isopen").show();
$("#report").show();
}
}
}
});
}
}
function closeLock(){
lock.clearCode();
$("#contentlock").html("");
$("#isopen").hide();
$("#report").hide();
$("#isclose").show();
}
The PHP code :
<?php
include("functions.php");
if((!empty($_POST["id"]))&&(!empty($_POST["code"]))){
$id = addslashes($_POST['id']);
$code = htmlspecialchars($_POST['code']);
$infos = lockInfo($id);
if(($infos['action'] == "L")&&($_POST['top'] == 1)){
$top = 1;
$redirect = 1;
$content = $infos["content"];
} else if($infos['action'] == "L"){
$redirect = 1;
$top = 0;
$content = $infos["content"];
} else {
$redirect = 0;
$top = 0;
$content = displayContent($infos["action"], $infos["content"], $infos["linked"], false);
}
$open = 1;
if($infos['code'] == $code){
$open = 1;
} else {
$open = 0;
}
} else {
$open = 0;
}
if($open == 0){
$content = "";
}
$file = ["open" => $open, "content" => $content, "redirect" => $redirect, "top" => $top];
header('Content-Type: application/json');
echo json_encode($file);
?>
This is an example which is not working for some users :
The code to open integrated lock is "123"
Thank's for your help !

I am getting array index in query string when use remote in jquery.How can I get its value in laravel controller?

I have send a get request
jQuery.validator.addClassRules({
termName:{
required: true,
maxlength:50,
unique:true,
/*termValidate : true,*/
remote: {
url: "/term/unique",
type: "get",
data: {
memberId: function () {
return $("input[name='member_id']").val();
},
},
dataFilter: function (data) {
var json = JSON.parse(data);
if (json.id!=0) {
return "\"" + "{{Lang::get('messages.membership_name_already_taken')}}" + "\"";
} else {
return 'true';
}
}
}
}
in controller
public function checkLimit()
{
$membership = Tenure::all()->where('name', Input::get('termName'))->first();
if (Input::get('memberId')!=" ") {
$id = Input::get('memberId');
} else {
$id = 0;
}
if($membership == null && $id == 0){
$membership = ['id' => '0'];
} else {
if ($membership->id == $id) {
$membership = ['id' => '0'];
}
}
return Response::json($membership);
}
i have used Input::get('termName') to get termName.but when i checked my querystring its like
http://localhost:8088/term/unique?term_name[0]=vfvfvfvffvff&memberId=
how can i get termname in controller?
Use this method
public function checkLimit(Request $request)
{
$membership = Tenure::all()->where('name', $request->term_name->first());
if ($request->memberId!="") {
$id = $request->memberId;
} else {
$id = 0;
}
if($membership == null && $id == 0){
$membership = ['id' => '0'];
} else {
if ($membership->id == $id) {
$membership = ['id' => '0'];
}
}
return Response::json($membership);
}

Ajax response not displaying anything in view file (Yii)

I have a file ( _gen.php) that is in my view that sends selected data to the controller file for verification:
$('#validate').on('click',function(){
var data = []; // data container
// collect all the checked checkboxes and their associated attributes
$("table#subsection_table input[type='checkbox']:checked").each(function(){
data.push({
section : $(this).data('sectionid'),
subsection : $(this).val(),
year : $(this).data('year')
})
});
// JSON it so that it can be passed via Ajax call to a php page
var data = JSON.stringify(data);
$.ajax({
url : "<?php echo Yii::app()->createAbsoluteUrl("scheduler/ScheduleValidation"); ?>",
type: "POST",
data : "myData=" + data,
success : function(data)
{
$("#ajax-results").html(data);
$("#ajax-results").dialog({ width: 500, height: 500})
},
error: function()
{
alert("there was an error")
}
})
console.log(JSON.stringify(data));
$('#dialog').html(data).dialog({ width: 500, heigh: 500});
});
Now #ajax-result is the id of one of my div tag after my button ( last thing displayed on the page).
As for the controller function, I do know it handles the data fine and the sql call correctly ( I made sure of it). However when I call renderPartial it will call my _ajax.php file correctly but it will only displayed it in an alert box, not to the #ajax-result tag. The controller function:
public function actionScheduleValidation()
{
print_r("in ajax");
$post_data = $_POST['myData'];
$decodedData = json_decode($post_data, true);
//$course = [[[]]];
$course=[];
$counter = 0;
//Save the years associated to sections chosen
foreach ($decodedData as $key) {
$tutOrLab = null;
$lec = null;
$currentYear = null;
foreach ($key as $id => $number) {
if ($id == 'year') {
$currentYear = $number;
} elseif ($id == 'subsection') {
$tutOrLab = Yii::app()->db->createCommand()
->select('courseID,kind,days,start_time,end_time,semester')
->from($id)
->where('id=' . $number)
->queryRow();
} else
$lec = Yii::app()->db->createCommand()
->select('courseID,kind,days,start_time,end_time,semester')
->from($id)
->where('id=' . $number)
->queryRow();
}
print_r(gettype($lec['start_time']));
$lecture = new Lecture($lec['courseID'],$lec['kind'],$lec['days'],$lec['start_time'],$lec['end_time'],$lec['semester'],$currentYear);
print_r(gettype($lecture->getStartTime()));
// WILL ACTUALLY DISPLAY SOMETHING
$tutorial = new TutorialAndLab($tutOrLab['courseID'],$tutOrLab['kind'],$tutOrLab['days'],$tutOrLab['start_time'],$tutOrLab['end_time'],$tutOrLab['semester'],$currentYear);
$course[$counter] = new CourseObj($lecture,$tutorial);
$counter++;
}
$courseYear1Fall = [];
$courseYear1Winter = [];
$courseYear2Fall = [];
$courseYear2Winter = [];
$courseYear3Fall = [];
$courseYear3Winter = [];
$courseYear4Fall = [];
$courseYear4Winter = [];
if($course != null) {
for ($i = 0; $i < count($course); $i++) {
if ($course[$i]->getLecture()->getYear() == '1') {
if ($course[$i]->getLecture()->getSemester() == 'F') {
array_push($courseYear1Fall, $course[$i]);
} elseif ($course[$i]->getLecture()->getSemester() == 'W') {
array_push($courseYear1Winter, $course[$i]);
}
} elseif ($course[$i]->getLecture()->getYear() == '2') {
if ($course[$i]->getLecture()->getSemester() == 'F') {
array_push($courseYear2Fall, $course[$i]);
} elseif ($course[$i]->getLecture()->getSemester() == 'W')
array_push($courseYear2Winter, $course[$i]);
} elseif ($course[$i]->getLecture()->getYear() == '3') {
if ($course[$i]->getLecture()->getSemester() == 'F') {
array_push($courseYear3Fall, $course[$i]);
} elseif ($course[$i]->getLecture()->getSemester() == 'W') {
array_push($courseYear3Winter, $course[$i]);
}
} elseif ($course[$i]->getLecture()->getYear() == '4') {
if ($course[$i]->getLecture()->getSemester() == 'F') {
array_push($courseYear4Fall, $course[$i]);
} elseif ($course[$i]->getLecture()->getSemester() == 'W') {
array_push($courseYear4Winter, $course[$i]);
}
}
}
$counter2=0;
$errorArr = [];
if($courseYear1Fall != null){
$fallErr = verification($courseYear1Fall);
$errorArr[$counter2] = $fallErr;
$counter2++;
}
elseif($courseYear1Winter != null) {
$winterErr = verification($courseYear1Winter);
$errorArr[$counter2] = $winterErr;
$counter2++;
}
if($courseYear2Fall != null) {
$fallErr = verification($courseYear2Fall);
$errorArr[$counter2] = $fallErr;
$counter2++;
}
if($courseYear2Winter != null) {
$winterErr = verification($courseYear3Fall);
$errorArr[$counter2] = $winterErr;
$counter2++;
}
if($courseYear3Winter != null) {
$fallErr = verification($courseYear3Fall);
$errorArr[$counter2] = $fallErr;
$counter2++;
}
if($courseYear3Fall != null) {
$winterErr = verification($courseYear3Winter);
$errorArr[$counter2] = $winterErr;
$counter2++;
}
if($courseYear4Fall != null) {
$fallErr = verification($courseYear4Fall);
$errorArr[$counter2] = $fallErr;
$counter2++;
}
if($courseYear4Winter != null) {
$winterErr = verification($courseYear4Winter);
$errorArr[$counter2] = $winterErr;
}
$this->renderPartial('_ajax', array(
'data' => $errorArr,
)
);
}
Any idea on how to append it to my original (_gen.php) html code?
Your ajax call is missing semi-colon.
And probably as a good practise you should not be naming both request and response variable "data".

Caluclation of a Vat from a value of a javascript function

Hello everyone I need help
then I have a form that through a javascript function I calculate the total of a product and then mail
Now I want to calculate the VAT on that value , but it does not work and I understand why , perhaps , the value that gives me is a value not a number for example he gives me 100 Euros .. not 100 and then I wanted to know , if is a system to extract the number to that value and then let him calculate the VAT
thank you
I guess this is what you need..
Try explode(). This function returns you an array of strings.
$valueWithCurrency = "100 Euros";
$extractedValue = explode(' ', $valueWithCurrency); //space as a delimiter in first argument
echo $extractedValue[0]; //Here you go. "100"
echo $extractedValue[1]; //this contains "Euros"
sorry .
This is the plug-in code that I purchased
(function($) {
$.fn.SimplePriceCalc= function (options) {
// Default options for text
var settings = $.extend({
totallabel: "Total:",
detailslabel: "Details:",
currency:"$"
}, options );
// Initialize Variables
var total=0;
var child=this.find('*');
var formdropdowns=this.find('select');
this.addClass("simple-price-calc");
InitialUpdate();
// Change select data cost on each change to current selected value
formdropdowns.change( function() {
if($(this).attr('multiple')) {
var selectedOptions = $(this).find(':selected');
var selectedOptionstotal=0;
if (selectedOptions != '')
{
selectedOptions.each( function() {
selectedOptionstotal += $(this).data('price');
});
}
$(this).attr('data-total',selectedOptionstotal);
}
else{
var selectedOption = $(this).find(':selected');
if($(this).data('mult') >= 0)
$("#simple-price-total label").attr('data-mult',selectedOption.val());
else
$(this).attr('data-total',selectedOption.data('price')) ;
}
UpdateTotal();
});
//Update total when user inputs or changes data from input box
$(".simple-price-calc input[type=text]").change( function() {
if($(this).attr('data-price') || $(this).attr('data-mult')) {
var userinput= $(this).val();
if($.isNumeric(userinput)) { var usernumber = parseFloat(userinput);} else if(userinput != '') { alert('Please enter a valid number'); var usernumber = 1; } else { usernumber = 1; }
var multiple=parseFloat($(this).data('mult')) || 0;
var pricecost=parseFloat($(this).data('price')) || 0;
var percentage=$(this).data('prcnt') || 1;
if($.isNumeric(pricecost) && pricecost !=0) {
var updpricecost=pricecost * usernumber;
$(this).attr('data-total', updpricecost);
}
if(multiple && multiple !=0) {
$("#simple-price-total label").attr('data-mult',usernumber);
}
}
UpdateTotal();
});
$(".simple-price-calc input[type=checkbox]").change( function() {
if($(this).is(':checked')) {
var checkboxval= $(this).val();
if($.isNumeric(checkboxval)) {
$(this).attr('data-total', checkboxval);
}
else {
$(this).attr('data-total', 0);
}
}
else {
$(this).attr('data-total', 0);
}
UpdateTotal();
});
$(".simple-price-calc input[type=radio]").change( function() {
$(".simple-price-calc input[type=radio]").each( function() {
if($(this).is(':checked')) {
var radioval= $(this).val();
if($.isNumeric(radioval)) {
$(this).attr('data-total', radioval);
}
else {
$(this).attr('data-total', 0);
}
}
else {
$(this).attr('data-total', 0);
}
});
UpdateTotal();
});
//Initialize all fields if data is there
function InitialUpdate() {
formdropdowns.each( function() {
if($(this).attr('multiple')) {
var selectedOptions = $(this).find(':selected');
var selectedOptionstotal=0;
if (selectedOptions != '')
{
selectedOptions.each( function() {
selectedOptionstotal += $(this).data('price');
});
}
$(this).attr('data-total',selectedOptionstotal);
}
else{
var selectedOption = $(this).find(':selected');
$(this).attr('data-total',selectedOption.data('price')) ;
}
});
//Update total when user inputs or changes data from input box
$(".simple-price-calc input[type=text]").each( function() {
if($(this).attr('data-price') || $(this).attr('data-mult')) {
var userinput= $(this).val();
if($.isNumeric(userinput)) { var usernumber = parseFloat(userinput);} else if(userinput != '') { alert('Please enter a valid number'); var usernumber = 1;} else { usernumber = 1; }
var multiple=parseFloat($(this).data('mult')) || 0;
var pricecost=parseFloat($(this).data('price')) || 0;
var percentage=$(this).data('prcnt') || 1;
if($.isNumeric(pricecost) && pricecost !=0) {
var updpricecost=pricecost * usernumber;
$(this).attr('data-total', updpricecost);
}
if(multiple && multiple !=0) {
$("#simple-price-total label").attr('data-mult',usernumber);
}
}
});
$(".simple-price-calc input[type=checkbox]").each( function() {
if($(this).is(':checked')) {
var checkboxval= $(this).val();
if($.isNumeric(checkboxval)) {
$(this).attr('data-total', checkboxval);
}
else {
$(this).attr('data-total', 0);
}
}
else {
$(this).attr('data-total', 0);
}
});
$(".simple-price-calc input[type=radio]").each( function() {
if($(this).is(':checked')) {
var radioval= $(this).val();
if($.isNumeric(radioval)) {
$(this).attr('data-total', radioval);
}
else {
$(this).attr('data-total', 0);
}
}
else {
$(this).attr('data-total', 0);
}
});
UpdateTotal();
}
//Change value of total field by adding all data totals in form
function UpdateTotal() {
total=0;
totalmult=$(".simple-price-calc #simple-price-total label").attr("data-mult");
//For each input with data-merge attr, take merge ids value and multiply by current data-price
$("input[data-merge]").each(function(){
var ids=$(this).data('merge');
var ids=ids.split(',');
var arraytotals=1;
$.each(ids, function(key,value) {
var inputid =$("#"+value);
if( (inputid.attr('type') == 'checkbox' || inputid.attr('type') == 'radio') && inputid.is(':checked') )
arraytotals*=$("#"+value).val();
else if (inputid.attr('type') == 'text')
arraytotals*=$("#"+value).val();
else if (inputid.prop('nodeName') == "SELECT")
arraytotals*=$("#"+value).attr('data-total');
});
var idtotal=arraytotals;
if($.isNumeric(idtotal)) {
var pricecost=parseFloat($(this).data('price')) || 0;
$(this).val(idtotal);
var updpricecost= pricecost * parseFloat($(this).val());
$(this).attr('data-total',updpricecost);
}
});
child.each(function () {
itemcost= $(this).attr("data-total") || 0;
total += parseFloat(itemcost);
});
if(totalmult) { total = total * parseFloat(totalmult); }
$(".simple-price-calc #simple-price-total label").html(settings.currency+$.number(total,2));
setTimeout(function() {
UpdateDescriptions();
}, 100);
}
//Update Field Labels and Pricing
function UpdateDescriptions() {
var selectedformvalues= [];
var currtag='';
$(".simple-price-calc").find('*').each( function () {
currtag=$(this).prop('tagName');
if(currtag == "SELECT") {
if($(this).attr('multiple')) {
var selectedOptions = $(this).find(':selected');
if (selectedOptions != '')
{
selectedOptions.each( function() {
var optionlabel= $(this).data('label') || '';
var optionprice = $(this).data('price');
if(optionlabel != '') {
selectedformvalues.push(optionlabel + ": " + settings.currency + optionprice);
}
});
}
}
else{
var selectedOption = $(this).find(':selected');
if (selectedOption != '')
{
var optionlabel= selectedOption.data('label') || '';
var optionprice = selectedOption.data('price');
if(optionlabel != '') {
selectedformvalues.push(optionlabel +": " + settings.currency + optionprice);
}
}
}
} // End of Form dropdown
if(currtag == "INPUT" && $(this).attr('type') == "text")
{
if($(this).attr('data-price') || $(this).attr('data-mult')) {
var userinput= $(this).val();
if($.isNumeric(userinput)) { var usernumber = parseFloat(userinput);} else { var usernumber = 1; }
var pricecost=parseFloat($(this).data('price')) || 0;
var currlabel= $(this).attr('data-label') || '';
var currinput= userinput;
if (currlabel != '' && currinput !='') {
if($.isNumeric(pricecost) && pricecost !=0) {
var updpricecost=pricecost * usernumber;
selectedformvalues.push(currlabel + ": " + settings.currency + updpricecost);
}
else{
selectedformvalues.push(currlabel + ": " + currinput);
}
}
}
} // End of input type text
if($("input[type=checkbox]") || $("input[type=radio]") )
{
if($(this).is(':checked')) {
var checkboxval= $(this).val();
if($.isNumeric(checkboxval)) {
var currlabel= $(this).attr('data-label') || '';
var currprice= checkboxval;
if (currlabel != '') { selectedformvalues.push(currlabel + ": " + settings.currency + currprice); }
}
}
} // End of input type checkbox or radio
});
$("#simple-price-details").html("");
if (selectedformvalues != '') {
$("#simple-price-details").append("<h3>"+ settings.detailslabel +"</h3>");
$.each(selectedformvalues, function(key,value) {
$("#simple-price-details").append(value + "<br />");
});
}
}// End of UpdateDescriptions()
this.append('<div id="sidebar"><div id="simple-price-total"><h3 style="margin:0;">' + settings.totallabel + ' </h3><label id="simple-price-total-num"> ' + settings.currency + $.number(total,2) + ' </label></div> <div id="simple-price-details"></div></div>');
return this;
}; // End of plugin
}(jQuery));
This is the call in html
// Attaches Simple Price Calc to form
$("#quoteform").SimplePriceCalc();
// Adds Total price and details to hidden inputs that can be used to e-mail data
$("form :input, form textarea, form select").change( function() {
setTimeout( function() {
var total=$('#simple-price-total-num').html();
var details=$('#simple-price-details').html();
$('#hiddentotal').val(total);
$('#hiddendetails').val(details);
}, 150);
});
in php use this to have the value
echo $_POST['hidden_total']

FAQ displaying style in JavaScript

I have implemented the following JavaScript in my FAQ page:
var Spry;
if (!Spry) Spry = {};
if (!Spry.Widget) Spry.Widget = {};
Spry.Widget.CollapsiblePanel = function(element, opts)
{
this.init(element);
Spry.Widget.CollapsiblePanel.setOptions(this, opts);
this.attachBehaviors();
};
Spry.Widget.CollapsiblePanel.prototype.init = function(element)
{
this.element = this.getElement(element);
this.focusElement = null;
this.hoverClass = "CollapsiblePanelTabHover";
this.openClass = "CollapsiblePanelOpen";
this.closedClass = "CollapsiblePanelClosed";
this.focusedClass = "CollapsiblePanelFocused";
this.enableAnimation = true;
this.enableKeyboardNavigation = true;
this.animator = null;
this.hasFocus = false;
this.contentIsOpen = true;
};
Spry.Widget.CollapsiblePanel.prototype.getElement = function(ele)
{
if (ele && typeof ele == "string")
return document.getElementById(ele);
return ele;
};
Spry.Widget.CollapsiblePanel.prototype.addClassName = function(ele, className)
{
if (!ele || !className || (ele.className && ele.className.search(new RegExp("\\b" + className + "\\b")) != -1))
return;
ele.className += (ele.className ? " " : "") + className;
};
Spry.Widget.CollapsiblePanel.prototype.removeClassName = function(ele, className)
{
if (!ele || !className || (ele.className && ele.className.search(new RegExp("\\b" + className + "\\b")) == -1))
return;
ele.className = ele.className.replace(new RegExp("\\s*\\b" + className + "\\b", "g"), "");
};
Spry.Widget.CollapsiblePanel.prototype.hasClassName = function(ele, className)
{
if (!ele || !className || !ele.className || ele.className.search(new RegExp("\\b" + className + "\\b")) == -1)
return false;
return true;
};
Spry.Widget.CollapsiblePanel.prototype.setDisplay = function(ele, display)
{
if( ele )
ele.style.display = display;
};
Spry.Widget.CollapsiblePanel.setOptions = function(obj, optionsObj, ignoreUndefinedProps)
{
if (!optionsObj)
return;
for (var optionName in optionsObj)
{
if (ignoreUndefinedProps && optionsObj[optionName] == undefined)
continue;
obj[optionName] = optionsObj[optionName];
}
};
Spry.Widget.CollapsiblePanel.prototype.onTabMouseOver = function()
{
this.addClassName(this.getTab(), this.hoverClass);
};
Spry.Widget.CollapsiblePanel.prototype.onTabMouseOut = function()
{
this.removeClassName(this.getTab(), this.hoverClass);
};
Spry.Widget.CollapsiblePanel.prototype.open = function()
{
this.contentIsOpen = true;
if (this.enableAnimation)
{
if (this.animator)
this.animator.stop();
this.animator = new Spry.Widget.CollapsiblePanel.PanelAnimator(this, true);
this.animator.start();
}
else
this.setDisplay(this.getContent(), "block");
this.removeClassName(this.element, this.closedClass);
this.addClassName(this.element, this.openClass);
};
Spry.Widget.CollapsiblePanel.prototype.close = function()
{
this.contentIsOpen = false;
if (this.enableAnimation)
{
if (this.animator)
this.animator.stop();
this.animator = new Spry.Widget.CollapsiblePanel.PanelAnimator(this, false);
this.animator.start();
}
else
this.setDisplay(this.getContent(), "none");
this.removeClassName(this.element, this.openClass);
this.addClassName(this.element, this.closedClass);
};
Spry.Widget.CollapsiblePanel.prototype.onTabClick = function()
{
if (this.isOpen())
this.close();
else
this.open();
this.focus();
};
Spry.Widget.CollapsiblePanel.prototype.onFocus = function(e)
{
this.hasFocus = true;
this.addClassName(this.element, this.focusedClass);
};
Spry.Widget.CollapsiblePanel.prototype.onBlur = function(e)
{
this.hasFocus = false;
this.removeClassName(this.element, this.focusedClass);
};
Spry.Widget.CollapsiblePanel.ENTER_KEY = 13;
Spry.Widget.CollapsiblePanel.SPACE_KEY = 32;
Spry.Widget.CollapsiblePanel.prototype.onKeyDown = function(e)
{
var key = e.keyCode;
if (!this.hasFocus || (key != Spry.Widget.CollapsiblePanel.ENTER_KEY && key != Spry.Widget.CollapsiblePanel.SPACE_KEY))
return true;
if (this.isOpen())
this.close();
else
this.open();
if (e.stopPropagation)
e.stopPropagation();
if (e.preventDefault)
e.preventDefault();
return false;
};
Spry.Widget.CollapsiblePanel.prototype.attachPanelHandlers = function()
{
var tab = this.getTab();
if (!tab)
return;
var self = this;
Spry.Widget.CollapsiblePanel.addEventListener(tab, "click", function(e) { return self.onTabClick(); }, false);
Spry.Widget.CollapsiblePanel.addEventListener(tab, "mouseover", function(e) { return self.onTabMouseOver(); }, false);
Spry.Widget.CollapsiblePanel.addEventListener(tab, "mouseout", function(e) { return self.onTabMouseOut(); }, false);
if (this.enableKeyboardNavigation)
{
// XXX: IE doesn't allow the setting of tabindex dynamically. This means we can't
// rely on adding the tabindex attribute if it is missing to enable keyboard navigation
// by default.
// Find the first element within the tab container that has a tabindex or the first
// anchor tag.
var tabIndexEle = null;
var tabAnchorEle = null;
this.preorderTraversal(tab, function(node) {
if (node.nodeType == 1 /* NODE.ELEMENT_NODE */)
{
var tabIndexAttr = tab.attributes.getNamedItem("tabindex");
if (tabIndexAttr)
{
tabIndexEle = node;
return true;
}
if (!tabAnchorEle && node.nodeName.toLowerCase() == "a")
tabAnchorEle = node;
}
return false;
});
if (tabIndexEle)
this.focusElement = tabIndexEle;
else if (tabAnchorEle)
this.focusElement = tabAnchorEle;
if (this.focusElement)
{
Spry.Widget.CollapsiblePanel.addEventListener(this.focusElement, "focus", function(e) { return self.onFocus(e); }, false);
Spry.Widget.CollapsiblePanel.addEventListener(this.focusElement, "blur", function(e) { return self.onBlur(e); }, false);
Spry.Widget.CollapsiblePanel.addEventListener(this.focusElement, "keydown", function(e) { return self.onKeyDown(e); }, false);
}
}
};
Spry.Widget.CollapsiblePanel.addEventListener = function(element, eventType, handler, capture)
{
try
{
if (element.addEventListener)
element.addEventListener(eventType, handler, capture);
else if (element.attachEvent)
element.attachEvent("on" + eventType, handler);
}
catch (e) {}
};
Spry.Widget.CollapsiblePanel.prototype.preorderTraversal = function(root, func)
{
var stopTraversal = false;
if (root)
{
stopTraversal = func(root);
if (root.hasChildNodes())
{
var child = root.firstChild;
while (!stopTraversal && child)
{
stopTraversal = this.preorderTraversal(child, func);
try { child = child.nextSibling; } catch (e) { child = null; }
}
}
}
return stopTraversal;
};
Spry.Widget.CollapsiblePanel.prototype.attachBehaviors = function()
{
var panel = this.element;
var tab = this.getTab();
var content = this.getContent();
if (this.contentIsOpen || this.hasClassName(panel, this.openClass))
{
this.removeClassName(panel, this.closedClass);
this.setDisplay(content, "block");
this.contentIsOpen = true;
}
else
{
this.removeClassName(panel, this.openClass);
this.addClassName(panel, this.closedClass);
this.setDisplay(content, "none");
this.contentIsOpen = false;
}
this.attachPanelHandlers();
};
Spry.Widget.CollapsiblePanel.prototype.getTab = function()
{
return this.getElementChildren(this.element)[0];
};
Spry.Widget.CollapsiblePanel.prototype.getContent = function()
{
return this.getElementChildren(this.element)[1];
};
Spry.Widget.CollapsiblePanel.prototype.isOpen = function()
{
return this.contentIsOpen;
};
Spry.Widget.CollapsiblePanel.prototype.getElementChildren = function(element)
{
var children = [];
var child = element.firstChild;
while (child)
{
if (child.nodeType == 1 /* Node.ELEMENT_NODE */)
children.push(child);
child = child.nextSibling;
}
return children;
};
Spry.Widget.CollapsiblePanel.prototype.focus = function()
{
if (this.focusElement && this.focusElement.focus)
this.focusElement.focus();
};
/////////////////////////////////////////////////////
Spry.Widget.CollapsiblePanel.PanelAnimator = function(panel, doOpen, opts)
{
this.timer = null;
this.interval = 0;
this.stepCount = 0;
this.fps = 0;
this.steps = 10;
this.duration = 500;
this.onComplete = null;
this.panel = panel;
this.content = panel.getContent();
this.panelData = [];
this.doOpen = doOpen;
Spry.Widget.CollapsiblePanel.setOptions(this, opts);
// If caller specified speed in terms of frames per second,
// convert them into steps.
if (this.fps > 0)
{
this.interval = Math.floor(1000 / this.fps);
this.steps = parseInt((this.duration + (this.interval - 1)) / this.interval);
}
else if (this.steps > 0)
this.interval = this.duration / this.steps;
var c = this.content;
var curHeight = c.offsetHeight ? c.offsetHeight : 0;
if (doOpen && c.style.display == "none")
this.fromHeight = 0;
else
this.fromHeight = curHeight;
if (!doOpen)
this.toHeight = 0;
else
{
if (c.style.display == "none")
{
// The content area is not displayed so in order to calculate the extent
// of the content inside it, we have to set its display to block.
c.style.visibility = "hidden";
c.style.display = "block";
}
// Unfortunately in Mozilla/Firefox, fetching the offsetHeight seems to cause
// the browser to synchronously re-layout and re-display content on the page,
// so we see a brief flash of content that is *after* the panel being positioned
// where it should when the panel is fully expanded. To get around this, we
// temporarily position the content area of the panel absolutely off-screen.
// This has the effect of taking the content out-of-flow, so nothing shifts around.
// var oldPos = c.style.position;
// var oldLeft = c.style.left;
// c.style.position = "absolute";
// c.style.left = "-2000em";
// Clear the height property so we can calculate
// the full height of the content we are going to show.
c.style.height = "";
this.toHeight = c.offsetHeight;
// Now restore the position and offset to what it was!
// c.style.position = oldPos;
// c.style.left = oldLeft;
}
this.increment = (this.toHeight - this.fromHeight) / this.steps;
this.overflow = c.style.overflow;
c.style.height = this.fromHeight + "px";
c.style.visibility = "visible";
c.style.overflow = "hidden";
c.style.display = "block";
};
Spry.Widget.CollapsiblePanel.PanelAnimator.prototype.start = function()
{
var self = this;
this.timer = setTimeout(function() { self.stepAnimation(); }, this.interval);
};
Spry.Widget.CollapsiblePanel.PanelAnimator.prototype.stop = function()
{
if (this.timer)
{
clearTimeout(this.timer);
// If we're killing the timer, restore the overflow
// properties on the panels we were animating!
if (this.stepCount < this.steps)
this.content.style.overflow = this.overflow;
}
this.timer = null;
};
Spry.Widget.CollapsiblePanel.PanelAnimator.prototype.stepAnimation = function()
{
++this.stepCount;
this.animate();
if (this.stepCount < this.steps)
this.start();
else if (this.onComplete)
this.onComplete();
};
Spry.Widget.CollapsiblePanel.PanelAnimator.prototype.animate = function()
{
if (this.stepCount >= this.steps)
{
if (!this.doOpen)
this.content.style.display = "none";
this.content.style.overflow = this.overflow;
this.content.style.height = this.toHeight + "px";
}
else
{
this.fromHeight += this.increment;
this.content.style.height = this.fromHeight + "px";
}
};
My problem is that I want to close all other row when I click on any one.
change the "Spry.Widget.CollapsiblePanel.prototype.onBlur" section for this:
Spry.Widget.CollapsiblePanel.prototype.onBlur = function(e)
{
this.contentIsOpen = false;
if (this.enableAnimation)
{
if (this.animator)
this.animator.stop();
this.animator = new Spry.Widget.CollapsiblePanel.PanelAnimator(this, false, { duration: this.duration, fps: this.fps, transition: this.transition });
this.animator.start();
}
this.removeClassName(this.element, this.openClass);
this.addClassName(this.element, this.closedClass);
};

Categories