Couldn't establish an ajax connection using jQuery, form automatically submits? - php

I am quite a newbie on Jquery and just faced a problem that I'm not able to get over.
I, simply, have an HTML form with a few elements on a page. I want to validate the form values upon clicking the submit button, and then insert some of the form values to a db using JQuery. Right after the insert process completed successfully, I want the form to be submitted naturally.
I made the validation work, and get all to values successfully from the form, but I am not able to connect to the PHP page. I have two pages.
Here is the JQuery code:
<script type="text/javascript">
$(document).ready(function() {
$("#odeme").submit(function() {
$('#ok').attr('disabled', 'disabled');
$("#ok").after('<span id="info" style="font-size:8pt;color:green;padding-left:5px;"><img align="absmiddle" src="loading.gif" border="0" /> Ödemeniz Yapılıyor</span>');
//değişkenler
var jad = $("#ad").val().length;
var jsoyad = $("#soyad").val().length;
var jadres = $("#adres").val().length;
var jeposta = $("#eposta").val().length;
var isEposta = $("#eposta").val();
var epostaReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var jsehir = $("#sehir").val();
var jtaksit = $("#taksit").val();
var jkartisim = $("#kartisim").val().length;
var jkartno = $("#kartno").val().length;
var jkartay = $("#kartay").val();
var jkartyil = $("#kartyil").val();
var jkartcvv = $("#kartcvv").val().length;
var hasError = false;
// kontrollere başla
if (jad < 6) {
$('#ad').css('border', 'solid 1px red');
hasError = true;
}
if (jsoyad < 2) {
$('#soyad').css('border', 'solid 1px red');
hasError = true;
}
if (jadres < 10) {
$('#adres').css('border', 'solid 1px red');
hasError = true;
}
if (jeposta < 6) {
$('#eposta').css('border', 'solid 1px red');
hasError = true;
}
if (jsehir == 0) {
$('#sehir').css('border', 'solid 1px red');
hasError = true;
}
if (jtaksit == 20) {
$('#taksit').css('background', '#FF9494');
hasError = true;
}
if (jkartisim < 6) {
$('#kartisim').css('border', 'solid 1px red');
hasError = true;
}
if (jkartno < 15) {
$('#kartno').css('border', 'solid 1px red');
hasError = true;
}
if (jkartay == 0) {
$('#kartay').css('border', 'solid 1px red');
hasError = true;
}
if (jkartyil == 0) {
$('#kartyil').css('border', 'solid 1px red');
hasError = true;
}
if (jkartcvv != 3) {
$('#kartcvv').css('border', 'solid 1px red');
hasError = true;
}
if ($('#sozlesme').is(':checked')) {
hasError = false;
} else {
$('#sozlesme').css('outline-color', 'red');
$('#sozlesme').css('outline-style', 'solid');
$('#sozlesme').css('outline-width', 'thin');
hasError = true;
}
if (!epostaReg.test(isEposta)) {
$('#eposta').css('border', 'solid 1px red');
hasError = true;
}
if (hasError == true) {
$("#info").remove();
$("#ok").after('<span id="errorSpan" style="color:red;padding-left:5px;">Lütfen formu eksiksiz doldurunuz.</span>');
$("#errorSpan").delay(3000).fadeOut(2000);
$('#ok').removeAttr("disabled");
return false;
} else {
// form verilerini db ye at
var form_ad = $("#ad").val();
var form_soyad = $("#soyad").val();
var form_adres = $("#adres").val();
var form_eposta = $("#eposta").val();
var form_sehir = $("#sehir").val();
var form_taksit = $("#taksit").val();
var form_telno = $("#telno").val();
var form_cinsiyet = $("#cinsiyet").val();
var dataString = 'ad='+ form_ad +
'&soyad=' + form_soyad +
'&adres=' + form_adres +
'&eposta=' + form_eposta +
'&sehir=' + form_sehir +
'&taksit=' + form_taksit +
'&telno=' + form_telno +
'&cinsiyet=' + form_cinsiyet;
alert(dataString);
JQuery.ajax({
type: "POST",
url: "form.php",
data: dataString,
cache: false,
success: function(result){
if(result == 1) {
alert(result);
return false; }
else {
$("#ok").after('<span id="errorSpan" style="color:red;padding-left:5px;">Lütfen formu eksiksiz doldurunuz.</span>');
}
}
});
}
});
});
</script>
and here is the code of the form.php
<?php
If (!isset($_POST['ad'])) {
echo 0;
}
else {
$ad = $_POST['ad'];
If ($ad == "asdasd") {
echo 1;
} else {
echo 0;
}
}
?>
I have read all the questions asked about this issue and try to apply all the solutions, but I'm stucked :/

Try this:
$(document).ready(function() {
$("#odeme").submit(function() {
//validation
//and
//ajax
return false; //this suppresses default form submission behaviour
});
});

Related

Why is laravel 5.8.35 showing me this javascript

