On a webpage that has a list of categories, and each category title is linked in this format: http://localhost/admin/category/unpublish/2
I wrote the following js code, trying to capture the url and the segments 'unpublish' (action) and '2' (id), and need to send the request to http://localhost/admin/category
$('#statusChanges a').click(function(evt) { // use the click event of hyperlinks
evt.preventDefault();
var url = $(location).attr('href');
// var action = url.segment(3); /*JS console complains that url.segment() method undefined! */
// var id = url.segment(4);
$.ajax({
type: "GET",
url: $(location).attr('href'),
dat: '',
/* do I need to fill the data with json data: {"action": "unpublish, "id": 2 } ? but I don't know how to get the segments */
success: function(data) {
$('.statusSuccess').text('success!');
},
error: function(data) {
$('.statusSuccess').text('error!');
}
});
}); // end of status change
Try this
var url = $(location).attr('href').split("/").splice(0, 5).join("/");
Update Answer:
User this object to get current anchor link see below
$(this).attr('href')
Split the URL into segments first:
var segments = url.split( '/' );
var action = segments[3];
var id = segments[4];
I think you can use split. Then you can have an array to work with from which you can get the action and id.
Related
what I have at the minute works for the first URL test, however, I don't know how to get it to test the second URL, should the first one not exist.
var str = document.title.replace(/ | My Site/i, '');
var title = str.replace(/ /g, '-');
var finish = title.toLowerCase();
var banner = finish.split('-', 1)[0]
var address = "http://example.com/images/" + finish + ".jpg";
var banneraddress = "http://example.com/images/" + banner + "-banner.jpg";
$.ajax({
type: 'HEAD',
url: address,
success: function() {
// Primary URL exists
document.getElementById("TRY").src = address;
},
error: function() {
$.ajax({
type: 'HEAD',
url: banneraddress,
success: function() {
// Secondary URL exists
document.getElementById("TRY").src = banneraddress;
},
error: function() {
// Both failed
null
}
});
}
});
What needs to happen is if the user loads a page and /images/page-title.jpg exists, it will add that src to the the images with the ID "TRY".
If that test fails, if /images/page-banner.jpg exists add that src to the images
And, for now, if neither work do nothing.
Just move your AJAX logic to separate function, later you can ask the function if both images exists, and if they, you can change the src attribute of your image.
E.g.
if( checkIfImageExists(address) && checkIfImageExists(banner_address) ) {
// both images exists, change src attribute
} else {
// both images do not exists, do something else
}
You should modify your success and error callbacks to return true or false.
I'm attempting to first make an AJAX request from a social API and append the results with a button inside the div that will save the corresponding item in the array to my firebase database. For example,
I have my AJAX request - I cut out about 75% of the actual code that isn't needed for the question.
$.ajax({
type : 'GET',
url : url,
dataType : "jsonp",
cache: false,
success : function(data){
console.debug(data);
vids = data.response.items;
for(var i in vids) {
dataTitle = vids[i].title;
ncode = "<div class='tile'><img src='"+ vids[i].title "'/></a><button class='btn' type='button' onClick='saveToDatabase()'>Save</button></div>";
$('#content').append( ncode )
And then I have my function that I want to save the 'title' of the object the button was appended with to the firebase database.
var dataTitle;
function saveToDatabase() {
ref.push({
title: dataTitle
});
}
The issue is that when the button is clicked it posts a random title from inside the array instead of the title of the item the button was appended with... How can I bind the buttons function to the correct dataTitle?
I'm not sure if that makes sense so please let me know if clarification is needed. Thanks in advance for any help you can provide!
This fails because you are iterating the entire list and assigning them to a global variable. The result is not random at all--it's the last item in the list, which was the last to be assigned to the globar variable.
Try using jQuery rather than writing your own DOM events, and utilize a closure to reference the video title.
function saveToDatabase(dataTitle) {
ref.push({
title: dataTitle
});
}
$.ajax({
type : 'GET',
url : url,
dataType : "jsonp",
cache: false,
success : function(data) {
console.debug(data); // console.debug not supported in all (any?) versions of IE
buildVideoList(data.response.items);
}
});
function buildVideoList(vids) {
$.each(vids, function(vid) {
var $img = $('<img></img>');
$img.attr('src', sanitize(vid.title));
var $button = $('<button class="btn">Save</button>');
$button.click(saveToDatabase.bind(null, vid.title));
$('<div class="tile"></div>')
.append($img)
.append($button)
.appendTo('#content');
});
}
// rudimentary and possibly ineffective, just here to
// point out that it is necessary
function sanitize(url) {
return url.replace(/[<>'"]/, '');
}
I actually just ended up passing the index to the function by creating a global array like so. It seems to be working fine... any reason I shouldn't do it this way?
var vids = []; //global
function foo() {
$.ajax({
type : 'GET',
url : url,
dataType : "jsonp",
cache: false,
success : function(data){
console.debug(data);
vids = data.response.items;
for(var i in vids) {
ncode = "<div class='tile'><img src='"+ vids[i].title "'/></a><button class='btn' type='button' onClick='saveToDatabase('+i+')'>Save</button></div>";
$('#content').append( ncode )
} //end ajax function
function saveToDatabase(i) {
ref.push({
title: vids[i].title
});
}
I have ajax code in my javascript file as follows:
// Default settings for Ajax requests
$.ajaxSetup({
type: 'POST',
url: path + '/relay.php'+ '?curr=' + currency + "&ver=" + Math.random(),
success: function(response) {
// Refresh the cart display after a successful Ajax request
container.html(response);
$('#jcart-buttons').remove();
},
.......
The above will post as (in firebug):
POST http://www.myshop.com/cart/relay.php?curr=EUR&ver=0.5750630930208085
I have a remove function as follows:
function remove(link) {
// Get the query string of the link that was clicked
var queryString = link.attr('href');
queryString = queryString.split('=');
// The id of the item to remove
var removeId = queryString[1];
// Remove the item and refresh cart display
$.ajax({
type: 'GET',
data: {
"jcartRemove": removeId,
"jcartIsCheckout": isCheckout
}
});
}
The remove will display as follows(firebug)
GET http://www.myshop.com/cart/relay.php?curr=EUR&ver=0.5750630&jcartRemove=5
I need to remove the curr variable too...
How can i do it in my remove link code above ???
CHANGE AJAX METHOD BECAUSE YOU ARE SENDING PARAMETERS FROM URL (this is get method to send parameters)
$.ajaxSetup({
type: 'GET',
url: path + '/relay.php'+ '?curr=' + currency + "&ver=" + Math.random(),
success: function(response) {
// Refresh the cart display after a successful Ajax request
container.html(response);
$('#jcart-buttons').remove();
},
$.ajax({
type: 'POST',
data: {
"jcartRemove": removeId,
"jcartIsCheckout": isCheckout
}
});
HERE ARE THE LINKS:
LINK AJAX
LINK POST
LINK GET
1.You need to change the $.ajaxSetup method, the url used in this method i.e
url: path + '/relay.php'+ '?curr=' + currency + "&ver=" + Math.random()
contains curr and ver parameters but you don't need curr variable in Remove Function So you need to remove curr varible from this url and add curr variable only in particular ajax calls where it will be required.
2.Like by default your url should be
url: path + '/relay.php?ver=' + Math.random()
and add curr varible in your subsequent ajax calls using data parameter.
3.Now, when you call remove function default query string will not contain curr parameter.
function remove(link) {
// Get the query string of the link that was clicked
var queryString = link.attr('href');
queryString = queryString.split('=');
// The id of the item to remove
var removeId = queryString[1];
// Remove the item and refresh cart display
$.ajax({
type: 'GET',
data: {
"jcartRemove": removeId,
"jcartIsCheckout": isCheckout
}
});
}
GET http://www.myshop.com/cart/relay.php?ver=0.5750630&jcartRemove=5&jcartIsCheckout=true
in case isCheckout=true
GET http://www.myshop.com/cart/relay.php?ver=0.5750630&jcartRemove=5&jcartIsCheckout=false
in case isCheckout=false
In case you have any queries, do post.
I am pretty sure this is not so complicated but I have been for hours trying to figure out how to catch the id of this dynamically generated anchor tags.
What I do in my code is that everytime a text input changes, theres an ajax request that goes to a php file and returns me a json array with the prices then I render this results of search in buttons that will be clickable to do other types of request but so far here's where I'm stuck.
heres's the code that loops through the array and renders this buttons (NOTE:The Id of the buttons are variables rendered by the function too.
$.ajax({
type: "POST",
url: "php/get_products.php",
data: {query:prod_qry},
success: function(data){
$('#loader_s').hide();
var jsarray = JSON.parse(data);
var length = jsarray.length;
for(i=0;i<jsarray.length;i++){
var index1 = i;
var index2 = Number(i++) + 1;
var index3 = Number(i++) + 2;
$('#modal-bod').append('<a onclick="renderProds();" class="btn btn-default-item prod_sel" style="margin-top:10px;" id="'+index3+'" data-dismiss="modal">'+jsarray[index1]+' <span class="pull-right" st>lps. '+jsarray[index2]+'</span></a>');
}
}
Then here's the function renderProds()
function renderProds(){
var id = $(this).attr('id');
alert(id);
}
the alert is just to try and catch the values for testing purposes, but what really goes there is another Ajax request.
The only thing I get here is that the var Id is undefined...
You can pass object like
function renderProds(obj) {
var id = obj.id;
alert(id);
}
Pass invoker object like
onclick="renderProds(this);"
I would do :
onclick="renderProds(this);"
function renderProds(that){
var id = that.id;
alert(id);
}
You use jQuery.. so USE jQuery !
Ajax can do the JSON.parse for you with just dataType: "json".
The inline onclick is bad practice.
Move the success function to make your code more readable.
$.ajax({
type: "POST",
url: "php/get_products.php",
data: {query:prod_qry},
dataType : 'json',
success: productsUpdate
});
function renderProds(event){
var id = $(event.target).attr("id");
alert("Id is:"+id);
}
function productUpdate(data){
$('#loader_s').hide();
for(i=0;i<data.length;i++){
var link = $('<a>....</a>');
link.click(renderProds);
$('#modal-bod').append(link);
}
}
Now, this is readable.
Complete the link creation with your code, without the onclick, remove the inline css and use a real css selector and finally, check this ugly Number(i++)+ .... it looks so bad.
I'm currently working on a bit of jQuery that will allow users to make an AJAX call from a text link. This is no problem but the text link has parameters that I need to send to the AJAX request in order for it to execute properly.
My text link looks something like this:
Click here
Here is my jQuery:
function getUrlParam(name)
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
/* Let's create a function that will allow us to vote on the hosts */
function hostVote() {
/* These variables are used to determine the button clicked */
var affiliate = getUrlParam('affiliate');
var voteType = getUrlParam('voteType');
$.ajax({
cache: false,
type: "POST",
url: "/php/hostvote.php",
data: "affilate=" + affiliate + "&voteType=" + voteType +"",
success: voteSubmitted
});
function voteSubmitted() {
alert('Thanks for voting');
$(this).addClass('yes');
}
return false;
};
$("a.vote").click(hostVote);
The trouble with this code is I can't submit the link to put any parameters in the url before the function is executed, resulting in empty affiliate and voteType vars.
Can anyone help?
A better approach would be to store the data you need in the data-* attribute of the link. This would make it much easier to retrieve the corresponding data. Here's a simple example of how it would work.
Click here
$("a.vote").click(function(e){
var affiliate = $(this).data('affiliate');
var voteType = $(this).data('voteType');
// do your ajax call here
e.preventDefault();
});
Instead of -
var results = regex.exec( window.location.href );
could you do -
var results = regex.exec($("a.vote").attr('href'));
and parse the variables directly from your link?