I'm building in Wordpress, I know I need to use AJAX, but not how to do so.
I have a drop down select box, when the user selects an option a div appears.
The data in that div needs to be pulled from a custom post, so I have a php variable to do this.
What I need to do, is be able to change that php variable based on the selection of the drop down.
I can do this in jQuery, but I don't know how to transfer the jQuery var to php.
Any assistance would be much appreciated.
$(document).ready(function(){
$('select').change(function(){
$( 'select option:selected').each(function(){
if($(this).attr('value')=='choose'){
hide_visible();
}
var val = $('#course_select option:selected').val();
var course_id;
if (val == 'CPR'){
course_id = 106; <!-- I need to send this to php -->
$( '#course_id' ).val(course_id);
};
if($(this).attr('value') == val){
if ($( '.course-info ' ).is(':visible')) {
$( '.course-info' ).slideUp( 'slow' ).delay(700);
$( '.iframe' ).slideUp( 'slow' );
$( '.form' ).slideUp( 'slow' );
$( '.'+ val ).slideDown( 'slow' );
}else{
$('.iframe').slideUp( 'slow' );
$( '.course-info' ).slideUp( 'slow' );
$( '.'+ val ).slideDown( 'slow' );
};
}
});
}).change();
});
From your edited question, you can just do something like the following:
$('.result-element').load('my-page.php?courseid=' + courseId);
Look into api.jquery.com/load for more information is using jQuery.load().
Your my-page.php can get "courseid" from $_GET['courseid'] and you can just echo your raw HTML as a "partial" which jQuery will automatically add to the '.result-element' element.
You won't need your PHP variable.
On the change event of your drop down, fetch the value selected, then build your ajax query and send it to the server.
Checkout the following functions of jQuery: ajax(), change(), val(), html(), show().
You also need to setup an endpoint for jQuery to request the data. Something like http://domain.com/api/get-my-data. That's a wordpress task (ie. PHP). This endpoint / script should return a JSON encoded object that contains the content of your div.
Maybe this helps additional that you're using jquery also. cheers men :)
$(document).ready(function(){
$('select').change(function(){
$( 'select option:selected').each(function()
{
if($(this).attr('value')=='choose')
{
hide_visible();
}
var val = $('#course_select option:selected').val();
var course_id;
if (val == 'CPR')
{
course_id = 106; // Sample code where you can send your jquery variable to php page
$.post("send_variable.php", {id:val}, function(data){
alert(data) //shouts the data from send_variable.php page
$("#hiddenTextbox").val(data); //this passes the value from send_variable.php to a textbox with Id(hiddenTextbox) into the page
});
$( '#course_id' ).val(course_id);
}
if($(this).attr('value') == val)
{
if ($( '.course-info ' ).is(':visible'))
{
$( '.course-info' ).slideUp( 'slow' ).delay(700);
$( '.iframe' ).slideUp( 'slow' );
$( '.form' ).slideUp( 'slow' );
$( '.'+ val ).slideDown( 'slow' );
}
else
{
$('.iframe').slideUp( 'slow' );
$( '.course-info' ).slideUp( 'slow' );
$( '.'+ val ).slideDown( 'slow' );
}
}
}
});
}).change();
Here's the code for send_variable.php
<?php
$val1 = $_POST['id'];
echo $val1; //thus returning the data that depends on your selected from dropdown
?>
Hopes this helps :)
Related
I am using jquery, to add dynamically two input fields in a new "row" div. The problem is, that only the second input field is cloned and appended.I canĀ“t find the solution. Any help is appreciated.
Trainer= {
neuen_trainer_hinzufuegen(){
var n = $( ".trainerposition" ).length;
$( "#trainer" ).append( $('<div class="trainerposition" id="trainerposition_'+n+'"></div>') );
$( "#trainer_0_vorname" ).clone().appendTo( "#rtrainerposition_"+n );
$( "#trainerposition_"+n+" input:nth-child(2)").attr('name', 'trainer_'+n+'_vorname');
$( "#trainerposition_"+n+" input:nth-child(2)").attr('id', 'trainer_'+n+'_vorname');
$( "#trainer_0_nachname" ).clone().appendTo( "#trainerposition_"+n );
$( "#trainerposition_"+n+" input:nth-child(3)").attr('name', 'trainer_'+n+'_nachname');
$( "#trainerposition_"+n+" input:nth-child(3)").attr('id', 'trainer_'+n+'_nachname');
}
}
You have an extra r in your selector :-)
$( "#trainer_0_vorname" ).clone().appendTo( "#rtrainerposition_"+n );
I think this should be
$( "#trainer_0_vorname" ).clone().appendTo( "#trainerposition_"+n );
What I'm trying to achieve is when the list of textareas is rearranged that the name of the textareas updates to always be ordered ascending. To demonstrate:
Original
name content
value[0] content0
value[1] content1
value[2] content2
Reordered (not necessarily in this order, just an example)
name content
value[0] content2
value[1] content0
value[2] content1
What I've written should loop through the list and update the name attributes, but sometimes it just doesn't and the other times it will get the order of the names very wrong. Here's the jQuery I'm running:
$(document).ready(function(){
$( ".sortable" ).sortable();
$( ".sortable" ).disableSelection();
$( ".sortable" ).on("sortchange", function( event, ui ) {
var $i = 0;
$('.sortable > li').each(function(){
$(this).children('textarea').attr( 'name', 'value[' + $i + ']' );
$i++;
});
});
});
And a fiddle. Not sure what I'm doing wrong.
use sortstop instead of sortchange:
$(document).ready(function(){
$( ".sortable" ).sortable();
$( ".sortable" ).disableSelection();
$( ".sortable" ).on("sortstop", function( event, ui ) {
var $i = 0;
$('.sortable > li').each(function(){
$(this).children('textarea').attr( 'name', 'value[' + $i + ']' );
$i++;
});
});
});
fiddle: https://jsfiddle.net/kz4t8ph5/2/
Also take a look at Saif's answer below :)
use sortupdate instead of sortchange. sortchange is triggered during sorting that's why you are getting unexpected number sequence. sortupdate will be triggered when you stopped sorting. so you will get the final position and expected sequence.
$( ".sortable" ).on("sortupdate", function( event, ui )
{
}
Applied DataTable (jquery.dataTables.min.js) to the existing table, so having that table paged and sorted:
$( '#news_table' ).DataTable( {
"order": [[ 5, "asc" ]],
"lengthMenu": [5, 10, 20],
} );
Everything works smoothly on first page of the table. Some JQuery scripts stop working correctly when change page. So, there are related chunks of code:
<td>
<a href="#myModal" class="editNews" role="button" data-toggle="modal" data-id="${news.id}">
<img src="resources/img/edit.png"></img>
</a>
</td>
By clicking on image (edit.png) modal window appears. The next part converts the modal to the edit flavour.
$( '.editNews' ).click(function(e) {
e.preventDefault();
$( '#deleteNews' ).removeClass( 'notShow' );
var dataId = $( this ).attr( 'data-id' );
$( '#resetNews' ).addClass( 'notShow' );
$.ajax({
type: "GET",
dataType: "json",
url: "admin/update/" + dataId,
success: function( response ) {
console.log( response );
$( '#myModalLabel' ).html( "Edit post with id:<span style='color: rgb(255, 0, 0);'>" + response.id + "</span>" );
$( '#newsId' ).text( response.id );
$( '#incomingDate' ).text( response.incomingDate );
$( '#changeDate' ).text( response.changeDate );
$( '#messageTitle' ).val( response.title );
$( 'div#messageStatus button' ).each(function( index ) {
if ( response.messageStatus == index + 1) {
$( this ).addClass( 'active' );
}
});
$( '.note-editable' ).html( response.message );
$( '#messageOrder' ).text( response.messageOrder );
$( '#myModal' ).modal( 'show' );
},
complete:function() {
}
});
return false;
});
I mean, that clicking, say on the link (edit.png) on any page excepting first one modal window will still appear, but will be empty, so looks like scripts just missed. I tried to figure it out, but stuck.
There are also some other scripts which also stopped acting properly.
Thanks for the any advice.
Images below illustrate the situation:
Hi this is quite common problem, you use your jQuery code once (on DOM ready I suppose).
When you click pagination table is generated again and that new elements are not bind to your jQuery code.
You have to 1) run jQuery code after each ajax request maybe using ajax complete:function() {//put me here...
or 2)
use jQuery "on"
$( "body" ).on( "click", ".editNews", function() {
//put your code here
});
I have a comment section that is initially hidden, and would be revealed by a link on the comment count and/or a link to add comments.
I would like for the comment section to open by either link, but not close if its already opened.
$( "#commentsToggle").click(function() {
$( "#comments" ).toggle( "fast" );
return false;
});
$( ".comment-add a").click(function() {
$( "#comments" ).toggle( "fast" );
return false;
});
See the jsfiddle
http://jsfiddle.net/pQ2np/
Thanks
EDIT: The '#commentsToggle' should be able to toggle (hide) the comments if open, the '.comment-add a' should only show, not hide as it opens an ajax comment form.
This is the code solves my need:
$( "#commentsToggle").click(function() {
$( "#comments" ).toggle( "fast" );
return false;
});
$( ".comment-add a").click(function() {
$( "#comments" ).show( "fast" );
return false;
});
http://jsfiddle.net/pQ2np/6/
If you want them to remain open. use show() instead of toggle().
$( "#commentsToggle").click(function() {
$( "#comments" ).show( "fast" );
return false;
});
$( ".comment-add a").click(function() {
$( "#comments" ).show( "fast" );
return false;
});
You can put both selectors into one function and pass true as the first parameter to showOrhide as referenced in the docs.
$( "#commentsToggle, .comment-add a").click(function() {
$( "#comments" ).toggle( true );
return false;
});
http://jsfiddle.net/pQ2np/3/
Try to use the code in the following link (I have updated your own).
I am not sure why to use toggle and not show. But generally you can check the css display attribute because this is what is used by jquery events.
$( "#commentsToggle").click(function() {
if ($( "#comments" ).css("display") != "block")
$( "#comments" ).toggle( "fast" );
return false;
});
$( ".comment-add a").click(function() {
if ($( "#comments" ).css("display") != "block")
$( "#comments" ).toggle( "fast" );
return false;
});
jsfiddle
Is that you are looking for?
You could use .show() instead of .toggle(), or you could add "true" as one of the parameters:
$( "#commentsToggle").click(function() {
$( "#comments" ).toggle( "fast", true );
return false;
});
$( ".comment-add a").click(function() {
$( "#comments" ).toggle( "fast", true );
return false;
});
Using false instead of true will hide the elements, so using a variable in there could come in useful later.
Here's an updated Fiddle plus enhancements. Below is the gist of it:
$( "#commentsToggle, .comment-add a").click(function (e) {
e.preventDefault();
var $comments = $("#comments");
if ($comments.is(":visible")) {
return;
}
$comments.show("fast");
});
UPDATE: I missed the fact that if you "show" the links again but want to prevent them from being toggled, you only need to use the .show() method. No need for toggle if your intention is for the comments section to appear once and remain open.
Guess I'm just starting out here, so might as well look for any kind of help since I'm quite frustrated with this novice question...
I have a button that shows a form I created, with 1 click, but the problem comes when I want to show another form that comes with another button.
What I want, basically is that buttonA shows formA, but when I click buttonB, I want to hide formA and show formB. Now what's happening is that it's overlaying formA and formB.
Here's my current code..
function runEffect() {
$( "#effect" ).show( "drop");
};
function runEffect2() {
$( "#effect2" ).show( "drop");
};
//callback function to bring a hidden box back
function hideEffect() {
$( "#effect:visible" ).hide( "drop");
};
// set effect from select menu value
$( "#button" ).each(function(index) {
$(this).click(function(){
runEffect();
});
});
$( "#button2" ).each(function(index) {
$(this).click(function(){
runEffect2();
});
});
$( "#effect" ).hide();
$( "#effect2" ).hide();
I know this is easy, but I can't seem to find the answer to it.
Thanks!
try this
function runEffect() {
$( "#effect" ).show( "drop");
$( "#effect2" ).hide( "drop");
};
function runEffect2() {
$( "#effect2" ).show( "drop");
$( "#effect" ).hide( "drop");
};
$('#buttonB').click(funciton()(
$('#formA').hide();
$('#formB').show();
});
something like this?
I haven't tested it, but maybe you want to a more dynamic function.
Button class must be something like "formButton" and the id like "form1Button", the form id then should be "form1" and so on..
(Form 2 would have a button with class "formButton", id like "form2Button" and form 2 needs id "form2"
$(".formButton").click(function(e) {
e.preventDefault(); //prevent default action
var id = $(this).attr('id');
var formId = id.replace('Button', '');
$('#' + formId).show();
$('form').not(document.getElementById(formId)).hide();
});
When a formButton is clicked, the form will be shown. All other forms, wich do not have the requested ID, will be hidden.