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.
Related
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.
I would like to have an alert whenever people start typing in the text box. It will return "Data Saved: " + my msg that's in the test.php folder.
$("#textbox").on('change keyup paste', function() {
$.ajax({
method: "POST",
url: "test.php",
data: { content: $("#textbox").val() }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
I've tried changing "method" to "type".
Using .serialize().
Using success: function
I'm not sure what the problem is. Thank you!
Edit:
Added an error code. So far no error messages on console for this.
$.ajax({
method: "POST",
url: "test.php",
data: { content: $("#textbox").val() }
})
error: function (request, error) {
alert("An error occurred");
},
success: function (response) {
if (response == 'OK') {
$("#diary").val()
} else {
alert("An error occurred");
}
From your comment you are getting the following error:
$.ajax is not a function at HTMLTextAreaElement. (loggedinpage.php:92) at HTMLTextAreaElement.dispatch (jquery-3.1.1.slim.min.js:3) at HTMLTextAreaElement.q.handle (jquery-3.1.1.slim.min.js:3)
The error is telling you that the code cannot find the $.ajax() function anywhere in order to execute it.
At the same time, the message gives away the fact that you are using jQuery Slim. This cut-down version of the library does not include the $.ajax() function, among other things. You need to use the full version of jQuery.
Details in the latest (or any recent) release notes (in the "Slim build" section): https://blog.jquery.com/2017/03/20/jquery-3-2-1-now-available/
As a side note, I'm surprised that you want to show an alert every single time a user types a character into the textbox. I predict that this will quickly get very annoying for users. Maybe just showing a message inside a div nearby (which doesn't steal the focus and stop them typing) would be better. I'd also question whether it's really necessary to save the data to to the server every time a character is entered? If the user types quite a lot it will trigger off dozens of ajax requests. Your inclusion of the "keyup" is the reason for this. Perhaps have a rethink of exactly how you want this to work, and why.
I'm pretty much a complete beginner at javascript and jQuery, so please bear with me.
I have a Spark-API running, and a web front-end that uses it through ajax calls.
I'm trying to call this function
function getSpotifyURL(ms, name) {
$.ajax({
url: "http://localhost:8081/playlist?ms=" + ms + "&name=" + name,
dataType: "json",
})
.done(function( data ) {
console.log(data);
})
}
The method is placed outside of:
$(document).ready(function() {
The reason it's outside is that I get an error upon calling it saying it's "undefined" if it's within $(document).ready.
The Spark-method is supposed to return a String (and it does when you try it directly through the browser).
The way I'm calling the getSpotifyURL-method is through a html button's "onclick". Like this:
<a href='#' onclick='getSpotifyURL(" + data[i].duration + ",\"" + data[i].destination + "\")'>Create Spotify playlist for this trip</a>"
The problem:
The .done-block does nothing in my code. Nothing is printed to console.
What I've tried:
Using "success" within the ajax part instead of .done
Placing the function with $(document).ready(function() { ... }
I understand that you might need more information to be able to help me, but I'm not sure what else information to provide right now. So if there's something you need to know, just ask.
Ideas?
SOLVED!
I'm a dumb person and forgot to remove dataType: "json", as the Spark-server in this instance returned a String, not a json object. Anyway, thanks for your input everybody. Much appreciated.
I think the problem is when you bind your function onclick. There is a syntax error, as you can see on the browser console
function getSpotifyURL(ms, name) {
console.log("http://localhost:8081/playlist?ms=" + ms + "&name=" + name);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href='#' onclick='getSpotifyURL(" + data[i].duration + ",\"" + data[i].destination + "\")'>Create Spotify playlist for this trip</a>"
I guess data is a variable, so you should call it without brackets
<a href='#' onclick='getSpotifyURL(data[i].duration, data[i].destination)'>Create Spotify playlist for this trip</a>
The reason you are getting undefined method when you are placing the function inside the $(document).ready(function() { ... }); call is because you are using the onclick attribute to call the function. $(document).ready(...) is not in global context as to where you onclick attribute is, and would therefore not recognize it from within the document.ready resulting in your undefined method error.
When sending your Ajax request, you also need to specify a type of request (GET or POST) that you are making. I would also suggest restructuring your ajax call to look more like #Moe's answer.
If you want to get it inside the DOM, consider doing the following:
HTML
<!-- I gave the link a class name and removed the onclick= attribute -->
Create Spotify playlist for this trip
JavaScript
$(document).ready(function() {
// I gave the <a> link a click handler
$(".create-spotify-playist").on("click", function(e) {
e.preventDefault(); // prevents link from requesting
var ms = ?? //I'm not sure where you're getting your parameters from,
var name = ?? //so you will probably have to figure out how to get those in here yourself
$.ajax({
type: "GET",
url: "http://localhost:8081/playlist",
data: { ms: ms, name: name },
success: function(data) {
console.log("Success: " + data);
},
error: function(data) {
console.log("Error: " + data);
}
});
});
});
I gave the link a click handler and placed it inside the $(document).ready, and by removing the onclick attribute from earlier, it can now be triggered from inside $(document).ready.
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');
});
});
});
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'