Get URL parameters from text link and post to AJAX call - javascript

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?

Related

Jquery validation for div

I've set up a page with a bunch of contenteditbale divs, along with some js/ajax functionality so that a user can inline edit.
<div class="inlineEdit" contenteditable="true"></div>
JS is a s such:
$(document).ready(function(){
$('div.inline-edit').blur(function()
{
var pathArray = window.location.pathname.split( '/' );
var segment_3 = pathArray[3];
var editableObj = $(this);
var token_input = $('input.token');
var save_data ={};
var token_name = token_input.attr('name');
save_data['field'] = editableObj.attr('id');
save_data['id'] = editableObj.closest('.inline-id').attr('id');
save_data['editedValue'] = editableObj.text();
$.ajax({
url: segment_3+'/update',
type: 'POST',
data:save_data,
success: function(){
//on success functionality
}
});
});
});
This part all works perfectly grand, all the right fields get updated with the right info. All i need is some way to validate that information before it get to the ajax
I know of JQuery Validation however I'm pretty sure it doesn't work with divs.
Is there a solution or am I stuck/have to change up the divs?
You can create a temporary input box and pass the value through it to check validity. I wrote a function to use HTML5 validation to check for validity.
function validityChecker(value, type) {
type = type?type:'text'
$('body').append('<input id="checkValidity" type="'+type+'" style="display:none;">');
$('#checkValidity').val(value)
validity = $('#checkValidity').val()?$('#checkValidity').val().length>0:false && $('#checkValidity')[0].checkValidity()
$('#checkValidity').remove();
return validity;
}
In your case use like this:
if(validityChecker(save_data['editedValue'], 'number')){ // if you want to check for number
$.ajax({
url: segment_3+'/update',
type: 'POST',
data:save_data,
success: function(){
//on success functionality
}
})
}
Demo:
function validityChecker(value, type) {
type = type?type:'text'
$('body').append('<input id="checkValidity" type="'+type+'" style="display:none;">');
$('#checkValidity').val(value)
validity = $('#checkValidity').val()?$('#checkValidity').val().length>0:false && $('#checkValidity')[0].checkValidity()
$('#checkValidity').remove();
return validity;
}
save_data = 'This is not a number';
alert(validityChecker(save_data, 'number')) // false
alert(validityChecker(save_data, 'text')) // true
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

using jQuery to get url and extract url segments

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.

Combine two functions? Javascript and AJAX api call with throbber

I have a function getShare which creates a script and then calls an url shortener api which then returns a shortened url and sets that link to an input box's value.
Secondly I also have this function which I'm trying get to work with the first. So far I've only been able to .show the loader gif but not hide it when the function is successful.
EDIT: Below is updated code with my original script inside the response.success but i'm get a message in the console saying Failed to load resource and a 404 - the missing url is shown to be http://b1t.co/Site/api/External/MakeUrlWithGet?callback=apiCallback&_=1391704846002
function getShare(url)
{
$('#loader').show(); // show loading...
$.ajax({
dataType: "jsonp",
jsonpCallback:'apiCallback', // this will be send to api as ?callback=apiCallback because this api do not want to work with default $ callback function name
url: 'http://b1t.co/Site/api/External/MakeUrlWithGet',
data: {'url':url},
success: function(response){
$('#loader').hide(); // hide loading...
//respponse = {success: true, url: "http://sdfsdfs", shortUrl: "http://b1t.co/qz"}
if(response.success){
{
var s = document.createElement('script');
var browserUrl = document.location.href;
//alert(browserUrl);
if (browserUrl.indexOf("?") != -1){
browserUrl = browserUrl.split("?");
browserUrl = browserUrl[0];
}
//alert(browserUrl);
var gifUrl = $('#gif_input').value;
var vidUrl = $('#gif_input').value;
//alert(gifUrl + "|" + vidUrl);
url = encodeURIComponent(browserUrl + "?gifVid=" + gifUrl + "|" + vidUrl);
//alert(encodeURIComponent("&"));
s.id = 'dynScript';
s.type='text/javascript';
s.src = "http://b1t.co/Site/api/External/MakeUrlWithGet?callback=resultsCallBack&url=" + url;
document.getElementsByTagName('head')[0].appendChild(s);
}
function resultsCallBack(data)
{
var obj = jQuery.parseJSON(JSON.stringify(data));
$("#input-url").val(obj.shortUrl);
}
}
},
error:function(){
$('#loader').hide();
}
});
}
There's no need to "combine" it.
What someone is suggesting is a regular ajax method. Just move your js scripts you want executed on success, inside the success: callback.
Read more about the ajax method at another answer I did here: https://stackoverflow.com/questions/21285630/writing-my-first-rest-api-call-to-a-webservice-endpoint-post/21286810#21286810 or jQuery's docs: http://api.jquery.com/jQuery.ajax/
Note: to use this you will need jQuery and probably an XDR plugin for the ajax to support < IE 10

How can I capture the attribute id from a dynamically generated html?

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.

how to pass and retrieve Html tags via querystring

Default.aspx
<script type="text/javascript">
$(function() {
$("#add_questions").click(function() {
var question = $("#wmd-output").val();
var option1 = $("#option1").val();
var option2 = $("#option2").val();
var option3 = $("#option3").val();
var option4 = $("#option4").val();
var answer = $("#answer").val();
var paper = $("#txt_subject_id").val();
var dataString = 'question='+ question +'&option1='+option1 +'&option2='+option2 +'&option3='+option3 +'&option4='+option4 +'&answer='+answer+'&paper='+paper;
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="../images/validate.gif" align="absmiddle">');
//alert(dataString)
$.ajax({
type: "GET",
url: "Default2.aspx",
data: dataString,
cache: false,
success: function(html){
$("#display").after(html);
//alert(html)
//document.getElementById('content').value='';
//document.getElementById('content').focus();
$("#flash").hide();
}
});
return false;
});
});
</script>
Let
dataString="question=p>hello</p>&option1=option1&option2=option2&option3=option3&option4=option4&answer=answer&paper=paper"
How could I pass this query string to next page using jquery? I didn't get response from the next page, which means the question=<p>hello</p> not getting the value.
Default2.aspx
Dim question As String
question = Request.QueryString("question")
Response.Write(question)
I also tried encodeUri and encodeURIcomponent.
You say that you try the encodeURIcomponent but I am afraid that you apply it on the full line. You must apply the encodeURIcomponent to each value alone to make it work as:
var dataString = 'question='+ encodeURIcomponent(question) +'&option1='+
encodeURIcomponent(option1) +'&option2='+ encodeURIcomponent(option2) +'&option3='+
encodeURIcomponent(option3) +'&option4='+ encodeURIcomponent(option4) +'&answer='+
encodeURIcomponent(answer)+'&paper='+ encodeURIcomponent(paper);
Also, do you have check that you read the values from var question = $("#wmd-output").val(); ? is the "#wmd-output" the correct one or you need to add the rendered client id ?
First of all thanks to everyone for their effort.
This is what i did
question=encodeURIComponent(question)
var dataString = 'question='+ encodeURIComponent(question) +'&option1='+ option1 +'&option2='+ option2 +'&option3='+ option3 +'&option4='+ option4 +'&answer='+ answer +'&paper='+ paper;
I have used encodeURIComponent twice and while decoding at the server side
quest = Server.UrlDecode(question)
display the correct value.
Thanks again for help !!
I am afraid you can't pass HTML via querystring. You can use Session instead. You can store HTML in a string variable and store it in Session. On next page, you can retrieve it from Session.
Session.Add("myHTML","<p></p>");
On next page load
String html = Session["myHTML"].ToString();

Categories