How can I post my href value in an ajax function? - javascript

I am trying to create an action that allows me to post an anchor href with an ajax call. Firstly the anchor tag is created with a backend set up so it cannot be inside a form etc so that is not going to work.
Here is the markup for the button, the href is added dynamically with js:
<a class="js-add-to-cart button buying-options buy-button" data-products-in-cart="<?= $products_in_cart ?>">
Select a size
</a>
I have currently got this code working which posts the anchor:
jQuery(function(){
jQuery('a.buy-button').click(function(event) {
event.preventDefault();
jQuery.ajax({
url: jQuery(this).attr('href'),
type: 'POST',
async: true,
beforeSend: function(){
jQuery('#result').hide();
jQuery('#ajax-loader').show();
},
error: function(xhr, status, thrown){
alert(xhr + ',' + status+ ',' + thrown);
},
complete: function(){
jQuery('#ajax-loader').hide();
},
success: function(data) {
jQuery('#result').empty().append(data);
jQuery('#result').fadeIn('slow');
}
});
});
});
It works but my only issue is that it basically does a get request and in the header network response I get this:
This does not post the add to cart url and make the product added to cart.
Does anyone know how this can be done?
Cheers,
Mark

try to see if the POST-action is actually triggered within the PHP code. It seems like it should be working.
Also the 'async' parameter is superfluous since you're already calling an A-jax function

perhaps using the .post() shorthand will help you (and also clean up your code).
I'm assuming that you are not using the $ alias for jQuery because you are not aware of it, and not because of any conflict issues.
$(function(){
$('a.buy-button').click(function(event) {
event.preventDefault();
$('#result').hide();
$('#ajax-loader').show();
$.post($(this).attr('href'), function (data) {
$('#ajax-loader').hide();
$('#result').empty().append(data);
$('#result').fadeIn('slow');
});
});
});

Related

How do I just run a php script with Ajax (no returns)