I am trying to do ajax with laravel. I am using jquery for ajax and making a simple call to a php function when user types in a name (3 letters for first call). I know my php function because I have var dumped the result in php and I can see it returns exactly what is expected however when i see that suuccess response on the ajax side it has load of javascript that i have no idea where it is coming from + the response I was expecting.
HTML
<input name="search" id="search" class="input-group" onkeydown="search_data(this.value)"/>
AJAX JQUERY
<script>
function search_data(search_value) {
if (search_value.length >= 3) {
console.log(search_value);
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: '/searching',
data: {id: search_value},
contentType: 'application/json; charset=utf-8',
method: 'POST',
success: function (data) {
alert(data);
console.log(data);
}
});
}
}
</script>
ROUTE
Route::post('/searching','HomeController#getResult')->name('searchResult');
PHP FUNCTION
public function getResult()
{
$search = \request('id');
$date = now()->toDateString();
$result = DB::select(DB::raw("SELECT *
FROM io_badar.address_books
join io_badar.events
ON io_badar.address_books.id = io_badar.events.address_book_id
where ((address_books.firstname LIKE '%$search%') and (events.meeting_date = '$date'));"));
$test = json_encode($result);
return $test;
}
RESPONSE THAT I SEE IN CONSOLE IS BELOW
<script> Sfdump = window.Sfdump || (function (doc) { var refStyle = doc.createElement('style'), rxEsc = /([.*+?^${}()|\[\]\/\\])/g, idRx = /\bsf-dump-\d+-ref[012]\w+\b/, keyHint = 0 <= navigator.platform.toUpperCase().indexOf('MAC') ? 'Cmd' : 'Ctrl', addEventListener = function (e, n, cb) { e.addEventListener(n, cb, false); }; (doc.documentElement.firstElementChild || doc.documentElement.children[0]).appendChild(refStyle); if (!doc.addEventListener) { addEventListener = function (element, eventName, callback) { element.attachEvent('on' + eventName, function (e) { e.preventDefault = function () {e.returnValue = false;}; e.target = e.srcElement; callback(e); }); }; } function toggle(a, recursive) { var s = a.nextSibling || {}, oldClass = s.className, arrow, newClass; if (/\bsf-dump-compact\b/.test(oldClass)) { arrow = '▼'; newClass = 'sf-dump-expanded'; } else if (/\bsf-dump-expanded\b/.test(oldClass)) { arrow = '▶'; newClass = 'sf-dump-compact'; } else { return false; } if (doc.createEvent && s.dispatchEvent) { var event = doc.createEvent('Event'); event.initEvent('sf-dump-expanded' === newClass ? 'sfbeforedumpexpand' : 'sfbeforedumpcollapse', true, false); s.dispatchEvent(event); } a.lastChild.innerHTML = arrow; s.className = s.className.replace(/\bsf-dump-(compact|expanded)\b/, newClass); if (recursive) { try { a = s.querySelectorAll('.'+oldClass); for (s = 0; s < a.length; ++s) { if (-1 == a[s].className.indexOf(newClass)) { a[s].className = newClass; a[s].previousSibling.lastChild.innerHTML = arrow; } } } catch (e) { } } return true; }; function collapse(a, recursive) { var s = a.nextSibling || {}, oldClass = s.className; if (/\bsf-dump-expanded\b/.test(oldClass)) { toggle(a, recursive); return true; } return false; }; function expand(a, recursive) { var s = a.nextSibling || {}, oldClass = s.className; if (/\bsf-dump-compact\b/.test(oldClass)) { toggle(a, recursive); return true; } return false; }; function collapseAll(root) { var a = root.querySelector('a.sf-dump-toggle'); if (a) { collapse(a, true); expand(a); return true; } return false; } function reveal(node) { var previous, parents = []; while ((node = node.parentNode || {}) && (previous = node.previousSibling) && 'A' === previous.tagName) { parents.push(previous); } if (0 !== parents.length) { parents.forEach(function (parent) { expand(parent); }); return true; } return false; } function highlight(root, activeNode, nodes) { resetHighlightedNodes(root); Array.from(nodes||[]).forEach(function (node) { if (!/\bsf-dump-highlight\b/.test(node.className)) { node.className = node.className + ' sf-dump-highlight'; } }); if (!/\bsf-dump-highlight-active\b/.test(activeNode.className)) { activeNode.className = activeNode.className + ' sf-dump-highlight-active'; } } function resetHighlightedNodes(root) { Array.from(root.querySelectorAll('.sf-dump-str, .sf-dump-key, .sf-dump-public, .sf-dump-protected, .sf-dump-private')).forEach(function (strNode) { strNode.className = strNode.className.replace(/\bsf-dump-highlight\b/, ''); strNode.className = strNode.className.replace(/\bsf-dump-highlight-active\b/, ''); }); } return function (root, x) { root = doc.getElementById(root); var indentRx = new RegExp('^('+(root.getAttribute('data-indent-pad') || ' ').replace(rxEsc, '\\$1')+')+', 'm'), options = {"maxDepth":1,"maxStringLength":160,"fileLinkFormat":false}, elt = root.getElementsByTagName('A'), len = elt.length, i = 0, s, h, t = []; while (i < len) t.push(elt[i++]); for (i in x) { options[i] = x[i]; } function a(e, f) { addEventListener(root, e, function (e, n) { if ('A' == e.target.tagName) { f(e.target, e); } else if ('A' == e.target.parentNode.tagName) { f(e.target.parentNode, e); } else if ((n = e.target.nextElementSibling) && 'A' == n.tagName) { if (!/\bsf-dump-toggle\b/.test(n.className)) { n = n.nextElementSibling; } f(n, e, true); } }); }; function isCtrlKey(e) { return e.ctrlKey || e.metaKey; } function xpathString(str) { var parts = str.match(/[^'"]+|['"]/g).map(function (part) { if ("'" == part) { return '"\'"'; } if ('"' == part) { return "'\"'"; } return "'" + part + "'"; }); return "concat(" + parts.join(",") + ", '')"; } function xpathHasClass(className) { return "contains(concat(' ', normalize-space(#class), ' '), ' " + className +" ')"; } addEventListener(root, 'mouseover', function (e) { if ('' != refStyle.innerHTML) { refStyle.innerHTML = ''; } }); a('mouseover', function (a, e, c) { if (c) { e.target.style.cursor = "pointer"; } else if (a = idRx.exec(a.className)) { try { refStyle.innerHTML = 'pre.sf-dump .'+a[0]+'{background-color: #B729D9; color: #FFF !important; border-radius: 2px}'; } catch (e) { } } }); a('click', function (a, e, c) { if (/\bsf-dump-toggle\b/.test(a.className)) { e.preventDefault(); if (!toggle(a, isCtrlKey(e))) { var r = doc.getElementById(a.getAttribute('href').substr(1)), s = r.previousSibling, f = r.parentNode, t = a.parentNode; t.replaceChild(r, a); f.replaceChild(a, s); t.insertBefore(s, r); f = f.firstChild.nodeValue.match(indentRx); t = t.firstChild.nodeValue.match(indentRx); if (f && t && f[0] !== t[0]) { r.innerHTML = r.innerHTML.replace(new RegExp('^'+f[0].replace(rxEsc, '\\$1'), 'mg'), t[0]); } if (/\bsf-dump-compact\b/.test(r.className)) { toggle(s, isCtrlKey(e)); } } if (c) { } else if (doc.getSelection) { try { doc.getSelection().removeAllRanges(); } catch (e) { doc.getSelection().empty(); } } else { doc.selection.empty(); } } else if (/\bsf-dump-str-toggle\b/.test(a.className)) { e.preventDefault(); e = a.parentNode.parentNode; e.className = e.className.replace(/\bsf-dump-str-(expand|collapse)\b/, a.parentNode.className); } }); elt = root.getElementsByTagName('SAMP'); len = elt.length; i = 0; while (i < len) t.push(elt[i++]); len = t.length; for (i = 0; i < len; ++i) { elt = t[i]; if ('SAMP' == elt.tagName) { a = elt.previousSibling || {}; if ('A' != a.tagName) { a = doc.createElement('A'); a.className = 'sf-dump-ref'; elt.parentNode.insertBefore(a, elt); } else { a.innerHTML += ' '; } a.title = (a.title ? a.title+'\n[' : '[')+keyHint+'+click] Expand all children'; a.innerHTML += '<span>▼</span>'; a.className += ' sf-dump-toggle'; x = 1; if ('sf-dump' != elt.parentNode.className) { x += elt.parentNode.getAttribute('data-depth')/1; } elt.setAttribute('data-depth', x); var className = elt.className; elt.className = 'sf-dump-expanded'; if (className ? 'sf-dump-expanded' !== className : (x > options.maxDepth)) { toggle(a); } } else if (/\bsf-dump-ref\b/.test(elt.className) && (a = elt.getAttribute('href'))) { a = a.substr(1); elt.className += ' '+a; if (/[\[{]$/.test(elt.previousSibling.nodeValue)) { a = a != elt.nextSibling.id && doc.getElementById(a); try { s = a.nextSibling; elt.appendChild(a); s.parentNode.insertBefore(a, s); if (/^[##]/.test(elt.innerHTML)) { elt.innerHTML += ' <span>▶</span>'; } else { elt.innerHTML = '<span>▶</span>'; elt.className = 'sf-dump-ref'; } elt.className += ' sf-dump-toggle'; } catch (e) { if ('&' == elt.innerHTML.charAt(0)) { elt.innerHTML = '…'; elt.className = 'sf-dump-ref'; } } } } } if (doc.evaluate && Array.from && root.children.length > 1) { root.setAttribute('tabindex', 0); SearchState = function () { this.nodes = []; this.idx = 0; }; SearchState.prototype = { next: function () { if (this.isEmpty()) { return this.current(); } this.idx = this.idx < (this.nodes.length - 1) ? this.idx + 1 : 0; return this.current(); }, previous: function () { if (this.isEmpty()) { return this.current(); } this.idx = this.idx > 0 ? this.idx - 1 : (this.nodes.length - 1); return this.current(); }, isEmpty: function () { return 0 === this.count(); }, current: function () { if (this.isEmpty()) { return null; } return this.nodes[this.idx]; }, reset: function () { this.nodes = []; this.idx = 0; }, count: function () { return this.nodes.length; }, }; function showCurrent(state) { var currentNode = state.current(), currentRect, searchRect; if (currentNode) { reveal(currentNode); highlight(root, currentNode, state.nodes); if ('scrollIntoView' in currentNode) { currentNode.scrollIntoView(true); currentRect = currentNode.getBoundingClientRect(); searchRect = search.getBoundingClientRect(); if (currentRect.top < (searchRect.top + searchRect.height)) { window.scrollBy(0, -(searchRect.top + searchRect.height + 5)); } } } counter.textContent = (state.isEmpty() ? 0 : state.idx + 1) + ' of ' + state.count(); } var search = doc.createElement('div'); search.className = 'sf-dump-search-wrapper sf-dump-search-hidden'; search.innerHTML = ' <input type="text" class="sf-dump-search-input"> <span class="sf-dump-search-count">0 of 0<\/span> <button type="button" class="sf-dump-search-input-previous" tabindex="-1"> <svg viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg"><path d="M1683 1331l-166 165q-19 19-45 19t-45-19L896 965l-531 531q-19 19-45 19t-45-19l-166-165q-19-19-19-45.5t19-45.5l742-741q19-19 45-19t45 19l742 741q19 19 19 45.5t-19 45.5z"\/><\/svg> <\/button> <button type="button" class="sf-dump-search-input-next" tabindex="-1"> <svg viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg"><path d="M1683 808l-742 741q-19 19-45 19t-45-19L109 808q-19-19-19-45.5t19-45.5l166-165q19-19 45-19t45 19l531 531 531-531q19-19 45-19t45 19l166 165q19 19 19 45.5t-19 45.5z"\/><\/svg> <\/button> '; root.insertBefore(search, root.firstChild); var state = new SearchState(); var searchInput = search.querySelector('.sf-dump-search-input'); var counter = search.querySelector('.sf-dump-search-count'); var searchInputTimer = 0; var previousSearchQuery = ''; addEventListener(searchInput, 'keyup', function (e) { var searchQuery = e.target.value; /* Don't perform anything if the pressed key didn't change the query */ if (searchQuery === previousSearchQuery) { return; } previousSearchQuery = searchQuery; clearTimeout(searchInputTimer); searchInputTimer = setTimeout(function () { state.reset(); collapseAll(root); resetHighlightedNodes(root); if ('' === searchQuery) { counter.textContent = '0 of 0'; return; } var classMatches = [ "sf-dump-str", "sf-dump-key", "sf-dump-public", "sf-dump-protected", "sf-dump-private", ].map(xpathHasClass).join(' or '); var xpathResult = doc.evaluate('.//span[' + classMatches + '][contains(translate(child::text(), ' + xpathString(searchQuery.toUpperCase()) + ', ' + xpathString(searchQuery.toLowerCase()) + '), ' + xpathString(searchQuery.toLowerCase()) + ')]', root, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null); while (node = xpathResult.iterateNext()) state.nodes.push(node); showCurrent(state); }, 400); }); Array.from(search.querySelectorAll('.sf-dump-search-input-next, .sf-dump-search-input-previous')).forEach(function (btn) { addEventListener(btn, 'click', function (e) { e.preventDefault(); -1 !== e.target.className.indexOf('next') ? state.next() : state.previous(); searchInput.focus(); collapseAll(root); showCurrent(state); }) }); addEventListener(root, 'keydown', function (e) { var isSearchActive = !/\bsf-dump-search-hidden\b/.test(search.className); if ((114 === e.keyCode && !isSearchActive) || (isCtrlKey(e) && 70 === e.keyCode)) { /* F3 or CMD/CTRL + F */ e.preventDefault(); search.className = search.className.replace(/\bsf-dump-search-hidden\b/, ''); searchInput.focus(); } else if (isSearchActive) { if (27 === e.keyCode) { /* ESC key */ search.className += ' sf-dump-search-hidden'; e.preventDefault(); resetHighlightedNodes(root); searchInput.value = ''; } else if ( (isCtrlKey(e) && 71 === e.keyCode) /* CMD/CTRL + G */ || 13 === e.keyCode /* Enter */ || 114 === e.keyCode /* F3 */ ) { e.preventDefault(); e.shiftKey ? state.previous() : state.next(); collapseAll(root); showCurrent(state); } } }); } if (0 >= options.maxStringLength) { return; } try { elt = root.querySelectorAll('.sf-dump-str'); len = elt.length; i = 0; t = []; while (i < len) t.push(elt[i++]); len = t.length; for (i = 0; i < len; ++i) { elt = t[i]; s = elt.innerText || elt.textContent; x = s.length - options.maxStringLength; if (0 < x) { h = elt.innerHTML; elt[elt.innerText ? 'innerText' : 'textContent'] = s.substring(0, options.maxStringLength); elt.className += ' sf-dump-str-collapse'; elt.innerHTML = '<span class=sf-dump-str-collapse>'+h+'<a class="sf-dump-ref sf-dump-str-toggle" title="Collapse"> ◀</a></span>'+ '<span class=sf-dump-str-expand>'+elt.innerHTML+'<a class="sf-dump-ref sf-dump-str-toggle" title="'+x+' remaining characters"> ▶</a></span>'; } } } catch (e) { } }; })(document); </script><style> pre.sf-dump { display: block; white-space: pre; padding: 5px; overflow: initial !important; } pre.sf-dump:after { content: ""; visibility: hidden; display: block; height: 0; clear: both; } pre.sf-dump span { display: inline; } pre.sf-dump .sf-dump-compact { display: none; } pre.sf-dump abbr { text-decoration: none; border: none; cursor: help; } pre.sf-dump a { text-decoration: none; cursor: pointer; border: 0; outline: none; color: inherit; } pre.sf-dump .sf-dump-ellipsis { display: inline-block; overflow: visible; text-overflow: ellipsis; max-width: 5em; white-space: nowrap; overflow: hidden; vertical-align: top; } pre.sf-dump .sf-dump-ellipsis+.sf-dump-ellipsis { max-width: none; } pre.sf-dump code { display:inline; padding:0; background:none; } .sf-dump-str-collapse .sf-dump-str-collapse { display: none; } .sf-dump-str-expand .sf-dump-str-expand { display: none; } .sf-dump-public.sf-dump-highlight, .sf-dump-protected.sf-dump-highlight, .sf-dump-private.sf-dump-highlight, .sf-dump-str.sf-dump-highlight, .sf-dump-key.sf-dump-highlight { background: rgba(111, 172, 204, 0.3); border: 1px solid #7DA0B1; border-radius: 3px; } .sf-dump-public.sf-dump-highlight-active, .sf-dump-protected.sf-dump-highlight-active, .sf-dump-private.sf-dump-highlight-active, .sf-dump-str.sf-dump-highlight-active, .sf-dump-key.sf-dump-highlight-active { background: rgba(253, 175, 0, 0.4); border: 1px solid #ffa500; border-radius: 3px; } pre.sf-dump .sf-dump-search-hidden { display: none !important; } pre.sf-dump .sf-dump-search-wrapper { font-size: 0; white-space: nowrap; margin-bottom: 5px; display: flex; position: -webkit-sticky; position: sticky; top: 5px; } pre.sf-dump .sf-dump-search-wrapper > * { vertical-align: top; box-sizing: border-box; height: 21px; font-weight: normal; border-radius: 0; background: #FFF; color: #757575; border: 1px solid #BBB; } pre.sf-dump .sf-dump-search-wrapper > input.sf-dump-search-input { padding: 3px; height: 21px; font-size: 12px; border-right: none; border-top-left-radius: 3px; border-bottom-left-radius: 3px; color: #000; min-width: 15px; width: 100%; } pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-input-next, pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-input-previous { background: #F2F2F2; outline: none; border-left: none; font-size: 0; line-height: 0; } pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-input-next { border-top-right-radius: 3px; border-bottom-right-radius: 3px; } pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-input-next > svg, pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-input-previous > svg { pointer-events: none; width: 12px; height: 12px; } pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-count { display: inline-block; padding: 0 5px; margin: 0; border-left: none; line-height: 21px; font-size: 12px; }pre.sf-dump, pre.sf-dump .sf-dump-default{background-color:#18171B; color:#FF8400; line-height:1.2em; font:12px Menlo, Monaco, Consolas, monospace; word-wrap: break-word; white-space: pre-wrap; position:relative; z-index:99999; word-break: break-all}pre.sf-dump .sf-dump-num{font-weight:bold; color:#1299DA}pre.sf-dump .sf-dump-const{font-weight:bold}pre.sf-dump .sf-dump-str{font-weight:bold; color:#56DB3A}pre.sf-dump .sf-dump-note{color:#1299DA}pre.sf-dump .sf-dump-ref{color:#A0A0A0}pre.sf-dump .sf-dump-public{color:#FFFFFF}pre.sf-dump .sf-dump-protected{color:#FFFFFF}pre.sf-dump .sf-dump-private{color:#FFFFFF}pre.sf-dump .sf-dump-meta{color:#B729D9}pre.sf-dump .sf-dump-key{color:#56DB3A}pre.sf-dump .sf-dump-index{color:#1299DA}pre.sf-dump .sf-dump-ellipsis{color:#FF8400}pre.sf-dump .sf-dump-ns{user-select:none;}</style><pre class=sf-dump id=sf-dump-1674511034 data-indent-pad=" "><span class=sf-dump-const>null</span>
</pre><script>Sfdump("sf-dump-1674511034")</script>
[{"id":5,"firstname":"Tony","lastname":"Stark","email":"abc#bcn.co.uk","company":"Stark Industries","car_reg":"asdfasd","created_at":"2019-10-14 08:03:55","updated_at":"2019-10-14 08:03:55","meeting_date":"2019-10-14","check_in":"10:00:00","check_out":"12:00:00","address_book_id":6,"bcn_user_id":1,"location":"Manchester"}]
OK, I have fixed my issue. There wasnt any problem with my code as I learnt it was my env file. I had APP_DEBUG=true which was showing all this javascript and now it works perfectly with APP_DEBUG=false
refer following link https://laravel.com/docs/5.8/responses#json-responses
use laravel standard methods
return response()->json($result);

Sorting of html-table with data from sql-query by clicking on field-name

I have an sql-database, where data can be read out by an html-form. The data are shown in an html-table, this works fine! However, I would like to make the table sortable, which means, that by clicking on the respective field-name the data should be sorted according to this field (ascending/descending). I have tried different javaScript-solutions including tablesorter.com that work well in "normal" tables, however, not in this table that is built dynamically with data from a database. Here is my code that creates the table (code without specific link to JavaScript-files):
$sql = "SELECT * FROM fruitdatabase WHERE (" . implode(", ",
$spalten) . ") = (" . implode(", ", $werte) . ")";
$result = mysqli_query($db, $sql) or die("Invalid query"); //Running the
query and storing it in result
$numrows = mysqli_num_rows($result); // gets number of rows in result
table
$numcols = mysqli_num_fields($result); // gets number of columns in
result table
$field = mysqli_fetch_fields($result); // gets the column names from the
result table
$row = mysqli_fetch_array($result);
if ($numrows > 0) {
echo "<table id=myTable class=tablesorter>";
echo "<thead><tr>";
echo "<th>" . 'Nr' . "</th>";
for($x=0;$x<$numcols;$x++){
echo "<th>" . $field[$x]->name . "</th>";
}
echo "</tr></thead>";
echo "<tbody><tr>";
$nr = 1;
while ($row = mysqli_fetch_array($result)) {
echo "<td>" . $nr . "</td>";
for ($k=0; $k<$numcols; $k++) { // goes around until there are no
columns left
echo "<td>" . $row[$k] . "</td>"; //Prints the data
}
$nr = $nr + 1;
echo "</tr></tbody>";
}
echo "</table>";
}
}
mysqli_close($db);
?>
One of the javaScript-files I tried:
(function () {
"use strict";
var tableSort = function (tab) {
var titel = tab.getElementsByTagName("thead")
[0].getElementsByTagName("tr")[
0].getElementsByTagName("th");
var tbdy = tab.getElementsByTagName("tbody")[0];
var tz = tbdy.rows;
var nzeilen = tz.length;
if (nzeilen == 0) return;
var nspalten = tz[0].cells.length;
var arr = new Array(nzeilen);
var sortiert = -1;
var sorttype = new Array(nspalten);
var sortbuttonStyle = document.createElement
('style'); // Stylesheet für Button im TH
sortbuttonStyle.innerText =
'.sortbutton { width:100%; height:100%; border:
none; background-color: transparent; font: inherit; color: inherit; text-
align: inherit; padding: 0; cursor: pointer; } .sortbutton::-moz-focus-
inner { margin: -1px; border-width: 1px; padding: 0; }';
document.head.appendChild(sortbuttonStyle);
var initTableHead = function (sp) { // Kopfzeile
vorbereiten
var b = document.createElement("button");
b.type = "button";
b.className = "sortbutton";
b.innerHTML = titel[sp].innerHTML;
b.addEventListener("click", function () {
tsort(sp);
}, false);
titel[sp].innerHTML = "";
titel[sp].appendChild(b);
}
var getData = function (ele, s) {
var val = ele.innerHTML;
if (!isNaN(val) && val.search(/[0-9]/) !
= -1) return val;
var n = val.replace(",", ".");
if (!isNaN(n) && n.search(/[0-9]/) !=
-1) return n;
sorttype[s] = "s"; // String
return val;
} // getData
var vglFkt_s = function (a, b) {
var as = a[sortiert],
bs = b[sortiert];
if (as > bs) return 1;
else return -1;
} // vglFkt_s
var vglFkt_n = function (a, b) {
return parseFloat(a[sortiert]) -
parseFloat(b[sortiert]);
} // vglFkt_n
var tsort = function (sp) {
if (sp == sortiert) arr.reverse(); //
Tabelle ist schon nach dieser Spalte sortiert, also nur Reihenfolge
umdrehen
else { // Sortieren
sortiert = sp;
if (sorttype[sp] == "n")
arr.sort(vglFkt_n);
else arr.sort(vglFkt_s);
}
for (var z = 0; z < nzeilen; z++)
tbdy.appendChild(arr[z][nspalten]); // Sortierte Daten zurückschreiben
} // tsort
// Kopfzeile vorbereiten
for (var i = 0; i < titel.length; i++) initTableHead(i);
// Array mit Info, wie Spalte zu sortieren ist,
vorbelegen
for (var s = 0; s < nspalten; s++) sorttype[s] = "n";
// Tabelleninhalt in ein Array kopieren
for (var z = 0; z < nzeilen; z++) {
var zelle = tz[z].getElementsByTagName
("td"); // cells;
arr[z] = new Array(nspalten + 1);
arr[z][nspalten] = tz[z];
for (var s = 0; s < nspalten; s++) {
var zi = getData(zelle[s], s);
arr[z][s] = zi;
// zelle[s].innerHTML
+= "<br>"+zi+"<br>"+sorttype[s]; // zum Debuggen
}
}
} // tableSort
var initTableSort = function () {
var sort_Table = document.querySelectorAll
("table.sortierbar");
for (var i = 0; i < sort_Table.length; i++) new
tableSort(sort_Table[i]);
} // initTable
if (window.addEventListener) window.addEventListener("DOMContentLoaded",
initTableSort, false); // nicht im IE8
})();
Another of the javaScript-files I tried:
( function() {
"use strict";
var JB_sortbutStyle = document.createElement('style'); // Stylesheet
für Button im TH
JB_sortbutStyle.innerText = 'button.sortbut { width:100%; height:100%;
border: none; background-color: transparent; font: inherit; color:
inherit; text-align: inherit; padding: 0; cursor: pointer; }
button.sortbut::-moz-focus-inner { margin: -1px; border-width: 1px;
padding: 0; }';
document.head.appendChild(JB_sortbutStyle);
var JB_Table = function(tab) {
var up = String.fromCharCode(9650);
var down = String.fromCharCode(9660);
// var up = String.fromCharCode(8593);
// var down = String.fromCharCode(8595);
// var up = String.fromCharCode(11014);
// var down = String.fromCharCode(11015);
var no = String.fromCharCode(160,160,160,160); // Idee: 9674 ???
var dieses = this;
var defsort = 0;
var startsort_u = -1,startsort_d = -1;
var first = true;
var ssort;
var tbdy = tab.getElementsByTagName("tbody")[0];
var tz = tbdy.rows;
var nzeilen = tz.length;
if (nzeilen==0) return;
var nspalten = tz[0].cells.length;
var Titel = tab.getElementsByTagName("thead")
[0].getElementsByTagName("tr")[0].getElementsByTagName("th");
var Arr = new Array(nzeilen);
var ct = 0;
var sdir = new Array(nspalten);
var stype = new Array(nspalten);
var sortable = new Array(nspalten);
for(var i=0;i<nspalten;i++) {
stype[i] = "n";
sdir[i] = "u";
sortable[i] = false;
}
var initTableHead = function(t,nr) {
var b = document.createElement("button");
b.type = "button";
b.className = "sortbut"
b.innerHTML = t.innerHTML;
t.innerHTML = "";
if(window.addEventListener) b.addEventListener
("click",function() { dieses.sort(nr); },false);
b.title = 'Die Tabelle nach "'+b.textContent+'"
sortieren.';
t.appendChild(b);
sortsymbol.init(t,no);
if(t.className.indexOf("vorsortiert-")>-1) {
sortsymbol.set(t,down);
ssort = nr;
}
else if(t.className.indexOf("vorsortiert")>-1) {
sortsymbol.set(t,up);
ssort = nr;
}
if(t.className.indexOf("sortiere-")>-1) startsort_d=nr;
else if(t.className.indexOf("sortiere")>-1)
startsort_u=nr;
sortable[nr] = true;
} // initTableHead
var sortsymbol = {
init: function(t,s) {
var tt = t.querySelector("button");
var sp = tt.getElementsByTagName("span");
for(var i=0;i<sp.length;i++) {
if(!sp[i].hasChildNodes()) {
t.sym = sp[i].appendChild
(document.createTextNode(s));
break;
}
}
if(typeof(t.sym)=="undefined") t.sym =
tt.appendChild(document.createTextNode(s));
},
set: function(t,s) {
t.sym.data = s;
},
get: function(t) {
return t.sym.data;
}
} // sortsymbol
var VglFkt_s = function(a,b) {
var as = a[ssort], bs = b[ssort];
var ret=(as>bs)?1:(as<bs)?-1:0;
if(!ret && ssort!=defsort) {
if (stype[defsort]=="s") { as = a[defsort]; bs
= b[defsort]; ret = (as>bs)?1:(as<bs)?-1:0; }
else ret = parseFloat(a[defsort])-parseFloat(b
[defsort])
}
return ret;
} // VglFkt_s
var VglFkt_n = function(a,b) {
var ret = parseFloat(a[ssort])-parseFloat(b[ssort]);
if(!ret && ssort!=defsort) {
if (stype[defsort]=="s") { var as = a
[defsort],bs = b[defsort]; ret = (as>bs)?1:(as<bs)?-1:0; }
else ret = parseFloat(a[defsort])-parseFloat(b
[defsort]);
}
return ret;
} // VglFkt_n
var convert = function(val,s) {
var dmy;
var trmdat = function() {
if(dmy[0]<10) dmy[0] = "0" + dmy[0];
if(dmy[1]<10) dmy[1] = "0" + dmy[1];
if(dmy[2]<10) dmy[2] = "200" + dmy[2];
else if(dmy[2]<20) dmy[2] = "20" + dmy[2];
else if(dmy[2]<99) dmy[2] = "19" + dmy[2];
else if(dmy[2]>9999) dmy[2] = "9999";
}
if(val.length==0) val = "0";
if(!isNaN(val) && val.search(/[0-9]/)!=-1) return val;
var n = val.replace(",",".");
if(!isNaN(n) && n.search(/[0-9]/)!=-1) return n;
n = n.replace(/\s| | |\u00A0/g,"");
if(!isNaN(n) && n.search(/[0-9]/)!=-1) return n;
if(!val.search
(/^\s*\d+\s*\.\s*\d+\s*\.\s*\d+\s+\d+:\d\d\:\d\d\s*$/)) {
var dp = val.search(":");
dmy = val.substring(0,dp-2).split(".");
dmy[3] = val.substring(dp-2,dp);
dmy[4] = val.substring(dp+1,dp+3);
dmy[5] = val.substring(dp+4,dp+6);
for(var i=0;i<6;i++) dmy[i] = parseInt(dmy
[i],10);
trmdat();
for(var i=3;i<6;i++) if(dmy[i]<10) dmy[i] = "0"
+ dmy[i];
return (""+dmy[2]+dmy[1]+dmy[0]+"."+dmy[3]+dmy
[4]+dmy[5]).replace(/ /g,"");
}
if(!val.search
(/^\s*\d+\s*\.\s*\d+\s*\.\s*\d+\s+\d+:\d\d\s*$/)) {
var dp = val.search(":");
dmy = val.substring(0,dp-2).split(".");
dmy[3] = val.substring(dp-2,dp);
dmy[4] = val.substring(dp+1,dp+3);
for(var i=0;i<5;i++) dmy[i] = parseInt(dmy
[i],10);
trmdat();
for(var i=3;i<5;i++) if(dmy[i]<10) dmy[i]
= "0"+dmy[i];
return (""+dmy[2]+dmy[1]+dmy[0]+"."+dmy[3]+dmy
[4]).replace(/ /g,"");
}
if(!val.search(/^\s*\d+:\d\d\:\d\d\s*$/)) {
dmy = val.split(":");
for(var i=0;i<3;i++) dmy[i] = parseInt(dmy
[i],10);
for(var i=0;i<3;i++) if(dmy[i]<10) dmy[i]
= "0"+dmy[i];
return (""+dmy[0]+dmy[1]+"."+dmy[2]).replace
(/ /g,"");
}
if(!val.search(/^\s*\d+:\d\d\s*$/)) {
dmy = val.split(":");
for(var i=0;i<2;i++) dmy[i] = parseInt(dmy
[i],10);
for(var i=0;i<2;i++) if(dmy[i]<10) dmy[i]
= "0"+dmy[i];
return (""+dmy[0]+dmy[1]).replace(/ /g,"");
}
if(!val.search(/^\s*\d+\s*\.\s*\d+\s*\.\s*\d+/)) {
dmy = val.split(".");
for(var i=0;i<3;i++) dmy[i] = parseInt(dmy
[i],10);
trmdat();
return (""+dmy[2]+dmy[1]+dmy[0]).replace
(/ /g,"");
}
stype[s] = "s";
// return val.toLowerCase().replace(/
\u00e4/g,"ae").replace(/\u00f6/g,"oe").replace(/\u00fc/g,"ue").replace(/
\u00df/g,"ss");
return val.toLowerCase().replace(/\u00e4/g,"a ").replace
(/\u00f6/g,"o ").replace(/\u00fc/g,"u ").replace(/\u00df/g,"ss");
} // convert
this.sort = function(sp) {
if(sp<0 || sp>=nspalten) return;
if(!sortable[sp]) return;
if (first) {
for(var z=0;z<nzeilen;z++) {
var zelle = tz[z].getElementsByTagName
("td"); // cells;
Arr[z] = new Array(nspalten+1);
Arr[z][nspalten] = tz[z];
for(var s=0;s<nspalten;s++) {
if (zelle[s].getAttribute("data-
sort_key"))
var zi = convert(zelle
[s].getAttribute("data-sort_key"),s);
else if (zelle[s].getAttribute
("sort_key"))
var zi = convert(zelle
[s].getAttribute("sort_key"),s);
else
var zi = convert(zelle
[s].textContent,s);
Arr[z][s] = zi ;
// zelle[s].innerHTML
+= "<br>"+zi; // zum Debuggen
}
}
first = false;
}
if(sp==ssort) {
Arr.reverse() ;
if ( sortsymbol.get(Titel[ssort])==down )
sortsymbol.set(Titel[ssort],up);
else
sortsymbol.set(Titel[ssort],down);
}
else {
if ( ssort>=0 && ssort<nspalten ) sortsymbol.set
(Titel[ssort],no);
ssort = sp;
if(stype[ssort]=="s") Arr.sort(VglFkt_s);
else Arr.sort(VglFkt_n);
if(sdir[ssort]=="u") {
sortsymbol.set(Titel[ssort],up);
}
else {
Arr.reverse() ;
sortsymbol.set(Titel[ssort],down);
}
}
for(var z=0;z<nzeilen;z++)
tbdy.appendChild(Arr[z][nspalten]);
if(typeof(JB_aftersort)=="function") JB_aftersort
(tab,tbdy,tz,nzeilen,nspalten,ssort);
} // sort
if(!tab.title.length) tab.title="Ein Klick auf die
Spalten\u00fcberschrift sortiert die Tabelle.";
for(var i=Titel.length-1;i>-1;i--) {
var t=Titel[i];
if(t.className.indexOf("sortier")>-1) {
ct++;
initTableHead(t,i);
defsort = i ;
if(t.className.indexOf("sortierbar-")>-1) sdir
[i] = "d";
}
}
if(ct==0) {
for(var i=0;i<Titel.length;i++)
initTableHead(Titel[i],i);
defsort = 0;
}
if(startsort_u>=0) this.sort(startsort_u);
if(startsort_d>=0) { this.sort(startsort_d); this.sort
(startsort_d); }
if(typeof(JB_aftersortinit)=="function") JB_aftersortinit
(tab,tbdy,tz,nzeilen,nspalten,-1);
} // JB_Table
var JB_initTableSort = function() {
if (!document.querySelectorAll) return;
var JB_Tables = [];
var Sort_Table = document.querySelectorAll("table.sortierbar,
table[sortable]");
for(var i=0;i<Sort_Table.length;i++) JB_Tables.push(new JB_Table
(Sort_Table[i]));
var pars = decodeURI(window.location.search.substring(1));
if(pars.length) { // jbts=((0,1),(10,0),(3,3),(2,2)) tnr,snr
pars = pars.replace(/\s/g,"");
pars = pars.match(/jbts=\(?(\(\d+,\d+\),?){1,}\)?/gi);
if(pars) {
pars = pars[0].substr(pars[0].search("=")+1);
pars = pars.replace(/\(\(/g,"(").replace(/\)
\)/g,")").replace(/\)\(/g,")|(").replace(/\),\(/g,")|(");
pars = pars.split("|");
for(var i=0;i<pars.length;i++) {
var p = pars[i].substring(1,pars
[i].length-1).split(",");
if(p[0]>-1&&p[0]<JB_Tables.length)
JB_Tables[p[0]].sort(p[1]);
}
}
}
} // initTableSort
if(window.addEventListener) window.addEventListener
("DOMContentLoaded",JB_initTableSort,false);
})();
I would be more than happy if anybody could help me with this Problem!
I used tablesorter for same purpose. I created table dynamically from database and it worked. First add to table id="myTable". After just call the script by adding code below:
$(document).ready(function()
{
$("#myTable").tablesorter();
}
);
Note: Don't forget to include src="jquery.tablesorter.js" (download it from download link).
Now you should be able to sort your table by all columns by just clicking on table header of column.
EDIT:
Insted of:
echo "<table id=myTable class=tablesorter>";
Put:
echo "<table id='myTable' class='tablesorter'>";
How about sorting the table before displaying?
For example, if your link to the page is:
http://example.com/view/product_table
The code for querying the table is:
function getTable($order = null) {
$statement = "SELECT * FROM product_table";
if ($order) {
// switch case to prevent sql injection
switch ($order) {
case: "price":
$statement .= " ORDER BY product_price";
break;
}
}
// Continue the build sql here
}
Have the sorting button redirect to:
http://example.com/view/product_table?sort=price
Call function by:
getTable($GET[sort]);
To further my answer
I would suggest separating the code responsible for displaying and the code for building data
Name your variable to something more meaningful
Currently your code is very hard to maintain and read.

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']

PHP ajax json on iis

New to project and php..Environment IIS 7.5
Trying to get script to retrieve pw to work on IIS.
Link
submitAJAX
function submitAJAX(iPage, iData, iSync) {
if (iSync == null) {
iSync = true;
}
$.ajax({
type: "POST",
dataType: "json",
url: iPage,
global: true,
async: iSync,
data: iData,
success: function(data, textStatus) {
handleAJAXResponse(data, textStatus);
}
});
}
ajax.js
var templateForm;
var desinationForm;
var containerForm;
/*
Wrapper for the JQuery AJAX .post function
*/
function submitAJAX(iPage, iData, iSync) {
if (iSync == null) {
iSync = true;
}
$.ajax({
type: "POST",
dataType: "json",
url: iPage,
global: true,
async: iSync,
data: iData,
success: function(data, textStatus) {
handleAJAXResponse(data, textStatus);
}
});
}
/*
Handle the JQuery AJAX Post response
*/
function handleAJAXResponse(jsonObj, textStatus) {
// Update the destination form
if ((templateForm) && (desinationForm)) {
desinationForm.html(templateForm.html());
containerForm = desinationForm.attr('id');
}
templateForm = '';
desinationForm = '';
if (textStatus == 'success') {
processJSONData(jsonObj, containerForm);
} else {
alert('AJAX Execution Error: ' + textStatus);
}
}
/*
Process the specified JSON data object
*/
function processJSONData(iJSON, iContainer) {
$.each(iJSON, function(iVariable, iValue) {
if (iValue) {
if (iContainer) {
var tmpObj = $('#' + iContainer + ' #' + iVariable);
//if (!tmpObj.size()) { var tmpObj = $('#' + iContainer + " [name=" + iVariable + "]"); }
//if (!tmpObj.size()) { var tmpObj = $('#' + iContainer + " [id*=" + iVariable + "]"); }
//if (!tmpObj.size()) { var tmpObj = $('#' + iContainer + " [name*=" + iVariable + "]"); }
} else {
var tmpObj = $('#' + iVariable);
//if (!tmpObj.size()) { var tmpObj = $("[name=" + iVariable + "]"); }
//if (!tmpObj.size()) { var tmpObj = $("[id*=" + iVariable + "]"); }
//if (!tmpObj.size()) { var tmpObj = $("[name*=" + iVariable + "]"); }
}
// If the current object is another JSON oject
if ((typeof iValue == 'object') && (iValue.toString().indexOf('object') > -1)) {
if (iContainer) {
processJSONData(iValue, iContainer + ' #' + iVariable);
} else {
processJSONData(iValue, iVariable);
}
} else {
//alert(iContainer + '.' + iVariable + ' = ' + iValue + ' : ' + tmpObj.size());
// Object exists on the page
if (tmpObj.size()) {
setFieldValue(tmpObj, iValue);
// Object doesn't exist on the page
} else {
// Check for a JS function
if (iVariable.indexOf('script_') == 0) {
setTimeout(iValue, 10);
//eval(iValue);
// Check for a form validation error
} else if (iVariable.indexOf('_error') > -1) {
setFormError(iVariable.replace('_error', ''));
} else {
//alert('AJAX Variable Error: ' + iVariable);
}
}
}
}
});
}
function setFieldValue(iFieldObj, iValue) {
switch (iFieldObj.attr('type')) {
case 'text':
case 'password':
case 'file':
case 'hidden':
case 'submit':
case 'button':
case 'reset':
case 'textarea':
case 'select-multiple':
iFieldObj.val(iValue);
//alert($(tmpObj).fieldValue());
break;
case 'checkbox':
if (!iFieldObj.attr('checked')) {
iFieldObj.trigger('click');
} else {
//iFieldObj.attr('checked', false);
}
break;
case 'select-one':
iFieldObj.val(iValue);
break;
case 'radio':
$("input[name=" + iFieldObj.attr('id') + "]").each(function() {
if ($(this).val() == iValue) {
$(this).attr('checked', 'checked');
}
});
break;
default:
if ((document.getElementById(iFieldObj.attr('id')).type == 'select-one') || (document.getElementById(iFieldObj.attr('id')).type == 'select-multiple')) {
iFieldObj.val(iValue);
} else if (iFieldObj.attr('id')) {
iFieldObj.html(iValue);
}
break;
}
}
/*
Add the error classes to the specified field
*/
function setFormError(iErrorName) {
if (iErrorName.indexOf(']') > 0) {
var tmpData = iErrorName.split('[');
var tmpIndex = 0;
for (i = 1; i < tmpData.length; i ++) {
tmpData[i] = tmpData[i].replace(']', '');
//if ((tmpData[i] * 1) == 0) { tmpData[i] = 1; }
tmpIndex = tmpIndex + (tmpData[i] * 1);
}
//alert(tmpData[0] + '\n' + tmpIndex);
$('[id*=' + tmpData[0] + ']:input').eq(tmpIndex).addClass('errorElem');
$('[id*=' + tmpData[0] + '_label]').eq(tmpIndex).addClass('errorCell');
} else {
$('#' + iErrorName).addClass('errorElem');
//$("[name=" + iErrorName + "]").addClass('errorElem');
$('#' + iErrorName + '_label').addClass('errorCell');
}
if ($('#updateMsgDescription').size() == 0) {
if (containerForm) {
$('#' + containerForm + ' #updateMsg').after('<div id="updateMsgDescription"></div>');
} else {
$('#updateMsg').after('<div id="updateMsgDescription"></div>');
}
}
/*
var tmpItem = replace($('#' + iErrorName + '_label').html(), ':', '');
tmpItem = Trim(tmpItem.replace(/<\/?(?!\!)[^>]*>/gi, ''));
if (tmpItem != '') {
$('#updateMsgDescription').html($('#updateMsgDescription').html() + '<br>• ' + tmpItem);
}
*/
}
/*
Clean all error elements in the specified form
*/
function clearFormErrors(iFormObj) {
$('.errorElem').removeClass('errorElem');
$('.errorCell').removeClass('errorCell');
}
/*
The error element has been focused so clear any error objects
*/
function cleanFormError(iErrorObj) {
/*
var tmpName = iErrorObj.id || iErrorObj.name || iErrorObj.attr('id') || iErrorObj.attr('name');
if (tmpName) {
$('#' + tmpName).removeClass('errorElem');
//$("[name=" + tmpName + "]").removeClass('errorElem');
$('#' + tmpName + '_label').removeClass('errorCell');
}
*/
$(iErrorObj).removeClass('errorElem');
$(iErrorObj).parent().parent().find('#' + $(iErrorObj).attr('id') + '_label').removeClass('errorCell');
}
/*
Disable a form button, and set updating display label
*/
function doFormSubmit(iDisplay, iForm, iDisabledBtn) {
if (iDisabledBtn == null) {
iDisabledBtn = true;
}
var tmpName = iForm.name || iForm.id || iForm.attr('id');
containerForm = tmpName;
// Clear all form errors
clearFormErrors(iForm);
var tmpType = $(iForm).attr("enctype");
if (tmpType == 'multipart/form-data') {
//alert('file upload');
} else {
if (iDisabledBtn) {
$('#' + tmpName + ' #updateBtn').attr('disabled', true);
}
}
$('#updateMsgDescription').remove();
//$('#' + tmpName + ' #updateBtn').attr('disabled', true);
iDisplay = replace(iDisplay, '...', '<img src=\'images/progress_dots.gif\'>');
$('#' + tmpName + ' #updateMsg').html('<span class="btext12">' + iDisplay + '</span><br><br>');
}
/*
Show a data form for the specified form
*/
function showDataForm(iID, iFormName, iFileName) {
var Now = new Date();
var Start = Now.getTime()
// Remove all existing update forms
//$('[id*=update_]').html('');
//$('[id*=image_]').attr('src', '/images/plus_box.gif');
toggleLinks('update_' + iID, 'image_' + iID);
if (($('#image_' + iID).attr('src')).indexOf('minus') == -1) {
return false;
}
$('#update_' + iID).html('<br><center><b>Loading data...</b></center><br>');
var tmpAddress = window.location.href;
if (tmpAddress.indexOf('?') > 0) {
var tmpDat = tmpAddress.split('?');
tmpAddress = tmpDat[0];
}
templateForm = $('#' + iFormName);
desinationForm = $('#update_' + iID);
if (iFileName == null) {
submitAJAX(tmpAddress + 'add_new.php?action=XML_GET', 1);
//alert(tmpAddress + 'add_new.php?action=XML_GET', { 0: iID });
} else {
submitAJAX(iFileName, {0: iID});
}
var Now = new Date();
//alert((Now.getTime() - Start));
//setTimeout('alert($(\'#update_1 #user_id\').fieldValue());', 2000);
}
I am having issues with other functions using this. What happens when running it is Finding Password... is displayed but it sits there.
Thanks for taking a look,
Doug

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