How can i send javascript variable values into php - javascript

How can i send javascript variable values into php. i have used ajax for this but its nt working for me. please help, i am new in javascript and ajax. Here is my ajax & javascript code.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.8/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css" type="text/css" />
<script type="text/javascript">
$(function ()
{
$("#slider-range").slider(
{
range: true,
min: 71,
max: 109,
values: [75, 100],
slide: function (event, ui)
{
$("#size-range").html(Math.floor(ui.values[0] / 12) + "'" + (ui.values[0] % 12) + '" - ' + Math.floor(ui.values[1] / 12) + "'" + (ui.values[1] % 12) + '"');
$("#min_inches").val(ui.values[0]);
$("#max_inches").val(ui.values[1]);
}
});
$("#size-range").html(Math.floor($("#slider-range").slider("values", 0) / 12) + "'" + ($("#slider-range").slider("values", 0) % 12) + '" - ' + Math.floor($("#slider-range").slider("values", 1) / 12) + "'" + ($("#slider-range").slider("values", 1) % 12) + '"');
var a = $("#min_inches").val($("#slider-range").slider("values", 0));
var b = $("#max_inches").val($("#slider-range").slider("values", 1));
$.ajax(
{
type: "POST",
url: "searchrange.php",
data:
{
a: a,
b: b
},
success: function (option)
{
alert("voted");
}
});
});
</script>
And Below is my php code(searchrange.php).
<?php
if(isset($_POST['a']) && $_POST['a'] != '')
{
$kws = $_POST['a'];
$kws1=$_POST['b'];
echo $kws;
echo $query = "select * from newusers where Age between '".$kws."' and '".$kws1."'" ;
$res = mysql_query($query);
$count = mysql_num_rows($res);
$i = 0;
if($count > 0)
{
echo "<ul>";
while($row = mysql_fetch_array($res))
{
echo "<a href='#'><li>";
echo "<div id='rest'>";?>
<?php echo $row['Religion'];?><br><?php echo $row['Name'];?>
<?php echo $row[0];
echo "<br />";
echo "<br />";
echo "<div style='clear:both;'></div></li></a>";
$i++;
if($i == 5) break;
}
echo "</ul>";
if($count > 5)
{
echo "<div id='view_more'><a href='#'>View more results</a></div>";
}
}
else
{
echo "<div id='no_result'>No result found !</div>";
}
}
?>
Any help would be appreciated. thank you

Try this code :
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Slider - Range slider</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
$( "#slider-range" ).slider({
range: true,
min: 0,
max: 500,
values: [ 75, 300 ],
slide: function( event, ui ) {
$( "#amount" ).val( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] );
},
change: function(event, ui) {
// when the user change the slider
},
stop: function(event, ui) {
// when the user stopped changing the slider
$.ajax(
{
type: "POST",
url: "searchrange.php",
data:
{"min" :ui.values[0],"max":ui.values[1]},
success: function (option)
{
alert("voted");
}
});
}
});
$( "#amount" ).val( "$" + $( "#slider-range" ).slider( "values", 0 ) +
" - $" + $( "#slider-range" ).slider( "values", 1 ) );
});
</script>
</head>
<body>
<p>
<label for="amount">Price range:</label>
<input type="text" id="amount" style="border:0; color:#f6931f; font-weight:bold;">
</p>
<div id="slider-range"></div>
</body>
</html>
And your search page will be like this :
if(isset($_POST['min']) && $_POST['min'] != '')
{
$kws = $_POST['min'];
$kws1=$_POST['max'];
echo $kws;
echo $query = "select * from newusers where Age between '".$kws."' and '".$kws1."'" ;
$res = mysql_query($query);
$count = mysql_num_rows($res);
$i = 0;
if($count > 0)
{
echo "<ul>";
while($row = mysql_fetch_array($res))
{
echo "<a href='#'><li>";
echo "<div id='rest'>";?>
<?php echo $row['Religion'];?><br><?php echo $row['Name'];?>
<?php echo $row[0];
echo "<br />";
echo "<br />";
echo "<div style='clear:both;'></div></li></a>";
$i++;
if($i == 5) break;
}
echo "</ul>";
if($count > 5)
{
echo "<div id='view_more'><a href='#'>View more results</a></div>";
}
}
else
{
echo "<div id='no_result'>No result found !</div>";
}
}

