jquery losing value of $(this) on ajax request [duplicate] - javascript

This question already has answers here:
Using selectors and $(this) in Jquery Ajax
(2 answers)
Closed 7 years ago.
Hi I am using jquery to make an ajax request to the database to add and remove favourites from the database. This works fine however I want to replace part of the href in the anchor link so that a user can add/remove again if required without refreshing the page e.g. the link is built as so http://article.local/favourite/delete/uniqueid therefore I need to replace the 'delete' with add and vise versa for the add favourite button. However I can't use the class name otherwise this will apply to all of the classes rather than the one clicked at that time.
$( ".remove-favourite" ).click(function(e) {
e.preventDefault();
var favform = $(this).parent('.fav-form-contents');
$(favform).append("<img src='/images/loading.gif' class='form-loader' class='loading-icon'/>");
$.ajax({
type : "POST",
cache : false,
url : $(this).attr('href'),
data : $(this).serialize(),
success : function(data) {
$('.loading-icon').hide();
$(this).attr('href').replace(/delete/, 'add');
$(this).removeClass('remove-favourite').addClass('add-favourite');
}
})
}); // end click function
However the error message I get back is as follows:
Uncaught TypeError: Cannot read property 'replace' of undefined
This suggests that it has lost the current item, any ideas as to what I am doing wrong??

You need to preserve $(this) in a variable for the callback like
var $link = $(this);
$.ajax({
type : "POST",
cache : false,
url : $(this).attr('href'),
data : $(this).serialize(),
success : function(data) {
$('.loading-icon').hide();
$link.attr('href').replace(/delete/, 'add');
$link.removeClass('remove-favourite').addClass('add-favourite');
}
})
this itself will have changed because the execution context of the success callback in $.ajax is different then when you called $.ajax.

make this as global means with in function
like var _this = $(this) use in ajax suuceess

