How to set selected value of jQuery chosen? - php

<script>
$(document).ready(function () {
$("#state").change(function () {
var stateId = $("#state").val()
phpurl = "sample_url" + stateId;
$.ajax({
url: phpurl,
success: function (data) {
$("#district").html(data).trigger("chosen:updated");
},
error: function(data) {
}
});
});
});
</script>
Above is my code to generate district based on state, and it works fine. I just want set the value what is selected by user. At present the selected value is cleared after selecting a state and submit.

You can use a global to hold selected value
var selectedDistrict = 0;
$("#district").change(function () {
selectedDistrict = $("#district").val();
});
then do:
$("#district")
.html(data)
.trigger("chosen:updated")
.val(selectedDistrict)
.trigger("chosen:updated");
in your ajax success.
Means your code will become:
<script>
var selectedDistrict = 0;
$(document).ready(function () {
$("#district").change(function () {
selectedDistrict = $("#district").val();
});
$("#state").change(function () {
var stateId = $("#state").val()
phpurl = "sample_url" + stateId;
$.ajax({
url: phpurl,
success: function (data) {
$("#district").html(data)
.trigger("chosen:updated")
.val(selectedDistrict)
.trigger("chosen:updated");
},
error: function(data) {
}
});
});
});
</script>

Related

Wordpress AJAX call response 0

I'm tryng to set up a panel, this one
The menu on the top calls different ajax functions in order to display a thumb. Clicking on the thumb you can see the details in the last box of the panel.
I have this php functions
function GetPostPartner(){
$catPartner = "loop_pb_partner";
get_template_part($catPartner);
wp_die();
}
add_action('wp_ajax_nopriv_GetPostPartner', 'GetPostPartner');
function GetPostEnte(){
$catEnte = "loop_pb_ente";
get_template_part($catEnte);
wp_die();
}
add_action('wp_ajax_nopriv_GetPostEnte', 'GetPostEnte');
function GetPostColl(){
$catColl = "loop_pb_coll";
get_template_part($catColl);
wp_die();
}
add_action('wp_ajax_nopriv_GetPostColl', 'GetPostColl');
function GetPostMedia(){
$catMedia = "loop_pb_media";
get_template_part($catMedia);
wp_die();
}
add_action('wp_ajax_nopriv_GetPostMedia', 'GetPostMedia');
function GetPostDetails(){
$pb_details = $_POST['postURL'];
get_template_part($pb_details);
wp_die();
}
add_action('wp_ajax_nopriv_GetPostDetails', 'GetPostDetails');
And those are called by these ajax functions
$(document).delegate('h4.homus-partners-global-ajax[data-pb- cat*=pb_partner]', 'click', function(event) {
event.preventDefault();
var pb_cat = "pb_partner";
var data = {
'action': 'GetPostPartner',
catURL : "loop_"+ pb_cat,
};
$.post(ajaxURL, data, function(response) {
$( 'ul.homus-partners-section-slide' ).html(response);
});
});
$(document).delegate('h4.homus-partners-global-ajax[data-pb-cat*=pb_ente]', 'click', function(event) {
event.preventDefault();
var pb_cat = "pb_ente";
var data = {
'action': 'GetPostEnte',
catURL : "loop_"+ pb_cat,
};
$.post(ajaxURL, data, function(response) {
$( 'ul.homus-partners-section-slide' ).html(response);
});
});
$(document).delegate('h4.homus-partners-global-ajax[data-pb-cat*=pb_coll]', 'click', function(event) {
event.preventDefault();
var pb_cat = "pb_coll";
var data = {
'action': 'GetPostColl',
catURL : "loop_"+ pb_cat,
};
$.post(ajaxURL, data, function(response) {
$( 'ul.homus-partners-section-slide' ).html(response);
});
});
$(document).delegate('h4.homus-partners-global-ajax[data-pb-cat*=pb_media]', 'click', function(event) {
event.preventDefault();
var pb_cat = "pb_media";
var data = {
'action': 'GetPostMedia',
catURL : "loop_"+ pb_cat,
};
$.post(ajaxURL, data, function(response) {
$( 'ul.homus-partners-section-slide' ).html(response);
});
});
$(document).delegate('li.homus-partners-section-single', 'click', function(event) {
event.preventDefault();
var pb_post_id = $(this).data('post-id');
var data = {
'action': 'GetPostDetails',
postURL : "single_pb_post_details",
post_id: pb_post_id
};
$.post(ajaxURL, data, function(response) {
$( '.homus-partners-detalis' ).html(response);
console.log(pb_post_id);
console.log(data.postURL);
console.log(response);
});
});
the response that I have is always 0 even if the console of the last ajax call here above return the right postid. You can find the whole project in this repo
https://github.com/wanbinkimoon/homus-web.git
in the code
function GetPostPartner(){
$catPartner = "loop_pb_partner";
get_template_part($catPartner);
wp_die();
}
add_action('wp_ajax_nopriv_GetPostPartner', 'GetPostPartner');
instead of including the file by get_template_part paste the code here and then try

jQuery use ajax and json to switch page with button

