This question is a continued one of this Giving an element multiple names/id's question I asked earlier.The second answer shows what is the better way to go about giving a element multiple attributes.
However after applying this method to my work. My javascript variables are undefined.
My html:
<a data-toggle="modal" data-id="prodModal" data-presId="<?php echo $selectPresForJs->valueof('pres_id'); ?>" data-prodId="<?php echo $prod->prod_id; ?>" data-target="#prodModal" class="image_modal" >
<img class="image-modal" style="width: 192px; height:192px;" src="<?php echo $prod->prod_icon; ?>">
<span ><h2 style='color:#2468A6'><b><?php echo $prod->prod_name ?></b></h2></span>
</a>
My javascript
$(document).ready(function(){
$('#prodModal').click(function() {
var ajaxprodId = $('#prodModal').data('prodId');
var ajaxpresId = $('#prodModal').data('presId');
/*Console Prints the variables as undefined*/
console.log(ajaxprodId);
console.log(ajaxpresId);
$.ajax({
url: "path/to/file/Presentation.php",
type: "POST",
data: {prodId : ajaxprodId,presId:ajaxpresId}
,success: function(data){
console.log("Success was achieved");
document.getElementById("modal_content").innerHTML = "Works";
},
error: function(data){
console.error("The action was unsuccessfull");
alert(data);
}
});
});
});
1. How would I fix/change my code so that variables ajaxprodId and ajaxpresId are not undefined?
2. Where would the correct place be to have ajax replace the innerHTML, as the current position only works after the modal has been opened, closed and then opened again.
when you use the selector $('#prodModal') you are referencing a DOM element with the attribute id set to prodModal. That id is not the same as your data-id.
So when you are using $('#prodModal') you get nothing because there isn't any element with that id
Related
I have a php loop that generates several buttons.Each button changes the content of a specific div and update some stuff in the database by using an ajax request.When the button is click it calls a function that executes the ajax request.The problem is that I am not able to pass the Div id as parameter in the function if I concatenate it with a string. Only when I write $TickCrossDiv = $i it is working (only when using number as Div id it works).
Here is my code :
for($i=0;$i<count($PlanningArray);$i++){
$TickCrossDiv = 'tickCrossDiv'.$i;
echo "<button onclick=\"SetActDone(
".$PlanningArray[$i]'PlanID'].",
".$PlanningArray[$i]['ActID'].",
".$TickCrossDiv.")\" >
Mark as done</button>"
}
Here is the function :
function SetActDone(PlanID,ActID,DivID)
{
$.ajax({
type: "POST",
url: 'testAjax.php',
data: {PlanID:PlanID, ActID:ActID},
success: function(data) {
$("#" + DivID ).html('<p>Status: Done</p> <i style="color:greenyellow; " class="fa fa-check-circle fa-2x"></i>');
}
});
}
I am getting the error :
Uncaught Error: Syntax error, unrecognized expression: #object HTMLDivElement
Without knowing what the values of $PlanningArray[$i][...] are I can't say for sure. But most likely you need to wrap your echoed variable in quotes. That would explain why a number would work, it will be treated as an integer rather than a string. Try this:
for($i=0;$i<count($PlanningArray);$i++){
$TickCrossDiv = 'tickCrossDiv'.$i;
echo "<button onclick=\"SetActDone(
".$PlanningArray[$i]['PlanID'].",
".$PlanningArray[$i]['ActID'].",
'".$TickCrossDiv."')\" >
Mark as done</button>"
}
I'm guessing that $PlanningArray[$i]['PlanID'] and $PlanningArray[$i]['ActID'] are also integers so they don't need to be wrapped in quotes.
I also fixed a typo on this line:
$PlanningArray[$i]'PlanID']
If your code works, that typo probably isn't in your real script.
I am trying to get WordPress Post Id dynamically as variable in jQuery. However, it is returning the value undefined when I try to debug in console. Can anyone help me on this ?
Here's the code:
data-id attribute displaying id of the current post
<?php $id = get_the_id(); ?>
<button data-id="<?php echo $id; ?>" type="button" class="book btn btn-danger">
Submit
</button>
My jQuery
jQuery(document).ready(function(jQuery){
jQuery('.packageForm').submit(packageSubmit);
function packageSubmit(){
var id = jQuery(this).attr('data-id');
var ceccForm = jQuery(this).serialize();
jQuery.ajax({
type:"POST",
url: "wp-admin/admin-ajax.php",
data: ceccForm,
success:function(data){
console.log(id);
console.log(data);
jQuery(".response").html(data);
jQuery(".packageForm")[0].reset();
jQuery('body').removeClass('modal-open');
}
});
return false;
}
});
Here, I am using var id = jQuery(this).attr('data-id'); to get the value of the attribute data-id dynamically. It's showing the message Undefined Value in the browsing console.
Any help ?
Here this is actually referring to your form packageForm since you're calling it from the submit function of the form, and it won't have the attribute you've set to the button.
You could probably do something like this
var id = jQuery(this).find('button.book').data('id');
this refers to the form not the button
do a find to get the button if the button is in the form tag
jQuery(this).find('button.book').attr('data-id');
I have a following Ajax success function which prints the folder div in the DOM when user load the page or add the folder.
for(var i in output.dirs){
//console.log(output.dirs[i]);
var html = '<div class="col-sm-3 text-center" id="img-folder"><input type="hidden" id="folder-names" name="open-folder" value="'+output.dirs[i].name+'"/>';
html+='<div class="mid-folder"> <i class="fa fa-folder fa-5x"></i>';
html+='<h3 class="title-folder">'+output.dirs[i].name.substr(0,15)+".."+'</h3></div>';
$(".folders").append(html);
And I want to add yet another Ajax request when each folder is clicked. I want to send the folder name of the folder that is being clicked and send it through the Ajax to the PHP controller, so that I could retrieve the images inside that folder. For that I attached an input tag with hidden attribute to print out the folder name as value, so that it could be easy for me to get the value using .val().
But the problem here is that how could I know which folder has been clicked and what's the value of the <input> tag which belongs to that div, since every div printed will have the same id "img-folder".
Looking at some alternatives, I found this:
$("#img-folder").each(function(i){
$(this).on("click",function(){
// Now how would I select the <input> tag value here, so that I could pass the value into the controller?
});
});
What I want to do now is to catch the value/folder name of the folder that being clicked and send the value to my ajax function which is something like this:
// function for showing the images and contents inside the folders.
$(function(){
$(document.body).on('click',"#img-folder",function(e){
console.log($("#folder-names").val());
//e.preventDefault();
$.ajax({
url:'<?php echo base_url("Welcome/show_image"); ?>',
type:'POST',
data:$('#folder-name').val(),
success:function(data){
console.log(data);
},
});
})
})
Any suggestion or any other logic to solve this problem? It would be great.
You are duplicating ids of element. IDs must be unique. You can rather give same class. like this:
for(var i in output.dirs){
//console.log(output.dirs[i]);
var html = '<div class="col-sm-3 text-center" class="img-folder"><input type="hidden" class="folder-names" name="open-folder" value="'+output.dirs[i].name+'"/>';
html+='<div class="mid-folder"> <i class="fa fa-folder fa-5x"></i>';
html+='<h3 class="title-folder">'+output.dirs[i].name.substr(0,15)+".."+'</h3></div>';
$(".folders").append(html);
and then use class selector to find element with class folder-names in clicked img-folder:
$(function(){
$(document.body).on('click',".img-folder",function(e){
var folderval = $(this).find(".folder-names").val();
console.log($(this).find(".folder-names").val());
//e.preventDefault();
$.ajax({
url:'<?php echo base_url("Welcome/show_image"); ?>',
type:'POST',
data:folderval ,
success:function(data){
console.log(data);
},
});
});
});
This is what you need -
Using jQuery this, you will get attribute value of that element. So, in your case it is input. You will store that attribute value and pass it in AJAX call.
$(this).on("click",function(){
var inputValue = $(this).attr('value');
$.ajax({
url:'<?php echo base_url("Welcome/show_image"); ?>',
type:'POST',
data: inputValue ,
success:function(data){
console.log(data);
},
});
});
I have been trying to have a button execute a PHP script on a page and refresh just a div tag without any success. When I remove the $ajax part of the script my buttons change state but when I add the ajax part again nothing happens.
I need to load some content from a PHP file and then change the button's and div tags state. Some help will be very much appreciated as I can't seem to find the problem.
<div id="noah-content">
<script>
$(document).ready(function() {
$("#ON'.$id.'").click(function() {
document.getElementById("ON'.$id.'").disabled = true;
document.getElementById("OFF'.$id.'").disabled = false;
$.ajax({
type: "POST",
url: "some.php",
data: {
param: $(this).attr("src");
}
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
$("#OFF'.$id.'").click(function() {
document.getElementById("ON'.$id.'").disabled = false;
document.getElementById("OFF'.$id.'").disabled = true;
});
});
</script>
<img src="images/about.png" alt="image" id="myimg" />
<input type="submit" class="ON" id = "ON'.$id.'" value=" ON " name="submit"/>
<input type="submit" class="OFF" id = "OFF'.$id.'" value=" OFF " name="submit" disabled="disable"/>
</div>
Lets start with evaluating your php:
In order to run your php you have to open php tags:
$("#ON<?php echo $id ?>")...
Replace it everywhere you want your id to appear. For debugging, open your page source in the browser and see what is being generated:
Example:
<input type="submit" class="ON" id="ON<?php echo $id ?>" value="ON" name="submit"/>
Firstly, your ids for your html tags, and the way you reference them in js, seem odd (though still perhaps valid when dropped into js or html as strings). Looks like your trying to reference a php value in an improper way in html and js.
Second, are you getting any errors on your javascript console? Does the ajax query complete (i.e. do you get the alert message)? Check your JS console because that will tell you something more than 'nothing happens'
Also
I usually use the success option for ajax rather than the done method. Personal choice.
You also have a syntax error after $(this).attr("src");. The semicolon indicates the end of a line of code usually, and you put it after an element in your array/object declaration for your data.
$.ajax({
type: "POST",
url: "some.php",
data: {
param: $(this).attr("src") //Removed the semicolon that was here
},
success: function(data){alert(msg)}
});
I currently have a dynamic number of these being generated with a foreach() loop:
<div id="<?php echo $data['id']; ?>" data-role="collapsible" data-theme="a">
<h1 style="white-space: normal"><?php echo $data['text']; ?></h1>
<center>
<p><?php echo $data['text']; ?></p>
</center>
</div>
What I want, is for an AJAX POST request to be dispatched to another resource with the parameters of $data['id'] when the collapsible <div> opens.
I tried using a .click method, but I was not able to make it work for a dynamic list of <div>s. I feel a method that waited until the animation was done (as to ensure the page is still responsive) is the best way.
Can someone please help with this?
For dynamically generated content, I would suggest you use the .on() method. Take for example the following code:
$('#container').on('click', 'div', function() {
var id = $(this).attr('id');
$(this).animate({
your animation
}, 5000, function() {
$.ajax({
url: "another_resource.php",
type: "POST",
data: {
id: id
}, //data to be sent
dataType: "text", //return data type
async: false,
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data);
}
});
});
}
The first parameter is the event(s)(can be space delimited for multiple events), while the second can either be the targeted element, or the function to execute. The last, in this case, is of course the function to execute.
The ajax will execute when the animation is complete, as requested.