I'm using this code (http://technologymantrablog.com/dynamic-combobox-ajax-php-mysql/) for getting country/state/city from my database to php/html selects. It's working perfect in registration form. Everything is fine! The problem is, after user register at the system, he can try to edit your registration/profile. Then, the select for country/state/city appears again. And there is the problem. If I use the same ID's from javascript it won't work. If I try to change the ID's and change the javascript, won't work too. Calling two functions and two different files, won't work too.
getSelects.php
function getStatus() {
if (window.XMLHttpRequest) {
xmlhttp3 = new XMLHttpRequest();
} else {
xmlhttp3 = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp3.onreadystatechange=function() {
if (xmlhttp3.readyState==4 && xmlhttp3.status==200) {
document.getElementById("inputStatus").innerHTML=xmlhttp3.responseText;
}
}
xmlhttp3.open("GET","includes/getStatus.php",true);
xmlhttp3.send();
}
function getMotivo(statusID) {
if (window.XMLHttpRequest) {
xmlhttp3 = new XMLHttpRequest();
} else {
xmlhttp3 = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp3.onreadystatechange=function() {
if (xmlhttp3.readyState==4 && xmlhttp3.status==200) {
document.getElementById("inputMotivo").innerHTML=xmlhttp3.responseText;
}
}
xmlhttp3.open("GET","includes/getMotivo.php?statusID="+statusID,true);
xmlhttp3.send();
}
function getComplemento(motivoID) {
if (window.XMLHttpRequest) {
xmlhttp3 = new XMLHttpRequest();
} else {
xmlhttp3 = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp3.onreadystatechange=function() {
if (xmlhttp3.readyState==4 && xmlhttp3.status==200) {
document.getElementById("inputComplemento").innerHTML=xmlhttp3.responseText;
}
}
xmlhttp3.open("GET","includes/getComplemento.php?motivoID="+motivoID,true);
xmlhttp3.send();
}
INCLUDES
Status:
echo '<select onchange="getMotivo(this.value);" class="form-control" name="status" id="status">';
echo
'<option value="">-- Selecione --</option>
<option value="0">Bloqueado</option>
<option value="1">Ativo</option>';
echo'</select>';
Motivo:
include("../lib/conexao.php");
$statusID = $_GET['statusID'];
echo '<select onchange="getComplemento(this.value);" class="form-control" name="motivo" id="motivo">';
echo '<option value="" selected>-- Selecione um Motivo --</option>';
$q = "SELECT * FROM motivo WHERE status = '$statusID' AND tipo = 'C' ORDER BY motivo";
if($res = $con->query($q))
{
while($obj = $res->fetch_object())
{
echo'<option value="'. $obj->motivoID .'">'. $obj->motivo .'</option>';
}
}
echo'</select>';
Complemento:
include("../lib/conexao.php");
$motivoID = $_GET['motivoID'];
if($motivoID == 2 || $motivoID == 4 || $motivoID == 5 || $motivoID == 6 || $motivoID == 8 || $motivoID == 9) {
echo '<label for="complemento">Complemento</label>';
echo '<input type="text" name="complemento" class="form-control" id="complemento" placeholder="Insira o Complemento">';
}
header.php:
<script>
function init() {
getStatus();
}
</script>
</head>
<body onload="init();">
I think if I post all the code files here will be very long post. But, with my text in the first paragraph I think I could explain what I'm trying to do.
I don't know if this will help solve your problem ( hope it does ) but I mentioned using a more or less generic ajax function and using that for the bulk of your work so this is what I meant.
function _ajax( url, options ){
var factories=[
function() { return new XMLHttpRequest(); },
function() { return new ActiveXObject('Msxml2.XMLHTTP'); },
function() { return new ActiveXObject('MSXML2.XMLHTTP.3.0'); },
function() { return new ActiveXObject('MSXML2.XMLHTTP.4.0'); },
function() { return new ActiveXObject('MSXML2.XMLHTTP.5.0'); },
function() { return new ActiveXObject('MSXML2.XMLHTTP.6.0'); },
function() { return new ActiveXObject('Microsoft.XMLHTTP'); }
];
/* Try each factory until we have a winner */
for( var i=0; i < factories.length; i++ ) {
try { var req = factories[ i ](); if( req!=null ) { break; } }
catch( err ) { continue; }
};
var method=options.hasOwnProperty('method') ? options.method.toUpperCase() : 'POST';
var callback=options.hasOwnProperty('callback') ? options.callback :false;
if( !callback ){
alert( 'No callback function assigned - a callback is required to handle the response data' );
return false;
}
var headers={
'Accept': "text/html, application/xml, application/json, text/javascript, "+"*"+"/"+"*"+"; charset=utf-8",
'Content-type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest'
};
/* The main parameters of the request */
var params=[];
if( options.hasOwnProperty('params') && typeof( options.params )=='object' ){
for( var n in options.params ) params.push( n + '=' + options.params[n] );
}
/* Additional arguments that can be passed to the callback function */
var args=options.hasOwnProperty('args') ? options.args : options;
/* Assign callback to handle response */
req.onreadystatechange=function(){
if( req.readyState==4 ) {
if( req.status==200 ) options.callback.call( this, req.response, args );
else console.warn( 'Error: '+req.status+' status code returned' );
}
}
/* Execute the request according to desired method: other methods could be added here */
switch( method ){
case 'POST':
req.open( method, url, true );
for( header in headers ) req.setRequestHeader( header, headers[ header ] );
req.send( params.join('&') );
break;
case 'GET':
req.open( method, url+'?'+params.join('&'), true );
for( header in headers ) req.setRequestHeader( header, headers[ header ] );
req.send( null );
break;
}
}
/*
example usage:
--------------
*/
function getStatus() {
_ajax.call( this, '/includes/getStatus.php',{ callback:cb_ajax, method:'get', args:{ id:'inputStatus' } } );
}
function getMotivo( statusID ) {
_ajax.call( this, '/includes/getMotivo.php',{ callback:cb_ajax, method:'get', params:{ 'statusID':statusID }, args:{ id:'inputMotivo' } } );
}
function getComplemento( motivoID ) {
_ajax.call( this, '/includes/getMotivo.php',{ callback:cb_ajax, method:'get', params:{ 'motivoID':motivoID }, args:{ id:'inputComplemento' } } );
}
/* The callback function */
function cb_ajax( r, o ){
console.info( 'ajax response: %s, args: %s', r, o );
if( o.hasOwnProperty( 'id' ) && document.getElementById( o.id ) ) document.getElementById( o.id ).innerHTML=r;
}
html form
---------
<form name='so_test_motivo' method='post' action='/test/target.php' enctype="multipart/form-data">
<select name='country' onchange='getStatus()'>
<option value=0 selected> Choose an option
<option value=1> Test
</select>
<select id='inputStatus' name='inputStatus' onchange='getMotivo(this.value)'>
</select>
<select id='inputMotivo' name='inputMotivo' onchange='getComplemento(this.value)'>
</select>
<select id='inputComplemento' name='inputComplemento'>
</select>
</form>
And for the purposes of the test, the php script /test/target.php was simply sending dummy data back like this:
$id=$_GET['id'];
for( $i=0; $i < 50; $i++ ) echo '<option value='.( ( $i+1 ) + $id ).'>Option - '.( ( $i+1 ) + $id ).PHP_EOL;
Related
Problem with duplicated posts..
The problem of duplicated posts accures when somebody scroll fast or just press END key.
If scroll is fast, or even scrolled to the end of the page, there are always duplicates of some posts.
I am using ajax fn from this thread: https://stackoverflow.com/a/18078705
this is my JS:
var canBeLoaded = true;
var ajax = {};
ajax.x = function () {
if (typeof XMLHttpRequest !== 'undefined') {
return new XMLHttpRequest();
}
var versions = [
"MSXML2.XmlHttp.6.0",
"MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"
];
var xhr;
for (var i = 0; i < versions.length; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
} catch (e) {
}
}
return xhr;
};
ajax.send = function (url, callback, method, data, async) {
if (async === undefined) {
async = true;
}
var x = ajax.x();
x.open(method, url, async);
x.onreadystatechange = function () {
if (x.readyState == 4) {
if ( x.status >= 200 && x.status < 400 ) {
callback(x.responseText);
} else {
console.log('Request failed. Returned status of ' + x.status);
}
}
};
if (method == 'POST') {
x.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
x.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
}
x.send(data);
};
ajax.post = function (url, data, callback, async) {
var query = [];
for (var key in data) {
query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
}
ajax.send(url, callback, 'POST', query.join('&'), async)
};
var load_ajax_posts = function(postPerPage, bottomOffset, postsOffset) {
if( document.querySelector('.car') == null ){
return;
}
var loader = document.getElementById('more_posts');
var model = document.getElementById('modelSelect').value;
var supportPageOffset = window.pageXOffset !== undefined;
var isCSS1Compat = ((document.compatMode || "") === "CSS1Compat");
var scrollTop = supportPageOffset ? window.pageYOffset : isCSS1Compat ? document.documentElement.scrollTop : document.body.scrollTop;
var callback = function(response) {
if (response.length) {
if ( canBeLoaded ) {
loader.innerHTML = 'Ładowanie...';
document.querySelector('.cars-list').insertAdjacentHTML('beforeend', response);
canBeLoaded = false;
loader.classList.add('post_loading_loader');
response = null;
}
} else {
loader.classList.remove('post_loading_loader');
loader.classList.add('post_no_more_posts');
loader.innerHTML = 'Nie znaleziono więcej wpisów';
canBeLoaded = false;
}
}
function init() {
if( scrollTop > bottomOffset ){
canBeLoaded = true;
loader.classList.remove('post_loading_loader');
loader.innerHTML = 'Wczytaj więcej';
}
if ( !canBeLoaded ) return;
if ( (!loader.classList.contains('post_loading_loader') || !loader.classList.contains('post_no_more_posts')) ) {
if( scrollTop > bottomOffset && canBeLoaded === true ){
var data = {
ppp: postPerPage,
offset: postsOffset,
action: 'loadposts',
};
ajax.post( jsVars.ajax_url, data, callback );
postsOffset += postPerPage;
}
}
return false;
}
return {
init,
};
}
function offsetTop(el) {
var rect = el.getBoundingClientRect(),
scrollTop = window.pageYOffset || document.documentElement.scrollTop;
return rect.top + scrollTop
}
ready( function() {
var postPerPage = 3;
var bottomOffset;
var postsOffset;
window.addEventListener('scroll', function() {
postsOffset = document.querySelectorAll('.car').length;
bottomOffset = offsetTop(document.getElementById('more_posts')) - (window.innerHeight / 1.3);
load_ajax_posts(postPerPage, bottomOffset, postsOffset).init();
});
});
and this is php:
function ajax_loadposts_posts() {
$ppp = (isset($_POST['ppp'])) ? $_POST['ppp'] : 3;
$offset = (isset($_POST['offset'])) ? $_POST['offset'] : 0;
$args = array(
'post_type' => array( 'cars' ),
'post_status' => array( 'publish' ),
'order' => 'DESC',
'orderby' => 'title',
'posts_per_page' => $ppp,
'offset' => $offset,
);
$the_query = new WP_Query( $args );
$out = '';
if( $the_query->have_posts() ):
$i=$offset+1; while( $the_query->have_posts() ) : $the_query->the_post();
set_query_var( 'iteration', $i );
$out .= get_template_part( 'cars/content', get_post_type() );
$i++; endwhile;
endif;
wp_reset_postdata();
wp_die($out);
}
add_action('wp_ajax_loadposts', 'ajax_loadposts_posts');
add_action('wp_ajax_nopriv_loadposts', 'ajax_loadposts_posts');
I have this function where on onkeyup it verifies the mobile number whether it exists in the database already or not now the issue is even if the response is "true" it will always show as false
PHP
elseif ($action == 'check_mobile_phone')
{
$mobile = trim($_GET['mobile']);
$mobile = json_str_iconv($mobile);
if (mobile_register($mobile))
{
echo 'false';
}
else
{
echo 'true';
}
}
Ajax Call
function checkMobilePhone(mobile)
{
if (mobile == '')
{
error.find('#mobile_notice_text').html('Mobile number cant be empty.');
submit_disabled = true;
}
else if (!Utils.isMobile(mobile))
{
error.find('#mobile_notice_text').html('Please enter mobile number in local format.');
}
if( submit_disabled )
{
document.forms['formUser'].elements['Submit'].disabled = 'disabled';
return false;
}
Ajax.call( 'user.php?act=check_mobile_phone', 'mobile=' + mobile, check_mobile_callback , 'GET', 'TEXT', true, true );
}
Response
function check_mobile_callback(result)
{
var logform = $('form[name="formUser"]');
var error = logform.find('#mobile_notice');
if ( result === "true" )
{
document.forms['formUser'].elements['Submit'].disabled = '';
}
else
{
error.find('#mobile_notice_text').html('Phone number already exists.');
document.forms['formUser'].elements['Submit'].disabled = 'disabled';
}
}
function mobile_register($mobile)
{
$res = $GLOBALS['db']->getOne("SELECT COUNT(*) FROM " . $GLOBALS['db']->table('users') .
" WHERE mobile_phone = '$mobile'");
return $res;
}
I uploaded the dropdown to my web site, somehow it looks double:)
Like this:
But, that's not the only problem,
Another problem is that Elements do not appear in the <select> list, but when I add some sample <option>Sample</option> all elements appear.
My Select Codes:
<select class="selectpicker" id="List" multiple data-live-search="true" data-actions-box="true" data-selected-text-format="count>1">
<option>asdd</option>
<option>3</option>
<option>ssasd</option>
<option>adsd</option>
<option>a</option>
<option>sasd</option>
<option>adsd</option>
</select>
My JavaScript code:
$.ajax({
type : "POST",
url : "db/../..",
dataType : "json"
})
.done(function( result ) {
if ( typeof result.error !== "undefined" ) {
// Error
dialog.close();
alertDialog( "Hata", result.error, BootstrapDialog.TYPE_DANGER );
} else if ( typeof result.List !== "undefined" && $.isArray( result.List ) ) {
// A proper result
if ( result.FirmList.length < 1 ) {
// No records found
dialog.close();
alertDialog( "Error", "Nothing Found!", BootstrapDialog.TYPE_WARNING );
} else {
// Parse details
var f = result.List;
for ( var i = 0; i < f.length; i++ ) {
var op = document.createElement( "option" );
op.value = f[ i ].Id;
op.textContent = f[ i ].Name;
document.getElementById( "List" ).appendChild( op );
}
$( "#select" ).chosen();
}
} else {
dialog.close();
alertDialog( "Error", "No Idea!", BootstrapDialog.TYPE_DANGER );
}
})
.fail(function(a, b, c) {
dialog.close();
alertDialog( "Error",
"Error",
BootstrapDialog.TYPE_DANGER );
});
I have a form with a dropdown list. On change, it calls 2 ajax functions :
<select onchange="getLimite(this.value); getPrice(this.value);">
Thoses functions call a PHP script which send a SQL query.
Problem : one function works, the other not.
In this way :
<select onchange="getLimite(this.value); getPrice(this.value);">
Only getPrice(this.value) works.
In this way :
<select onchange="getPrice(this.value); getLimite(this.value);">
Only getLimite(this.value) works.
Source of one of those functions (for example) :
function getPrice(billet) {
if(billet == 'vide') {
document.getElementById("blocPrixP").innerHTML = '';
}
else {
var prixBlocP = document.getElementById("blocPrixP");
prixBlocP.innerHTML = '<img src="images/loading.gif" alt="loading" title="loading" />';
creerRequete(); // new XMLHttpRequest();
var urlPrix = 'prix.php?billet='+billet;
requete.open('GET', urlPrix, true);
requete.onreadystatechange = function() {
if(requete.readyState == 4) {
if(requete.status == 200) {
affichePrix();
}
}
};
requete.send(null);
}
}
prix.php looks like this :
if(isset($_GET['billet'])) {
$billet = $_GET['billet'];
}
else {
$billet = false;
}
if(false !== $billet) {
$requete_prix = $bdd->prepare('SELECT nom_billet, prix_billet FROM ce_billet WHERE nom_billet = :nom_billet');
$requete_prix->execute(array(
':nom_billet' => $billet
));
$data = $requete_prix->fetch();
echo $data['prix_billet'];
}
else {
echo 'Error';
}
Edit : the other function
function getLimite(billet_bis) {
if(billet_bis == 'vide') {
document.getElementById('blocQuantite').innerHTML = '';
}
else {
var blocQuantite = document.getElementById('blocQuantite');
blocQuantite.innerHTML = '<img src="images/loading.gif" alt="loading" title="loading" />';
creerRequete();
var url_limite = 'limite.php?billet='+ billet_bis;
requete.open('GET', url_limite, true);
requete.onreadystatechange = function()
{
if(requete.readyState == 4)
{
if(requete.status == 200)
{
afficheLimite();
}
}
};
requete.send(null);
}
}
limite.php :
if(isset($_GET['billet'])) {
$billet2 = $_GET['billet'];
}
else {
$billet2 = false;
}
if(false !== $billet2) {
$requete_limite = $bdd->prepare("SELECT id_billet, nom_billet, limitation_chiffre_billet FROM ce_billet WHERE nom_billet = :nom_du_billet");
$requete_limite->execute(array(
':nom_du_billet' => $billet2
));
$data = $requete_limite->fetch();
$limite = intval($data['limitation_chiffre_billet']);
if($limite == '') {
$liste = NULL;
}
else {
$liste = '<select id="quantite-billet" name="quantite-billet-name" onchange="getQte(document.getElementsByClassName(\'selecttwo\')[0].value);">'; //
$liste .= '<option value="vide" id="vide">- - - Choisissez la quantité - - -</option>';
for($i = 1; $i <= $limite; $i++) {
$liste .= '<option value="'.$i.'" id="'.$i.'billet">'.$i.'</option>';
}
$liste .= '</select>';
}
echo $liste;
}
else {
echo "Erreur";
}
Edit 2 : function creerRequete(), function affichePrix(), function afficheLimite()
/* creerRequete() */
var requete = null;
function creerRequete() {
try {
requete = new XMLHttpRequest();
}
catch (microsoft) {
try {
requete = new ActiveXObject('Msxml2.XMLHTTP');
}
catch(autremicrosoft){
try {
requete = new ActiveXObject('Microsoft.XMLHTTP');
}
catch(echec) {
requete = null;
}
}
}
if(requete == null) {
alert('Ajax does not work');
}
}
/* afficheLimite() */
function afficheLimite() {
var limite = requete.responseText;
var blocQuantiteb = document.getElementById('blocQuantite');
blocQuantiteb.innerHTML = limite;
}
/* affichePrix() */
function affichePrix() {
var prixDuBillet = requete.responseText;
var prixBloc = $("#blocPrix");
var totalprice = $("#prixtotal");
prixBloc.val(parseFloat(prixDuBillet));
totalprice.val(prixBloc.val() + ' €');
$('#quantite-billet').on('change', function() {
var quantite = $("#quantite-billet option:selected").val();
totalprice.val((Math.round((prixBloc.val() * parseInt(quantite)) * 100) / 100 ) + ' €');
});
document.getElementById("blocPrixP").innerHTML = '';
}
I don't know how to call the 2 functions separately.
Have you tried calling the two from within a wrapper function, and sending a call to that as your onchange event handler? Like this:
<select onchange="getLimiteAndPrice(this.value)">
function getLimiteAndPrice(billet) {
getLimite(billet);
getPrice(billet);
}
requete is a global variable in your code. You use it in both getLimite() and getPrix() functions. One function overrides the other's value.
Here is what I'd do:
function creerRequete() {
var requete = null;
try {
requete = new XMLHttpRequest();
}
//etc.
// And at the end:
if(requete == null) {
alert('Ajax does not work');
} else {
return requete;
}
Then in getPrix():
function getPrix() {
[... do your stuff ...]
var maRequete = creerRequete(); // This is another variable (it exists only inside the function - you can give it another name if you find it easier to understand)
[... do other stuff ...]
affichePrix(maRequete);
}
Finally:
function affichePrix(toujoursMaRequete) {
// Here you can use requete (you still can give it another name: it exists only inside this function)
var prixDuBillet = toujoursMaRequete;
}
Same with your "Limite" functions.
You could have had a global variable (as you did before) if both function weren't executing at the same time, and changing the variable's value at the same time (or if this specific behavior was wanted).
I am doing an AJAX call from a function. Everything works fine until the AJAX call(I tried console.log before the AJAX call that was executed). It calls a controller's index function from there it returns the JSON object
in view:
$.ajax({
type: "POST",
url: "<?php echo $this->Html->url('/proposals');?>",
data: form,
dataType: "json",
success: function(data){
//alert(data.id+'--'+data.msg);
console.log("test");
if(data.msg == 'success'){
var valueRemaining= $('#RemainingFunding').val() ;
if (valueRemaining <= 0 ) {
alert ('No Funds Remaining');
return false;
}
var valueSubmitted = $('#subtotal'+state).text();
var valueSubmitted = parseInt(valueSubmitted);
if (valueSubmitted != null || valueSubmitted != '') {
//var substract = valueRemaining - valueSubmitted;
//$('#RemainingFunding').val(substract);
}
//console.log( 'value of subtotao f = ' + subflt );
$('#ProposalId').val(data.id); //ajx_submit
$('#sum').val(data.propsum);
$('#ajx_submit').val(parseInt(tot_ajxsub)+1);
$("input:radio[id=ProposalAnotherLocationY]").prop('checked', false);
$('#fld_subtotal').val('0');
pastSubtotals += flttot;
console.log("test");
tableState=0;
//console.log( 'value of pastSubtotal = ' + pastSubtotals);
//$('#RemainingFunding'). val(intamtval);
}else if(data.msg == 'error'){
alert('Proposal budget can not be blank!!');
return false;
}else {
alert('no match');
}
return false;
//$("#form")[0].reset();
//Unterminated String constant fixed
}
});
Controller:
if ($this - > request - > isAjax()) {
$Proposalsum = $this - > DftsProposalbudget - > find('all', array('fields' => array('SUM(DftsProposalbudget.cy1) as cy1', 'SUM(DftsProposalbudget.cy2) as cy2', 'SUM(DftsProposalbudget.cy3) as cy3 ', 'SUM(DftsProposalbudget.cy4) as cy4 ', 'SUM(DftsProposalbudget.cy5) as cy5', 'SUM(DftsProposalbudget.cy6) as cy6', 'SUM(DftsProposalbudget.cy7) as cy7', 'SUM(DftsProposalbudget.cy8) as cy8', 'SUM(DftsProposalbudget.cy9) as cy9', 'SUM(DftsProposalbudget.cy10) as cy10'), 'conditions' => array('DftsProposalbudget.proposal_id' => $LastID, 'DftsProposalbudget.user_id' => $UID), 'group' => 'DftsProposalbudget.proposal_id'));
$sum = 0;
echo '<pre>'.print_r($Proposalsum, true).
"</pre>";
if (!empty($Proposalsum)) {
foreach($Proposalsum[0][0] as $key => $value) {
//echo $sum += $value['0']['cy1'];
$sum += $value;
}
}
echo json_encode(array('msg' => 'success', 'id' => $LastID, 'propsum' => $sum));
exit(0); //json_encode('msg' => 'success', 'id' => '1');
In the network I get this message:
But it is not printing or working for anything that is in the block success.