Hi so I have a JS file with a function for my button, this button get value from different checkbox in a table. But now i want to get these value on another page (for invoice treatement).
Here is my Script :
$("#boutonfacturer").click(function () {
var checked = $('input[name="id_commande[]"]:checked');
var tab = [];
var jsonobj = {};
checked.each(function () {
var value = $(this).val();
jsonobj.value = value;
tab.push(jsonobj);
});
var data= { recup : tab };
console.log(data);
$.ajax({
type: 'POST',
url: 'genererfacture-facture_groupee.html',
data: data,
success: function (msg) {
if (msg.error === 'OK') {
console.log('SUCCESS');
}
else {
console.log('ERROR' + msg.error);
}
}
}).done(function(msg) {
console.log( "Data Saved: " + msg );
});
});
i use an MVC architecture so there is my controller :
public function facture_groupee() {
$_POST['recup'];
var_dump($_POST['recup']);
console.log(recup);
$this->getBody()->setTitre("Facture de votre commande");
$this->getBody()->setContenu(Container::loader());
$this->getBody()->setContenu(GenererFacture::facture_groupee());
and for now my view is useless to show.
I have probably make mistake in my code.
Thank you.
Nevermind after thinking, I have used my ajax.php page which get my another page thanks to a window.location :
my JS :
$("#boutonfacturer").click(function () {
var checked = $('input[name="id_commande[]"]:checked');
var tab = [];
checked.each(function () {
var value = $(this).val();
tab.push(value);
});
var data = {recup: tab};
console.log(data);
$.ajax({
type: 'POST',
url: 'ajax.php?action=facture_groupee',
data: data,
success: function (idfac) {
console.log("Data Saved: " + idfac);
var id_fac = idfac;
window.location = "ajax.php?action=facture_groupee=" + id_fac;
}
});
});
my php :
public function facture_groupee() {
foreach ($_POST['recup'] as $p){
echo $p; }

jquery get data from controller using json_encode

ajax function
<script type="text/javascript">
var timeOutID =0;
var checkScores = function () {
$.ajax({
url: 'http://127.0.0.1/ProgVsProg/main/countScoreCh',
success: function(response) {
if(response == false){
timeOutID = setTimeout(checkScores, 3000);
} else {
jsn = JSON.parse(response);
score= jsn.scoreCH;
$('#progressbar').progressbar({
value: score
});
clearTimeout(timeOutID);
}
}
});
}
timeOutID = setTimeout(checkScores,1000);
</script>
Controller
public function countScoreCh(){
$id = $this->session->userdata('userID');
$data['getScore'] = $this->lawmodel->battleUserID($id);
foreach($data['getScore'] as $row){
$scoreCH = $row->challengerScore;
echo json_encode(array('scoreCH' => $scoreCH));
}
}
Im having a problem..im using a progress bar..my idea is making the progress bar like a Hit Point/Health bar..but it seems that when i put the $('#progressbar').progressbar it will not get the value from jsn.scoreCH..jst disregards the response == false it still working i tried using console log..But when i put this code..it will not be read and display the output..
$('#progressbar').progressbar({
value: score
});
You can omit JSON.parse(response). Just use dataType: 'json'
$.ajax({
url: "http://127.0.0.1/ProgVsProg/main/countScoreCh",
dataType: 'json'
success: function(response) {
if(response.scoreCH == undefined){
timeOutID = setTimeout(checkScores, 3000);
} else {
$('#progressbar').progressbar({
value: response.scoreCH
});
clearTimeout(timeOutID);
}
}
});

Two ajax post simultaneously on one link click jquery

I am using one link which has class name next and id end.
On clcik on it both class name and id i am using jquery post.
The issue i am getting is sometimes the ajax request fires multiple times on one click.on one click i am getting data from one url and simultaneously saving these data into db by another url.So sometimes there are some issues coming while inserting into db.sometimes null values enters and sometimes multiple rows entering into db.So how can i write these two functions so that both will work perfectly?
$('.next').live('click', function (e) {
e.preventDefault();
var result = [];
var answer = [];
var le = '';
$('.answertext').each(function (index, element) {
result.push($(this).val());
});
$('.answer').each(function (index, element) {
answer.push($(this).val());
});
le = $('#level').val();
mle = $('#mainlevel').val();
$.ajax({
url: 'matchanswers.php',
type: 'POST',
data: {
result: result,
answer: answer,
level: le,
mle: mle
},
async: true,
beforeSend: function () {
// show indicator
},
complete: function () {
// hide indicator
},
success: function (data) {
$('.quizform').html(data);
}
});
});
$('#end').live('click', function (e) {
e.preventDefault();
var sublev = $('#level').val();
var score = $('#count').val();
if (sublev < 11) {
$.ajax({
url: 'submitanswers.php',
type: 'POST',
data: {
sublev: sublev,
score: score
},
async: true,
beforeSend: function () {
// show indicator
},
complete: function () {
// hide indicator
},
success: function (data2) {}
});
} else {
$.ajax({
url: 'getanswers.php',
type: 'POST',
data: {
sublev: sublev,
score: score
},
async: true,
beforeSend: function () {
// show indicator
},
complete: function () {
// hide indicator
},
success: function (data3) {
if (data3) {
$('.quizform').html("");
$('form :input').attr('disabled', 'disabled');
$('#logout').removeAttr("disabled");
var obj = $.parseJSON(data3);
$('#sum').html("Your Total Score for level - " + obj[0] + " is " + obj[1] + " in " + obj[2] + "secs");
}
}
});
}
});
You are firing click on same click even if id and class are different the link is same.
$('.next').live('click', function(e)
fires one ajax call and
$('#end').live('click', function(e)
fires another, what you can do is fire one ajax on success of other
$('.next').live('click', function(e) { ...
success: function(data) { $.ajax({
url: 'submitanswers.php', }
but this is not good practice
Simply check for the event trigger like :
$('.next').live('click', function (e) {
if(e.handled !== true){ // This will prevent event triggering more then once
e.handled = true;
//Your code
}
});
$('#end').live('click', function (e) {
if(e.handled !== true){ // This will prevent event triggering more then once
e.handled = true;
//Your code
}
});
By doing so, you will stop multiple event trigger which is quite a common problem and should solve your problem.
Edit :
Your full code will be :
$('.next').live('click', function (e) {
if (e.handled !== true) { // This will prevent event triggering more then once
e.handled = true;
//Your code
e.preventDefault();
var result = [];
var answer = [];
var le = '';
$('.answertext').each(function (index, element) {
result.push($(this).val());
});
$('.answer').each(function (index, element) {
answer.push($(this).val());
});
le = $('#level').val();
mle = $('#mainlevel').val();
$.ajax({
url: 'matchanswers.php',
type: 'POST',
data: {
result: result,
answer: answer,
level: le,
mle: mle
},
async: true,
beforeSend: function () {
// show indicator
},
complete: function () {
// hide indicator
},
success: function (data) {
$('.quizform').html(data);
}
});
}
});
$('#end').live('click', function (e) {
if (e.handled !== true) { // This will prevent event triggering more then once
e.handled = true;
//Your code
e.preventDefault();
var sublev = $('#level').val();
var score = $('#count').val();
if (sublev < 11) {
$.ajax({
url: 'submitanswers.php',
type: 'POST',
data: {
sublev: sublev,
score: score
},
async: true,
beforeSend: function () {
// show indicator
},
complete: function () {
// hide indicator
},
success: function (data2) {}
});
} else {
$.ajax({
url: 'getanswers.php',
type: 'POST',
data: {
sublev: sublev,
score: score
},
async: true,
beforeSend: function () {
// show indicator
},
complete: function () {
// hide indicator
},
success: function (data3) {
if (data3) {
$('.quizform').html("");
$('form :input').attr('disabled', 'disabled');
$('#logout').removeAttr("disabled");
var obj = $.parseJSON(data3);
$('#sum').html("Your Total Score for level - " + obj[0] + " is " + obj[1] + " in " + obj[2] + "secs");
}
}
});
}
}
});

Grab current value of textbox and drop-down-list and output them using jquery

What I would like to do is output the textbox value and the drop-down-list selected value simultaneously. The reason is I would like to eventually sort results through a mysql db table. Right now... when I change the textbox it will add onto the drop-down-list value, which is what I want. But when I change the drop-down-list value, it won't recognize the textbox value and revert to when the document was loaded as the value. How do I grab both values and echo them AND be able to change them and view the changes when I 'keyup' on the textbox or 'change' the drop-down-list value. Thanks in advance.
jquery
$(document).ready(function () {
var type_term = $("#type option:selected").text()
var search_term = $("#search").val()
$.post('search_db.php',{type_term:type_term, search_term:search_term}, function (data) {
$('#search_results').html(data)
});
$('#search').keyup(function() {
var search_term = $("#search").val()
$.post('search_db.php',{type_term:type_term, search_term:search_term}, function (data) {
$('#search_results').html(data)
});
});
$('#type').change(function() {
var type_term = $("#type option:selected").text()
$.post('search_db.php',{type_term:type_term, search_term:search_term}, function (data) {
$('#search_results').html(data)
});
});
});
HTML
<input id="search" type="text" value="Value">
<select id="type">
<option>Type1</option>
<option>Type2</option>
</select>
<div id="search_results"></div>
searchdb.php
$type_term = $_POST['type_term'];
$search_term = $_POST['search_term'];
echo $type_term;
echo $search_term;
Try setting the variables for both form elements on each event, rather than just the one that you are changing.
$(document).ready(function () {
var type_term = $("#type option:selected").text()
var search_term = $("#search").val()
$.post('search_db.php',{type_term:type_term, search_term:search_term}, function (data) {
$('#search_results').html(data)
});
$('#search').keyup(function() {
var search_term = $("#search").val()
var type_term = $("#type option:selected").text()
$.post('search_db.php',{type_term:type_term, search_term:search_term}, function (data) {
$('#search_results').html(data)
});
});
$('#type').change(function() {
var search_term = $("#search").val()
var type_term = $("#type option:selected").text()
$.post('search_db.php',{type_term:type_term, search_term:search_term}, function (data) {
$('#search_results').html(data)
});
});
});

Categories