send the img id to another file with ajax - javascript

I am trying to make this work, I have some images each one of them has this link with its own id.
this is the link: x
this is the script:
<script>
$(document).ready(function() {
$(".remove_img").click(function() {
e.preventDefault();
var id = $this.data('id');
$.ajax({
url: 'remove_img.php',
type: 'POST',
data: { bild : id },
success: function(data) {
alert("Gespeichert!");
}
});
});
});
</script>
and I receive the id in the remove_img.php like this: $_POST['bild']
in the chrome console I see this error:
$this is not defined (repetead 2 times)

You want to refer to the jQuery object correctly:
var id = $(this).data('id');
$this is read as a variable that hasn't been declared yet, whereas $(this) is the jQuery object wrapper for this, or the item that was clicked.

The current way to refer to the current jQuery element is $(this) not $this (your approach would work if that was a variable with the value of $(this) like var $this = $(this); which is valid but wouldn't make much sense in your case). So change this line:
var id = $this.data('id');
To:
var id = $(this).data('id');
Or (referring to the DOM element directly instead of using jQuery):
var id = this.dataset.id;

Related

how to use this incomplete javascript object in HTML

I got this javascript code to solve in a manner to use inner function but not able to use it. Please try to help me to use inner functions or do i need to modify this. I want to use inner functions on click on html element such as view and remove respectively;
var App = function(){
var url = 'api';
function view(event) {
var id = '??'; //here i have to receive id of the element(data-id)
$.ajax({
url: url + '/view/' +id,
data: data
}).done( function (data){
});
}
function remove(event) {
var id = '??'; //please determine the id
$.ajax({
url: url + '/remove/' + id ,
data: data
}).done( function (data){
});
}
function initialize() {
//
}
return {
//
}
}();
Try doing this:
For id you can do one thing, Save the id in data-id attribute of the element on which you want onClick listener and access it using Event-Delegation in javascript.
To use the inner method you don't need to return anything. Just do it this way :
var App = function(){
var url = 'api';
function view(event) {
//access the id attribute of event.target
}
function remove(event) {
//same
}
function initialize() {
//
}
App.view = view;
App.remove = remove;
};
//EDIT : instead of making it self-invoking, call the app function
App();
//to access it outside:
App.view("your_parameter");
App.remove("your_parameter");
EDIT : Instead of making it self-invoking, call the app function
Well it's pretty simple, use the $("#caller").click() function of our beloved
jQuery
Then inside the .click() function you can easily retrieve your id
Here you can find more on the .click() function
It will be something like this
$( "#view" ).click(function() {
id = document.getElementById("id").id;
//Here paste the code of your view function
});

How to properly use appendChild

$(document).ready(function() {
$("a:last").on("click", function(event) {
event.preventDefault();
var url = $("a:last").attr("href");
var page = url.slice(-2).trim();
var newDiv = document.createElement("div");
$(newDiv).addClass("content");
$(newDiv).addClass(page);
$(newDiv).load(url);
document.getElementById("main").appendChild($(newDiv));
});
});
I want to create a new div and load some content into it, then append it to the "main" div, but I get a TypeError:
Argument 1 of Node.appendChild does not implement interface Node.
I already have a div with id="main", why can't I append my new div to it?
Basically appendChild() expects a node object as its parameter, but here you are passing a jquery object. You can fix it by passing a node object,
document.getElementById("main").appendChild(newDiv);
And since you are using jquery, you can use its own append() function,
$(document).ready(function() {
$("a:last").on("click", function(event) {
event.preventDefault();
var url = $("a:last").attr("href");
var page = url.slice(-2).trim();
var newDiv = $("<div>");
newDiv.addClass("content");
newDiv.addClass(page);
newDiv.load(url);
$("#main").append(newDiv);
});
});
The issue is because you're mixing up jQuery and plain old JS. The error itself is because you're proving a jQuery object to appendChild() when it's expecting a DOMElement. As you're using jQuery anyway you may as well use that to create your elements. Try this:
$("a:last").on("click", function(e) {
e.preventDefault();
var url = $("a:last").attr("href");
var page = url.slice(-2).trim();
$('<div />').addClass('content ' + page).appendTo('#main').load(url);
});
$(newDiv) is a jquery object, not the node. You need to pass the node in. This will work
$(document).ready(function() {
$("a:last").on("click", function(event) {
event.preventDefault();
var url = $("a:last").attr("href");
var page = url.slice(-2).trim();
var newDiv = document.createElement("div");
$(newDiv).addClass("content");
$(newDiv).addClass(page);
$(newDiv).load(url);
document.getElementById("main").appendChild(newDiv);
});
});

Conditional addClass not working for each elements with same class

Les say I have some buttons with same class. On page load I am checking some value using ajax for each button. Depending on returned value of ajax request I want to add some class to the buttons, but it is not working,
$(document).ready(function(){
$('.add-remove-permissoion').each(function(){
var child = $(this).val();
var parent = $('#parent-name').text();
$.get('my-url', function(data){
if(data == 1){
$(this).addClass('glyphicon glyphicon-ok');
}else{
$(this).addClass('emptybox-blank');
}
});
});
});
I have checked that my ajax request is returning correct data. What is that I am doing wrong here?
The problem is the this reference inside the ajax callback, in the success callback this refers to the jqXHR object not the dom element reference that is why it is not working.
You can use a closure variable as given below to fix the problem
$(document).ready(function () {
$('.add-remove-permissoion').each(function () {
var $this = $(this),
child = $this.val();
var parent = $('#parent-name').text();
$.get('my-url', {}, function (data) {
if (data == 1) {
$this.addClass('glyphicon glyphicon-ok');
} else {
$this.addClass('emptybox-blank');
}
});
});
});
this in the context of the $.get handler doesn't refer to the element of the current iteration. Each function has it's own this value. You have several options.
Use the second parameter of the each callback.
$('.add-remove-permissoion').each(function(index, element) {
Use $.proxy or Function.prototype.bind method for setting the this value of the handler.
$.get('my-url', function(data) {
// ...
}.bind(this));
Cache the this value of the each handler and use it in your $.get handler.
var elem = this;
$.get('my-url', function(data) {
// ...
$(elem)...
});
Also note that there is a syntax error in your code:
$.get('my-url'}, function(data){
// -----------^
Problem is $(this) within ajax call does not refer to the button clicked.
Replace $(this).addClass with myElement.addClass. Create myElement within click event just before the ajax call: var myElement = $(this).

jQuery function not attached to dom elements

I am trying build a web page that will construct elements from JSON file and attach click function to those elements.
$(document).ready(function(){
$.ajax({
url: 'database.php',
type: "POST",
dataType: 'json',
success: function (datas) {
(datas);
for (var x = 0; x < datas.data.length; x++) {
var id = datas.data[x].ID;
var ip = datas.data[x].IP;
var ips='<div class="ip"><span id="ids">'+id+'</span><span id="number">'+ip+'</span></div>';
$('#left').append(ips);
}
}
});
$('.ip').click(function () {
alert($(this).children('#ids').text());
});
});
the code above builds the elements successfully but the click function is not working.
You can use the on function instead, it is used to apply event handlers to elements that are not yet created.
Where you have your current click setup, try something like this instead:
$(document).on('click', '.ip', function(){
alert($(this).children('#ids').text());
});
As #Pete has suggested, it is not a good idea to assign the same id attributes within a loop, they should be unique to the document. Consider finding them via class names instead, so you could alert something like:
alert($(this).children('.MyIdsSpan').text());

How to save "title" attribute of "a" with jQuery?

How can I save the value of the title for a row? These are the values of the title=%s:
<a class="false" title=1106 href="/useradminpage?main_id=%s&display=false"><span class="small">(hide)</span></a>
<a class="false" title=1153 href="/useradminpage?main_id=%s&display=false"><span class="small">(hide)</span></a>
<a class="false" title=1175 href="/useradminpage?main_id=%s&display=false"><span class="small">(hide)</span></a>
...
I've tried countless variations but none of them work. This is what I have now:
<script>
$(document).ready(function() {
console.log("ready");
$("a.false").click(function(e) {
$(this).closest("tr.hide").hide("slow");
var main_id = a.title;
var display = "false";
e.preventDefault();
});
$("a.false").click(function() {
$.ajax({
url: "/useradminpage?main_id=%s&display=false",
data: {main_id: "main_id", display: "display"},
success: function(data) {
display_false()
alert("4 - returned");
}
});
});
});
</script>
This is the third question on this topic. I appreciate any help. Thanks.
instead of
var main_id = a.title;
try
var main_id = $(this).attr('title');
because if I'm not wrong, "a" isn't defined
I think what you're trying to do is pass the value of the title attribute along in your AJAX request. If that's the case, the easiest thing to do will be to do it all in one event handler (is there a reason you're binding 2 different handlers to the same event?):
$("a.false").click(function(e) {
$(this).closest("tr.hide").hide("slow");
var main_id = this.title;
var display = "false";
e.preventDefault();
$.ajax({
url: "/useradminpage",
data: {main_id: main_id, display: display},
success: function(data) {
display_false();
alert("4 - returned");
}
});
});
Your problem currently is that main_id and display are not in the scope of the second event listener, so will be undefined (and they shouldn't be quoted, otherwise you're just passing in strings). As you're passing in a data object to the ajax function, you don't really need to add the query string to the URL either.
Aside from that, when you assign a value to main_id, you're using a.title. In this case a is undefined, and you will need to use this, which will be a reference to the clicked element.
I suspect that I might be missing something, but I suspect that your problem is using a.title instead of this.title:
$("a.false").click(function(e) {
$(this).closest("tr.hide").hide("slow");
var main_id = this.title; // or you could use the jQuery object approach: $(this).attr('title') instead
var display = "false";
e.preventDefault();
});
The problem in your original approach is that a would be parsed as a variable, which hasn't been assigned a value, nor has it been declared, so that it would return undefined or null (at best). Within the scope of the each() method, you're iterating over individual nodes; so to access the properties/attributes of that node use this.
To access any attribute of a DOM element through jQuery, you can use the .attr() function.
In your particular case you would do.
var main_id = $(this).attr('title');

Categories

Resources