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.
Related
I have an ajax function that updates every second some value on page, I want to update it only when the script is working, because to not request a value that is the same.
The script is updating this value, and ajax is refreshing it on website, but when script is not working, my ajax is requesting the value. How to make it work only when the script is working?
var interval = 1000;
function update() {
$.ajax({
type: 'GET',
url: 'http://localhost:8000/api/updating',
headers : {'Authorization': "Token "+ token,},
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
$('#points_a').html(data)// first set the value
},
complete: function (data) {
// Schedule the next
setTimeout(update, interval);
}
});
}
setTimeout(update, interval);
This is script in python view, Django:
def task(userid, seconds_for_thirtydays=0):
if(seconds_for_thirtydays < 2592000):
p_a = Wallet.objects.filter(name__id=userid).values("points").first()['points']
add = p_a + 1
result = Wallet.objects.filter(name__id=userid).update(points=add)
seconds_for_thirtydays = seconds_for_thirtydays + 1
time.sleep(1)
task(userid)
else:
return
The thing that I want to make is: When the value is not changing(the script is not working), then this ajax won't work and won't make requests, is it possible?
How may I take the input from a textbox in HTML, using autocomplete, in order to feed that data into my url parameter via ajax? My goal is to output the data into HTML. The type of data that I am querying is an XML API.
This is my html:
<input id="data_from_autocomplete">
<button type="submit>Submit</button>
This is my jQuery:
$.ajax({
type: "GET",
url: "http://www.something" + data_from_autocomplete + ".com",
dataType: "xml",
success: parse
});
Use
var param = $("#data_from_autocomplete").val();
var url = "http://www.something" + encodeURIComponent(param) + ".com";
//call your ajax
[update]
If you need to pass the value of the search field as parameter, just pass it in the data parameter of the ajax call:
var city = $("#data_from_autocomplete").val();
var state = "wa";
$.ajax({
url : "https://www.zillow.com/webservice/GetRegionChildren.htm",
data : {
"zws-id": /*your zws-id goes here*/,
state : state,
city: city
},
success: function(response) {
//process your response here
}
});
I do not have much grip on javascript and having problemswith it.
My data is coming from a server and the user when clicks on an item is redirected to a new page which has that items all details. The problem is when a user clicks on an item,how to send the data from one page to the next.
No php is used. javascript ajax jquery used and data coming from json
this is format and when user clicks on play button a new age should be displayed where the data is to be shown to user.
Template={"Big_Display_Template": '{{#items}}<input type="hidden" name="guid" value="{{id}}"><div class="hero"
style="background-image:url({{videoStillURL}})"><div class="hero-content"><br>
<h2>{{name}}</h2> <p>{{shortDescription}}</p> <div class="hero-links"><a href="Watch_Live.html"
onclick="PassDataToNextPage({{name}},{{id}},{{shortDescription}});">
Play<span class="genericon genericon-play"> </span></a></div>
<div class="hero-links-fav"><a href="#">Favourite<span class="genericon genericon-fav">
</span></a></div></div></div>{{/items}}'
}
This is my function PassDataToNextPage()
function PassDataToNextPage(name,guid,Description)
{
var url = 'Watch_Live.html';
$.ajax({
url: url,
type: 'POST',
data: 'name=' + name + '&guid=' + guid + '&shortDescription=' + Description,
success: function(result) {
dataUrl=data;
}
});
return window.location+"/"+dataUrl;
}
I know this is wrong but how to make it right? thanks a lot in advance
The problem lies in the return window.location+"/"+dataUrl; line: the redirect should be done inside the success function because it will be called when the request is completed:
function PassDataToNextPage(name,guid,Description)
{
var url = 'Watch_Live.html';
$.ajax({
url: url,
type: 'POST',
data: 'name=' + name + '&guid=' + guid + '&shortDescription=' + Description,
success: function(result) {
dataUrl = data;
window.location = window.location + "/" + dataUrl;
}
});
}
In the template you must add return false in the onclick attribute to avoid the browser following the link interrupting your handler:
<a href="Watch_Live.html" onclick="PassDataToNextPage({{name}},{{id}},{{shortDescription}});return false">
You can pass key:value data via url GET parameters.
For example: if you want to pass data to this page: Watch_Live.html, you can do something like:
<button>Pass data</button>
To parse the parametesr in the other page, read this SO answer to a similar question.
https://stackoverflow.com/a/901144/4440845
Look like you want to pass data and go to the next page with the data, you don't need ajax to achieve. Simply:
function PassDataToNextPage(name,guid,Description)
{
var url = 'Watch_Live.html';
window.location.href = url + '?name=' + name + '&guid=' + guid + '&shortDescription=' + Description;
}
Comment:
You can use:
< a onclick="PassDataToNextPage({{name}},{{id}},{{shortDescription}});">Play< /a>
The click event will be handled by the function PassDataToNextPage in onclick.
Assuming you use PHP in your next page, you can fetch the data
$name = $_GET['name'];
$guid = $_GET['guid'];
$shortDesc = $_GET['shortDescription'];
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
});
}
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.