this inside ajax is related to xhr object.
Use context option of ajax,
This object will be the context of all Ajax-related callbacks. By default, the context is an object that represents the Ajax settings
$.ajax({
context:this,
....

Related

How do I get the original data provided to a ajax call in the ajax callback? [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 3 years ago.
Basically, I'm looping through an array of images. If the image doesn't have a source, it will make a ajax call to pixabay to find an image of the item and setting the URL to the src of the image element. However, calling "this" will reference the ajax call instead of the image element. My approach right now is to get the element's element ID from the "data" in the "options" but that isn't working. I also tried to call "imageOf" from inside the success callback but that doesn't work either.
$("img").each(function() {
if (!$(this).attr("src")) {
var imageOf = $(this).attr("imageOf");
//get imageURL via ajax call
var pixabayAPI = "https://pixabay.com/api/";
$.ajax(pixabayAPI, {
method: "GET",
async: false,
dataType: "json",
data: {
key: "...",
q: imageOf,
category: "food"
},
success: function(result, status, jqXHR) {
var images = result.hits;
if (images.length > 0){
console.log(images[0].webformatURL);
$(this).attr("src", images[0].webformatURL);
// "this" becomes the ajax call when I want to get the image element instead
};
},
error: function(e) {
console.log(e);
}
});
}
});
GET requests doesn't have data - which basically is the body of the requests.
So for this solution the best is to provide API key inside URL like this:
https://pixabay.com/api/?key=${key}&q=${imageOf}&image_type=photo
Don't forgt to put this stirng into backticks (`) since it's interpolated string with variable key and imageOf
Then in response yo ucan go through just like their API documentation says: https://pixabay.com/api/docs/

JQuery - Send inputs via ajax (which were obtained by ajax)

I have an application that after performing a search, returns me multiple "fieldsets" with some hidden inputs (via AJAX!).
I want to use these inputs to send information to the server (again) via AJAX.
The names of these inputs are automatically listed with a prefix:
"video_url_1", "video_url_2", etc.
When the user clicks the button, the value of "video_url_1" or "video_url_2" will be sent via AJAX depending on the button to which it has clicked. To solve this I got the name of the button that was clicked and then I cut the name so that I only have one number, this number I put in a variable and then use it in the "data" section of AJAX.
I did the test by sending a locally stored input and it worked but when trying to send the inputs that were previously obtained by an ajax, it does not work.
What can be wrong? This is my code:
$(document).ajaxComplete(function(){
$('a.report_video').click(function() {
var idbutton = $(this).attr('id');
var idreport = idbutton.replace('report_video_', '');
//I'm still not using these variables, can they be used to pass the input data to ajax?
var videourl = $("#video_url_" + idreport).val();
var videoid = $("#video_id_" + idreport).val();
var videoserver = $("#server").val();
///////////
$.ajax({
type : 'POST',
url : 'https://example.com/script/script.php',
data : $($("#video_url_" + idreport)).serialize(), //It doesn't work
//For example, data: $("#server").serialize()
//Work fine, this input is stored locally.
beforeSend: function(){
$('#video_report_' + idreport).html('<img src="'+pluginUrl+'./assets/img/loading.svg" />');
}
}).done(function(data) {
$('#video_report_' + idreport).html(data);
});
return false;
});
});
Edit:
I just did some tests as suggested by Kevin B and I see that the problem I have is in the syntax when trying to send two dynamic ID's by Ajax.
The problem is that I do not know how to write them correctly, I know that is the problem because when I tried to send them separately they did work...
data : $($("#video_id_" + idreport), $("#video_url_" + idreport)).serialize(),
I'm not sure I completely understand your problem, but this might help.
You call your second AJAX call in the .success() method of the first AJAX call. Essentially chaining the responses.
$('#btn').click(function() {
$.ajax({
type: "POST",
url: 'someURL',
data: someData
}).done(function(firstCallData) {
// This OPTIONAL method fires when the AJAC call succeeded
// You can also put another AJAX call in here with the data returned from the first call
$.ajax({
type: "POST",
url: 'someURL',
data: firstCallData
}).done(function(data) {
// Do something with second AJAX call with data
}).fail(function(data) {
// Second AJAX call failed, handle error
});
}).fail(function(data) {
// This OPTIONAL method fires when the first response failed
}).always(function(data) {
// This OPTIONAL method fires regardless if the first call succeeded or failed.
});
});

Jeditable sends no variables

I'm trying to send a variable, intent, alongside the default variables of jeditable. According to the documentation, the default should send the variables id and value (I've confirmed that every element I'm using jeditable with has a valid id). I'm using the following code:
jedit-config.js
$(document).ready(function () {
$('.jedit').each(function() {
var $this = $(this);
$this.editable('service.php', {
loadtype : 'GET',
onblur : 'submit',
submitdata : { 'intent' : 1 }
});
});
});
service.php
$elID = $_GET['id'];
$newText = $_GET['value'];
$intent = $_GET['intent'];
if ($intent == 1) {
// Do something. Never called.
}
echo $newText;
Example of element that jeditable is used on:
<li id='listend' class='jedit'>Text here</li>
None of my variables (id, value or intent) reach service.php. They're all blank. I've sent variables to service.php using the following test and it receives it correctly:
$.ajax({
type: "GET",
url: "service.php",
data: "intent=1",
success: function(result){
//
}
});
Not sure what I'm doing wrong?
Update:
Looks like variables are being sent by POST and not GET. loadtype : 'GET' appears to only apply when used in conjunction with the loadurl option. I'm seeing if there's a method to use GET with the original url.
As per my update, it looks like there's no straightforward means to send data to a url from jeditable by GET, only POST if not using a loardurl option.
The answer is to switch to using POST or integrate a method that uses a loadurl option. Without this option, loadtype : 'GET' does not switch the data submission type to GET.

Ajax response not working as expected from PHP

I am calling the JS function cancelAppointment on button click, I can confirm that the function is running okay as the first alert is shown.
I have followed many guides to try and get this to work but they are yielding no results.
At the moment the success message is not being showed and the row is not being deleted. I can confirm the PHP script works fine.
the function is as below:
<head>
<script>
//Making the call to ajax this is encased in a function so it is not called pre-maturely
function deleteAppointment()
{
jQuery(document).ready(function(){
alert("Trying to run!");
$.ajax({
type : "POST",
url : "http://www.website.com/delete_appointment.php",
//data : "",
success : function(response) {
//Success
alert("Deleted");
}
});
});
}
</script>
For the moment, until I get the ajax to work the PHP contains PDO, that will delete from both the Appointments & AppointmentLines table with an ID of 1000. I will parse this in once this first part works.
In Wordpress the jQuery library included in the noConflict() mode, so the global $ shortcut for jQuery is not available, see more details here.
To make it work change $ to jQuery:
function deleteAppointment()
{
jQuery.ajax({
type : "POST",
url : "http://www.website.com/delete_appointment.php",
success : function(response) {
alert("Deleted");
}
});
}
You need to define what response the Ajax method is expecting to receive.
Make the response either 'text' (as shown in the example bellow) or make the response 'json'. You just add 'dataType: "text"' as a setting to the ajax call.
$.ajax({
type : "POST",
url : "http://www.website.com/delete_appointment.php",
dataType : "text",
success : function(response) {
//Success
alert("Deleted");
}
});
Currently you're your success method is waiting for the value of "response" to be returned however you are not defining what it is.
EDIT: I was corrected that it should be dataType not data for the setting I was originally talking about.
I found the answer,
Because I was using wordpress you must use jQuery in place of $ I needed to wrap this in a DOM function with $ defined so that jQuery would understand $
I kept the data argument commented in the end.
This issue was caused due to wordpress requiring slightly different syntax when calling a jQuery function. Thanks for your help everyone.

Value attribute of html element is undefined

Why is name undefined?
$('#langs li').click(function(){
var name = $(this).attr('value');
$.ajax({
type: "POST",
url:'test.php',
data: 'name='+name,
success:function(raspuns){
//$('#content1').html(raspuns);
var ras = raspuns;
$.ajax({
type: "POST",
url: "index.php",
data: 'ras='+ras;
)};
}
});
});
You can check a few things:
make sure you have data before sending. you have value attribute on li? or if you want to get li contents, use html() or txt(). But probably you want to get input field value inside li?. then use $(this).find("input").val() if you have just one input inside.
Then others to check:
1) Visit http://example.com/test.php to make sure it echoes the response correctly. You may have error in php or the link may not be accessible.
2) Your url is like this: http://example.com/test.php ? It is also fine if you have a virtual host in your local machine like http://example.local/test.php. But it will not work if you have something like
http://localhost/mysite/test.php
unless you correct your path in ajax call to a full link.
3) Make sure your javascript doesnt fail before sending. I mean, are you able to do alert(name) ? You can also use beforeSend() above success to check if you are ending data correctly.
4) Make sure you are not trying to make a cross domain ajax request as you can't do so with POST.
5) May try using "/test.php" instead of "test.php" although it wouldn't be the problem, I think.
You can also use console to see what is going on.
If what you mean is that raspuns seems to be undefined, maybe it's because you did not echo your response from test.php?
test.php
...
echo 'this is my response';
AJAX call
$.ajax({
...
success: function(raspuns) {
// raspuns == 'this is my response'
}
});
And also, if you're passing POST data, I think it would be better if you pass a JSON object, like so:
$.ajax({
url: 'test.php',
type: 'POST',
data: {name: name},
...
});
li elements don't support a value attribute. Perhaps you're looking for an input or the contents of li via .html().
See in this demo that name is undefined: http://jsbin.com/IzOXiJOZ/2/edit

Categories