Try this. Let the ajax call be done inside a call back.
$(function (){
$("#slider-range").slider({
range: true,
min: 71,
max: 109,
values: [75, 100],
slide: function (event, ui)
{
$("#size-range").html(Math.floor(ui.values[0] / 12) + "'" + (ui.values[0] % 12) + '" - ' + Math.floor(ui.values[1] / 12) + "'" + (ui.values[1] % 12) + '"');
$("#min_inches").val(ui.values[0]);
$("#max_inches").val(ui.values[1]);
var a = $("#min_inches").val($("#slider-range").slider("values", 0));
var b = $("#max_inches").val($("#slider-range").slider("values", 1));
$.ajax({
type: "POST",
url: "searchrange.php",
data:
{
a: a,
b: b
},
success: function (option)
{
alert("voted");
}
});
}
});
$("#size-range").html(Math.floor($("#slider-range").slider("values", 0) / 12) + "'" + ($("#slider-range").slider("values", 0) % 12) + '" - ' + Math.floor($("#slider-range").slider("values", 1) / 12) + "'" + ($("#slider-range").slider("values", 1) % 12) + '"');
});

I think your problem is that your $.ajax({...}) is being called too early - ie. on document ready $(function (){ ... $.ajax({...}) });, and not after your sliders are changed/selected. You could call your $.ajax({...}) on a button click -
<input id="vote" type="button" value="Vote" />
$("#vote").on('click',function(){
var a= $("#min_inches").val();
var b=$("#max_inches").val();
$.ajax ({
type: "POST",
url: "searchrange.php",
data: { a : a,
b : b },
success: function(option)
{
alert("voted");
}
});
});
so your code could be -
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.8/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css" type="text/css" />
<script type="text/javascript">
$(function ()
{
$("#slider-range").slider(
{
range: true,
min: 71,
max: 109,
values: [75, 100],
slide: function (event, ui)
{
$("#size-range").html(Math.floor(ui.values[0] / 12) + "'" + (ui.values[0] % 12) + '" - ' + Math.floor(ui.values[1] / 12) + "'" + (ui.values[1] % 12) + '"');
$("#min_inches").val(ui.values[0]);
$("#max_inches").val(ui.values[1]);
}
});
$("#size-range").html(Math.floor($("#slider-range").slider("values", 0) / 12) + "'" + ($("#slider-range").slider("values", 0) % 12) + '" - ' + Math.floor($("#slider-range").slider("values", 1) / 12) + "'" + ($("#slider-range").slider("values", 1) % 12) + '"');
$("#min_inches").val($("#slider-range").slider("values", 0));
$("#max_inches").val($("#slider-range").slider("values", 1));
$("#vote").on('click',function(){
var a= $("#min_inches").val();
var b=$("#max_inches").val();
$.ajax({
type: "POST",
url: "searchrange.php",
data:
{
a: a,
b: b
},
success: function (option)
{
alert("voted");
}
});
});
});
</script>
see this JSFiddle example (using alert in place of $.ajax()) -http://jsfiddle.net/8JgW6/