I'm trying to run a php script with ajax. All I want for it to do is just run the script, I don't want any echos or anything. Is there a way to do this. Here is what I've tried:
$('button')[1].click(function () {
$.ajax({
method: 'get',
url: 'like.php',
data: {
id: $('button')[1].id
},
success: function(data) {
console.log(data);
}
});
I thought that this would just run like.php with the get data I sent it but it is not working. I know that the php script works because when I type in the url with the id parameter manually it works.
This will clean up and work better for your "fire n forget" like buttons. Add a special class to only the buttons you want to do this:
<button class="like-it">I Likes!</button>
Then the jquery handler can be this:
$(document).ready(function() {
$('body').on('click','.like-it',function(e){
e.preventDefault(); // stops the button from doing something else
$.get( 'like.php',
{ id : $(this).attr('id') },
function(response) { console.log(response); }
);
});
});
You can test if your PHP is doing something, by simply returning something and inspecting the result in your console tab of the browser devtools. Since you are ignoring the result, you can echo anything for debugging in devtools. Then comment out the echo when you go to live.

PHP code and JQuery within onclick event [duplicate]

I have a link, which links to domain.com , when a person clicks, I want it to do an ajax call to counter.php and post 2 variables to it, so it can add 1 to the views for that link.
I have a link:
Link Title
How would I do this with jquery?
EDIT:
I tried something like this
function addHit(str, partNumber){
$.get("counter.php", { version: str, part: partNumber })
}
It seems to work, but in firebug, the request never completes... it just does that "working..." animation. counter.php echos out some text when its done (doesnt need to show up anywhere).
From the jQuery documentation: http://api.jquery.com/jQuery.ajax/
function addHit(data1, data2)
{
$.ajax({
type: "POST",
url: "http://domain.com/counter.php",
data: "var1=data1&var2=data2",
success: function(msg){
alert( "Data Saved: " + msg ); //Anything you want
}
});
}
You need to add a callback on success
function addHit(str, partNumber){
$.get(
"counter.php",
{
version: str,
part: partNumber
},
function(data){
alert("Data Loaded: " + data);
})
)};
In the case of an anchor, you're leaving the page, so firebug's going to show some weird behavior here as it thinks execution would stop. Unless you're also preventing the default event behavior of the anchor...you're leaving the page and the request (in firebug's view) is discarded.

Jquery caching data-* attributes

In my HTML page , I have the following div:
<div id="notification"></div>
An ajax call add some attribute to that div after receiving successful response.This is what the ajax success does:
$("form").on("submit", function (e) {
e.preventDefault();
$.ajax({
dataType: 'json',
type: "POST",
url: "/dummy/url",
data: {Redacted},
success: function (data) {
$('#notification').attr({'data-status': data['status'], 'data-message': data['message']});
$('#notification').click();
$('#notification').removeAttr("data-status data-message");
}
});
});
The problem is the attributes of #notification does not go away after using removeAttr. I mean it removes the attributes from the page, but remains as cached. Thats why I am getting same data-message on every click though the server returns different data-message.
For example:
In my first ajax call, server returned:
{"status":"success","message":"Invitation sent"}
In this case the #notification triggers and shows me data-message="Invitation Sent". But in my second call server returned:
{"status":"danger","message":"Invitation sending failed"}
But #notification shows data-message="Invitation Sent" again.
Any suggestion for me on this? How can I remove the cached data? Or is there any alternative of what I am doing up there?
Instead of using attribute, use data(). If you had already used data() to read the attribute it is going to be cached as a property of the element.
success: function (data) {
var elementData = {
status: data['status'],
message: data['message']
}
$('#notification').data(elementData);
$('#notification').click();
// not sure why it needs to be removed here
// if it does use `removeData()
}

How to get the id of a dynamically created form in jquery

I am using a Bootstrap modal to display an ASP.Net MVC5 form, the form is inserted dynamically into a div using a jquery ajax call to the relevant controller and then opened.
I need to intercept the submission of the form so I would like to bind to the submit event of the form in jquery but have so far only been able to bind to the submit event of all forms since the dynamic forms are of course not present when the main view is rendered e.g.
$('form').submit(...)
rather than
$('#serverForm').submit(...)
Whilst this sort of works, it has a problem in that I actually have 3 different dynamic forms in this view which can be shown using modal popups, thus I need to do one of 2 things:
A) (ideally)manage to intercept the submit event for each form.
B) in the global form event handler, identify which form has been submitted.
I have tried every option I can imagine to use option A including adding the binding to the code which pops the modal. all without success.
I am currently trying to go with option B so that I can then decide where to post the form. This does at least get called when a form is submitted but my problem is that I cannot get the id or name of the form which has been submitted and thus have no way of knowing which one it is.
I have the following handler:
<script>
$(function () {
$('form').submit(function(e) {
// this is always null
var id = $(this).attr('id');
$.ajax({
url: '#Url.Action("EditServer", "AccountAdmin")',
data: new FormData(this),
...
});
});
});
</script>
Within this handler I have tried the following (plus a few more!) to get the form's id:
this.id
$(this).id
$(this).attr('id');
$(this).prop('id');
I have tried adding the handler after the ajax call to populate the modal like this:
$(".server-link").click(function (event) {
event.preventDefault();
$.ajax({
url: $(this).attr("href"),
cache: false,
type: "GET",
dataType: "html",
success: function (data, textStatus, XMLHttpRequest) {
$('#serverDiv').html(data);
$('#serverModal').modal('show');
$('form').submit(function (e) {
var id = $(this).attr(id);
// test to see if handler called
alert(id);
});
},
error: function (jgXHR, textStatus, errorThrown) {
//The commented out message is full of Html but includes compilation errors etc from the server
//alert('An error occured: ' + jgXHR.responseText);
alert(textStatus + ':' + errorThrown);
}
});
});
It's driving me bonkers! I have tried every combination of ideas from various posts with no joy. I need to post using FormData (in one case at least) because there is a file upload (an image) involved. Any assistance is much appreciated.
The problem is that your JavaScript code is running before the form has actually been added to the page. When using AJAX, you need to run whatever JavaScript you need in the callback:
$.get('/some/url', function (result) {
$('#whatever').html(result);
$('form').submit(function(e) {
var id = $(this).prop('id');
// do whatever with id
});
});
Use this instead:
var id = $(e.target).attr('id');

jQuery Ajax HTTP Request INTO a click function - not working

My question is:
Is it possible to do an Ajax request WITHIN a click function, with jQuery? (see example below), If so, what am I doing wrong? Because I'm not being able to do any request (I'm alerting the data through my success function and nothing is being retrieved).
Thank you very much in advance for any help! :)
function tracker(){
this.saveEntry = function(elementTracked, elementTrackedType){
var mode = "save";
var dataPost = "mode="+mode+"&elementTracked="+elementTracked+"&elementTrackedType="+elementTrackedType;
$.ajax({
type: "POST",
url: 'myURL',
data:dataPost,
success:function(msg){
alert(msg);
},
beforeSend:function(msg){
$("#trackingStatistics").html("Loading...");
}
});
return;
},
this.stopLinksSaveAndContinue = function(){
var fileName;
$("a[rel^='presentation']").click(function(e){
fileName = $(this).attr("rel").substring(13);
this.saveEntry(fileName,"Presentation");
})
}
}
If your anchor is linked with the href attribute, then this may be interrupting your AJAX request. A similar problem was recently discussed in the following Stack Overflow post:
window.location change fails AJAX call
If you really want to stick to using AJAX for link tracking, you may want to do the following:
Link
With the following JavaScript logic:
function tracker(url) {
$.ajax({
type: 'POST',
url: 'tracker_service.php',
data: 'some_argument=value',
success: function(msg) {
window.location = url;
}
});
}
Have you considered the possiblity that the request might be failing. If so, you're never going to hit the alert.
Can you confirm that the beforeSend callback is being fired?
Also, I'm assuming 'myURL' isn't that in your real-world source code?
There may also be something awry in the }, that closes your function.
Im guessing some sort of error is being generated. Try adding
error:function(a,b){
alert(a);
},
After 'success'

Categories

Resources