HI,
You can try this.In this example you can see how I have made a call to ajax
function callService(val1,val2){
alert("call service here "+val1);
$.ajax({
type: "POST",
url: "searchrange.php",
data:
{
a: val1,
b: val2
},
success: function (option)
{
alert("voted");
}
});
}
$sliderValue="";
$(function() {
$( "#slider-range" ).slider({
range: true,
min: 0,
max: 500,
values: [ 75, 300 ],
slide: function( event, ui ) {
},
stop: function(event, ui) {
$( "#amount" ).val( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] );
b = 0;
$sliderValue=ui.value;
console.log($sliderValue)
callService($sliderValue,b);
}
});
http://jsfiddle.net/kapilgopinath/c4XA5/

Related

AJAX is not passing data via POST to its intended URL

I want to pass an array through AJAX but I am not getting any feed back on what it is I am sending. I tried to do a var_dump($_POST); on the PHP side (next.php) but nothing is showing up. I'm guessing there is something wrong with my code.
function sendToServer(data) {
$.ajax({
type: "POST",
data: { arr: JSON.stringify(data) },
url: "next.php",
success: function() {}
});
}
next.php:
<?php
var_dump($_POST);
$data = json_decode(stripslashes($_POST['arr']));
foreach ($data as $item) {
echo $item;
// insert to db
}
?>
Full snippet of my code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
<!-- #main {
max-width: 800px;
margin: 0 auto;
}
-->
</style>
</head>
<body>
<div id="main">
<h1>Add or Remove text boxes with jQuery</h1>
<div class="my-form">
<!-- <form action="next.php" method="post">-->
<button onclick="addAuthor()">Add Author</button>
<br>
<br>
<div id="addAuth"></div>
<br>
<br>
<button onclick="submit()">Submit</button>
<!-- </form>-->
</div>
<div id="result"></div>
</div>
<script type="text/javascript">
var authors = 0;
function addAuthor() {
authors++;
var str = '<br/>' + '<div id="auth' + authors + '">' + '<input type="text" name="author" id="author' + authors + '" placeholder="Author Name:"/>' + '<br/>' + '<button onclick="addMore(\'auth' + authors + '\')" >Add Book</button>' + '</div>';
$("#addAuth").append(str);
}
var count = 0;
function addMore(id) {
count++;
var str =
'<div id="bookDiv' + count + '">' + '<input class="' + id + '" type="text" name="book' + id + '" placeholder="Book Name"/>' + '<span onclick="removeDiv(\'bookDiv' + count + '\')">Remove</span>' + '</div>';
$("#" + id).append(str);
}
function removeDiv(id) {
$("#" + id).slideUp(function() {
$("#" + id).remove();
});
}
function submit() {
var arr = [];
for (i = 1; i <= authors; i++) {
var obj = {};
obj.name = $("#author" + i).val();
obj.books = [];
$(".auth" + i).each(function() {
var data = $(this).val();
obj.books.push(data);
});
arr.push(obj);
}
sendToServer(arr);
//$("#result").html(JSON.stringify(arr));
}
function sendToServer(data) {
$.ajax({
type: "POST",
data: {
arr: JSON.stringify(data)
},
url: "next.php",
success: function() {
}
});
}
</script>
</body>
</html>
The problem is when you try to echo the item. As $item is an object (stdClass), and the echo command expects a string, the echo command fails with "stdClass could not be converted to a string". You can either change to:
echo print_r($item, true);
or:
var_dump($item);

Getting a JavaScript issue due to a 500 server error [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
In open cart I have a custom module - with ajax filter - when trying to use the filter i'm getting following errors.
<script type="text/javascript">
$("#btnForm").fancybox({
width: 1000,
height: 1050,
autoSize : false,
fitToView : false,
closeBtn : false,
maxWidth : '100%'
});
$(function() {
$( "#slider-range" ).slider({
range: true,
min: 0,
max: <?php echo $max_price ?>,
values: [ <?php echo $start_price ?>, <?php echo $end_price ?> ],
slide: function( event, ui ) {
$( "#amount" ).val( "<?php echo $curr ?>" + ui.values[ 0 ] + " - <?php echo $curr ? >" + ui.values[ 1 ] );
$("#results").html('<img src="catalog/view/theme/pollishop2/image/ajax-loader.gif" />');
$("#pagination").html('');
clearTimeout(wto);
wto = setTimeout(function() {
filter();
}, 100);
}
});
$( "#amount" ).val( "<?php echo $curr ?>" + $( "#slider-range" ).slider( "values", 0 ) + " - <?php echo $curr ?>" + $( "#slider-range" ).slider( "values", 1 ) );
});
var wto;
$(".checkish").change(function() {
$("#results").html('<img src="catalog/view/theme/pollishop2/image/ajax-loader.gif" />');
$("#pagination").html('');
clearTimeout(wto);
wto = setTimeout(function() {
filter();
}, 100);
});
$("input[type='text']").change(function() {
$("#results").html('<img src="catalog/view/theme/pollishop2/image/ajax-loader.gif" />');
$("#pagination").html('');
filter();
});
function mrvidaloca(filter, page) {
$.ajax({
url: 'index.php?route=information/jewels/xml' + filter,
dataType: 'json',
success: function(json) {
all_jewels = json.all_jewels;
pagination = json.pagination;
doolittle = '';
$.each( all_jewels, function( key, value ) {
doolittle += '<div style="text-align:left;padding-bottom:10px;margin- right:1px;">';
doolittle += '<div class="image"><img src="' + value.image + '" /></div>';
doolittle += '<div class="name"><a style="font-size:16px;" href="' + value.view + '">' + value.title + '</a></div>';
doolittle += '<div class="description" style="display:block;">' + value.description + '</div>';
doolittle += '<div class="rating" style="right:10px;position:absolute;z-index:3;top:0;"><img src="catalog/view/theme/pollishop2/image/stars-' + value.rating + '.png" /></div>';
doolittle += '</div>';
});
if(doolittle){
$("#results").html(doolittle);
$("#pagination").html(pagination);
} else {
$("#results").html('<?php echo $no_results ?>');
$("#pagination").html('');
}
}
});
}
function filter(page) {
url = '';
var filter_named = $('#mans').find('input[name="searchjewellery"]').val();
if (filter_named) {
url += '&term=' + filter_named;
}
var filter_name = $('input[name=\'price\']').attr('value');
if (filter_name) {
filter_name = filter_name.replace(/<?php echo $curr ?>/g, '');
filter_name = filter_name.split(' ').join('');
filter_name = filter_name.split('-');
url += '&start_price=' + filter_name[0] + '&end_price=' + filter_name[1];
}
var filter_cat = $('input[name=\'cat\']').attr('value');
if (filter_cat) {
url += '&jewels_category_id=' + filter_cat;
}
var vali = [];
$('#god :checkbox:checked').each(function(i){
vali[i] = $(this).val();
});
lashes = vali.join(',');
if(lashes) {
url += '&difficulty=' + lashes;
}
var valio = [];
$('#bios :checkbox:checked').each(function(i){
valio[i] = $(this).val();
});
helium = valio.join(',');
if(helium) {
url += '&designer_id=' + helium;
}
if(page){
url += '&page=' + page;
} else {
url += '&page=1';
}
mrvidaloca(url,page);
}
</script>
Console shows:
GET http://test.risetea.co.uk/index.php?route=information/jewels/xml&start_price=$0&end_price=$500&jewels_category_id=5&difficulty=1&pa ge=1 500 (Internal Server Error)
jquery-1.8.3.min.js?j2v=2.3.3:2 v.support.ajax.v.ajaxTransport.send
jquery-1.8.3.min.js?j2v=2.3.3:2 v.extend.ajax
index.php?route=information/jewels&jewels_category_id=5:989 mrvidaloca
index.php?route=information/jewels&jewels_category_id=5:1054 filter
index.php?route=information/jewels&jewels_category_id=5:980 (anonymous function)`
It is not Javascript error. It is 500 (Internal Server Error) which means that you have problems on your server side.

Trouble with Flot for Wordpress Tooltip plugin

I'm trying to enable tooltips for Flot for Wordpress and am having problems with it when I add in a certain function and I need this to work from what I've tried to decipher onnline.
I downloaded the latest version of tooltips for flot charts and loaded the script when the plugin is loaded.
The chart I have create loads perfect when the following js code is not in the code or when the function is empty like below too.
Can anyone tell me what's wrong with the code that is stopping my chart appearing?
Cheers in advance, Alan.
This is code I believe I need to make the tooltips work
function showTooltip(x, y, contents) {
    $("<div id="tooltip">" + contents + "</div>").css({
        position: "absolute",
        display: "none",
        top: y + 5,
        left: x + 20,
        border: "2px solid #4572A7",
        padding: "2px",    
        size: "10",  
        "background-color": "#fff",
        opacity: 0.80
    }).appendTo("body").fadeIn(200);
}
This is what works when I remove the inside of the code
function showTooltip(x, y, contents) {
        position: "absolute"
}
Here full code below:
echo ' <script language="javascript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script language="javascript" type="text/javascript" src="' . plugins_url( $path ) . '/flot-for-wp/flot/jquery.flot.js"></script>
<script language="javascript" type="text/javascript" src="' . plugins_url( $path ) . '/flot-for-wp/flot/jquery.flot.resize.js"></script>
<script language="javascript" type="text/javascript" src="' . plugins_url( $path ) . '/flot-for-wp/flot/excanvas.min.js"></script>
<link href="' . plugins_url( $path ) . '/flot-for-wp/flot/layout.css" rel="stylesheet" type="text/css">
<div id="placeholder" style="width:95%; height:85%; max-width:100%; margin:auto;"></div>
';
echo '
<script language="javascript" type="text/javascript" id="source">
var lie_results = [ ';
foreach($chartdata as $row){
echo '[' .$row['mentalerrors_date'] . ',' .$row['mentalerrors_lie'] . '],';
}
echo ' ];
var options_results = [ ';
foreach($chartdata as $row){
echo '[' .$row['mentalerrors_date'] . ',' .$row['mentalerrors_options'] . '],';
}
echo ' ];
var context_results = [ ';
foreach($chartdata as $row){
echo '[' .$row['mentalerrors_date'] . ',' .$row['mentalerrors_context'] . '],';
}
echo ' ];
var decide_results = [ ';
foreach($chartdata as $row){
echo '[' .$row['mentalerrors_date'] . ',' .$row['mentalerrors_decide'] . '],';
}
echo ' ];
var dataset = [
{
label: "Lie",
data: lie_results
}, {
label: "Context",
data: context_results
}, {
label: "Options",
data: options_results
},{
label: "Decide",
data: decide_results
}
];
var options = {
xaxis: { mode: "time", tickSize: [2, "month"] },
yaxes: [{ min: ' .$min_count . ', max: ' .$max_count . ' },{},{},{}],
points: { show: true, symbol: "circle", fill: true },
lines: { show: true, },
legend: { noColumns: 0, labelFormatter: function (label, series) { return "<font color=\"white\">" + label + "</font>";}, backgroundColor: "#000", backgroundOpacity: 0.9, labelBoxBorderColor: "#000000", position: "nw"},
grid: { hoverable: true, mouseActiveRadius: 8 }
};
jQuery(document).ready(function($){
var placeholder = $("#placeholder");
var plot = $.plot(placeholder,dataset,options);
$("#placeholder").UseTooltip();
}
);
var previousPoint = null;
$.fn.UseTooltip = function () {
$(this).bind("plothover", function (event, pos, item) {
if (item) {
if (previousPoint != item.dataIndex) {
previousPoint = item.dataIndex;
$("#tooltip").remove();
var x = item.datapoint[0];
var y = item.datapoint[1];
console.log(x+","+y)
showTooltip(item.pageX, item.pageY,
x + "<br>" + "<strong>" + y + "</strong> (" + item.series.label + ")");
}
}
else {
$("#tooltip").remove();
previousPoint = null;
}
});
};
function showTooltip(x, y, contents) {
$("<div id=\'tooltip\'>" + contents + "</div>").css({
position: "absolute",
display: "none",
top: y + 5,
left: x + 20,
border: "2px solid #4572A7",
padding: "2px",
size: "8",
opacity: 0.85,
background: "#4572A7",
}).appendTo("body").fadeIn(200);
};
</script></div>';
When using javascript, get in the habit of checking the debugger console for errors. This is invalid javascript:
$("<div id="tooltip">" + contents + "</div>")
It produces:
SyntaxError: Unexpected identifier
Why? Because it's not properly quoted.
Try:
"<div id=\"tooltip\">" + contents + "</div>"
The quotes around tooltip are escaped.

Ajax form only working after first refresh

I've a form that is sent via AJAX, but AJAX only works after first refresh (F5).
The first time I open the html I send the form and I've to do a page refresh otherwise data it is not submited. After this first refresh, AJAX is working perfectly and always reflect new data on success.
The data that I append after submits the form: ( $("#fldIdLetraN") and $("#fldLetraN") ), I've to call it via $_REQUEST on php file, I think this can do some interference the first time form is sent because data isn't really insert in JSON file cause $_REQUEST is not setting correctly.
$("body").on("submit", "#frmPersonas", function(e) {
$("#fldIdLetraN").val(jQuery.inArray(RemoveAccents($("#fldNombre").val().substr(0, 1)), $aLetras));
$("#fldLetraN").val(RemoveAccents($("#fldNombre").val().substr(0, 1)));
var fd = new FormData($("#frmPersonas")[0]);
$.ajax({type: 'POST',
url: "procjson.php",
data: fd,
processData: false,
contentType: false,
success: function() {
CargarPagina($LetraAct, $IdLetraAct, $PagActual);
$("#form").css("display", "none");
$("#formbg").css("display", "none");
}
});
e.preventDefault();
});
The entire code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Agenda</title>
<script type="text/javascript" src="jquery-1.11.0.min.js"></script>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="formbg">
<div id="form"></div>
</div>
<div id="divAgenda">
<div id="divLetras"></div>
<div id="divEditar">
<div><img src="img/ops/add.png" alt="" /></div>
<div><img src="img/ops/update.png" alt="" /></div>
<div><img src="img/ops/delete.png" alt="" /></div>
</div>
<div id="divBusqueda">
<div><img src="img/ops/hojear.png" alt="" /></div>
<div><img src="img/ops/search.png" alt="" /></div>
</div>
<div id="divPersonas"></div>
<div id="divPaginas"></div>
<div id="divDesplazar">
<div><img src="img/move/first.png" alt="" /></div>
<div><img src="img/move/previous.png" alt="" /></div>
<div><img src="img/move/next.png" alt="" /></div>
<div><img src="img/move/last.png" alt="" /></div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function() {
$aLetras = new Array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
"k", "l", "m", "n", "ñ", "o", "p", "q", "r", "s", "t", "u", "v",
"w", "x", "y", "z");
for (var i = 0; i < $aLetras.length; i++) {
$("#divLetras").append("<a href='#" + $aLetras[i] + "' id='" + $aLetras[i] + "-" + i + "'\n\
class='tab-letra'>" + $aLetras[i].toUpperCase() + "</a>");
}
$PagActual = 0;
CargarPagina("a", 0, 0);
});
function CargarPagina(letra, id_letra, pag_actual, hojear) {
$.getJSON("datos.json", function(datos) {
$("#divPersonas").empty();
$("#divPersonas").append("<ul id='col1'></ul><ul id='col2'></ul>");
var res_pagina = 6;
for (var i = pag_actual * res_pagina; i < pag_actual * res_pagina + res_pagina; i++) {
if (datos.personas[id_letra][letra][i] === undefined) {
break;
}
var html = "<div id='per" + datos.personas[id_letra][letra][i].id + "'>";
html += "<div><img src='img/photo/" + datos.personas[id_letra][letra][i].foto + "' /></div>";
html += "<div><span>Nombre: </span><span id='nom" + datos.personas[id_letra][letra][i].id + "'>";
html += datos.personas[id_letra][letra][i].nombre + "</span><br />";
html += "<span>Apellidos: </span><span id='ape" + datos.personas[id_letra][letra][i].id + "'>";
html += datos.personas[id_letra][letra][i].apellidos + "</span><br />";
html += "<span>Edad: </span><span id='eda" + datos.personas[id_letra][letra][i].id + "'>";
html += datos.personas[id_letra][letra][i].edad + "</span><br />";
html += "<span>Teléfono: </span><span id='tel" + datos.personas[id_letra][letra][i].id + "'>";
html += datos.personas[id_letra][letra][i].telefono + "</span><br /></div></div>";
if (i >= pag_actual * res_pagina && i < pag_actual * res_pagina + res_pagina - 3) {
$("#col1").append(html);
} else {
$("#col2").append(html);
}
}
$LetraAct = letra;
$IdLetraAct = id_letra;
if (datos.personas[id_letra][letra].length % res_pagina === 0) {
$TotalPag = datos.personas[id_letra][letra].length / res_pagina - 1;
} else {
$TotalPag = Math.floor(datos.personas[id_letra][letra].length / res_pagina);
}
$("#divPaginas").empty();
for (var i = 0; i <= $TotalPag; i++) {
$("#divPaginas").append("<a href='#" + $LetraAct + ",p" + (i + 1) + "' id='pag" + i + "'>" + (i + 1) + "</a>");
}
if($TotalPag === -1) {
$("#divPersonas").html("<div id='noRes'>No se ha encontrado ningún resultado.</div>");
}
if (hojear) {
Hojear(true);
}
});
}
function GreyBox() {
$("#form").fadeIn("fast", function() {
$("#form").css("display", "block");
});
$("#formbg").fadeIn("fast", function() {
$("#form").css("display", "block");
});
}
function AbrirFormulario(crud, id_persona) {
$("#form").html("<div id='frmOp'></div>\n\
<form id='frmPersonas' name='frmPersonas'>\n\
<label for='fldNombre'>Nombre:</label>\n\
<input type='text' id='fldNombre' name='fldNombre' autocomplete='off' />\n\
<label for='fldApellidos'>Apellidos:</label>\n\
<input type='text' id='fldApellidos' name='fldApellidos' autocomplete='off' />\n\
<label for='fldEdad'>Edad:</label>\n\
<input type='text' id='fldEdad' name='fldEdad' autocomplete='off' />\n\
<label for='fldTlf'>Teléfono:</label>\n\
<input type='text' id='fldTlf' name='fldTlf' autocomplete='off' />\n\
<input type='hidden' id='fldIdLetraN' name='fldIdLetraN' />\n\
<input type='hidden' id='fldLetraN' name='fldLetraN' />\n\
<input type='hidden' id='crud' name='crud' value='" + crud + "' />\n\
<input type='submit' id='btnEnviar' value='Enviar' /></form>\n\
<div id='frmAlert'></div>");
if (crud === "C") {
$("#frmOp").html("Agregar contacto");
}
if (crud === "U") {
$("#frmOp").html("Modificar contacto");
$("#fldNombre").val($("#nom" + id_persona).html());
$("#frmPersonas").append("<input type='hidden' id='fldLetraAct' name='fldLetraAct' \n\
value='" + RemoveAccents($("#fldNombre").val().substr(0, 1)) + "' />");
$("#frmPersonas").append("<input type='hidden' id='fldIdLetraAct' name='fldIdLetraAct' \n\
value='" + jQuery.inArray(RemoveAccents($("#fldNombre").val().substr(0, 1)), $aLetras) + "' />");
$("#fldApellidos").val($("#ape" + id_persona).html());
$("#fldEdad").val($("#eda" + id_persona).html());
$("#fldTlf").val($("#tel" + id_persona).html());
$("#frmPersonas").append("<input type='hidden' id='fldIdPersona' name='fldIdPersona' value='" + id_persona + "' />");
}
}
function RemoveAccents(strAccents) {
var strAccents = strAccents.split('');
var strAccentsOut = new Array();
var strAccentsLen = strAccents.length;
var accents = 'ÁABCDÉEFGHÍIJKLMNÑÓOPQRSTÚUVWXYZ';
var accentsOut = "aabcdeefghiijklmnñoopqrstuuvwxyz";
for (var y = 0; y < strAccentsLen; y++) {
if (accents.indexOf(strAccents[y]) !== -1) {
strAccentsOut[y] = accentsOut.substr(accents.indexOf(strAccents[y]), 1);
} else
strAccentsOut[y] = strAccents[y];
}
strAccentsOut = strAccentsOut.join('');
return strAccentsOut;
}
function Hojear(active) {
if (active) {
if ($TotalPag === -1) {
$TotalPag = 0;
}
if ($PagActual === $TotalPag) {
if ($IdLetraAct + 1 === $aLetras.length) {
$IdLetraAct = 0;
$LetraAct = $aLetras[$IdLetraAct];
$PagActual = 0;
} else {
$IdLetraAct++;
$LetraAct = $aLetras[$IdLetraAct];
$PagActual = 0;
}
} else {
$PagActual++;
}
$DelayHojear = setTimeout(function() {
CargarPagina($LetraAct, $IdLetraAct, $PagActual, true);
}, 1000);
} else {
clearTimeout($DelayHojear);
}
}
$("body").on("click", "#divLetras a", function() {
var letra = $(this).attr("id").substr(0, 1);
var id_letra = $(this).attr("id").substr($(this).attr("id").search(/\d/));
$PagActual = 0;
CargarPagina(letra, id_letra, $PagActual);
});
$("#divDesplazar a").click(function() {
var acc = $(this).attr("id");
if (acc === "first") {
$PagActual = 0;
}
if (acc === "prev" && $PagActual > 0) {
$PagActual--;
}
if (acc === "next" && $PagActual < $TotalPag) {
$PagActual++;
}
if (acc === "last") {
$PagActual = $TotalPag;
}
CargarPagina($LetraAct, $IdLetraAct, $PagActual);
});
$("#divEditar a").click(function() {
var acc = $(this).attr("id");
if (acc === "update" || acc === "delete") {
if ($("[id*=per]").hasClass("selected")) {
var id_persona = $(".selected").attr("id").substr($(".selected").attr("id").search(/\d/));
if (acc === "update") {
GreyBox();
AbrirFormulario("U", id_persona);
}
if (acc === "delete") {
var crud = "D";
$.ajax({type: "POST",
url: "procjson.php",
data: {'crud': crud, 'id_persona': id_persona, 'letra_act': $LetraAct, 'id_letra': $IdLetraAct},
success: function() {
CargarPagina($LetraAct, $IdLetraAct, $PagActual);
}
});
}
} else {
console.log("no");
}
}
if (acc === "add") {
GreyBox();
AbrirFormulario("C", -1);
}
});
$("body").on("submit", "#frmPersonas", function(e) {
e.preventDefault();
$("#fldIdLetraN").val(jQuery.inArray(RemoveAccents($("#fldNombre").val().substr(0, 1)), $aLetras));
$("#fldLetraN").val(RemoveAccents($("#fldNombre").val().substr(0, 1)));
var fd = new FormData($("#frmPersonas")[0]);
$.ajax({type: 'POST',
url: "procjson.php",
cache: false,
data: fd,
processData: false,
contentType: false,
success: function() {
CargarPagina($LetraAct, $IdLetraAct, $PagActual);
$("#form").css("display", "none");
$("#formbg").css("display", "none");
}
});
return false;
});
$("body").on("click", "#divPersonas [id*=p]", function() {
$("#divPersonas [id*=per]").removeAttr("class");
var id_persona = $(this).attr("id").substr($(this).attr("id").search(/\d/));
$("#per" + id_persona).attr("class", "selected");
});
$("body").on("click", "#formbg", function() {
$("#form").css("display", "none");
$("#formbg").css("display", "none");
});
$("body").on("click", "#divPaginas a", function() {
var id_pagina = $(this).attr("id").substr($(this).attr("id").search(/\d/));
CargarPagina($LetraAct, $IdLetraAct, id_pagina);
});
$("#divBusqueda a").click(function() {
var Acc = $(this).attr("id");
if (Acc === "hojear") {
Hojear(true);
}
if (Acc === "search") {
}
});
$("body").on("mouseover", "[id*=per]", function() {
Hojear(false);
});
$("#form").click(function(e) {
e.stopPropagation();
});
$("a").click(function(e) {
return false;
e.preventDefault();
});
</script>
try disabling the cache:
$.ajax({type: 'POST',
url: "procjson.php",
cache: false
//the rest
});
Is this all of your javascript code used on this site? Because if yes, try to wrap your code like this:
$(document).ready(function() {
$("body").on("submit", "#frmPersonas", function(e) {
$("#fldIdLetraN").val(jQuery.inArray(RemoveAccents($("#fldNombre").val().substr(0, 1)), $aLetras));
$("#fldLetraN").val(RemoveAccents($("#fldNombre").val().substr(0, 1)));
var fd = new FormData($("#frmPersonas")[0]);
$.ajax({type: 'POST',
url: "procjson.php",
data: fd,
processData: false,
contentType: false,
success: function() {
CargarPagina($LetraAct, $IdLetraAct, $PagActual);
$("#form").css("display", "none");
$("#formbg").css("display", "none");
}
});
e.preventDefault();
});
});
Then jquery will wait before the DOM is ready before attaching the eventhandler etc., this could be an explanation why it's working on refresh (because of your browser cache dom could be ready faster then on your first load).

TypeError: $(".ajax-fc-container").captcha is not a function

I'm having problem with captcha (http://www.webdesignbeach.com/beachbar/ajax-fancy-captcha-jquery-plugin). I'm getting error like in the title. Anyboby know what's the problem?
The "obj" has "captxt and "array" field.
I'm including jquery-1.5.1.min.js and jquery-ui.min.js library
This is a sample from my JS code:
function loadlang(lang) {
var rand = $.ajax({ url: '/captcha/data.aspx', async: false }).responseText;
var obj = eval(rand)[0];
$(".red").removeClass('red');
$(function () {
$(".ajax-fc-container").captcha({
borderColor: "silver",
text: obj['captxt'],
items: obj['array']
});
});
$("#resend_password_link").html(obj['resend_password_link']);
$("#sectxt").html(obj['sectxt']);
$("#more").html(obj['more']);
$("#langtxt").html(obj['langtxt']);
$("#optionstxt").html(obj['optionstxt']);
$("#submit").val(obj['Login']);
$("#tab").hide();
$("#desc").html(obj['Text']);
$("#dialog").html(obj['Browser']);
}
$(document).ready(function () {
$.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());
//InitLang();
var lang = document.location.href.split('lang=')[1] || 'pl';
loadlang(lang);
$("#lang").remove();
$("#myForm").append("<input id=\"lang\" type=\"hidden\" style=\"display: none;\" name=\"lang\" value=\"" + lang + "\">");
$('.lang').click(function () {
$("#lang").remove();
$("#myForm").append("<input id=\"lang\" type=\"hidden\" style=\"display: none;\" name=\"lang\" value=\"" + $(this)[0].id + "\">");
loadlang($(this)[0].id);
});

Categories