I have a page that lists courses. When a student clicks on one of the course titles, it will use AJAX to pass the parameter (courseId) to a second page which will return the course details. How can the parameter (courseId) be accessed in the second page? If I put a value directly in the source instead of accessing the parameter, it shows the details:
var idInput = 12345;
var regNoInput = 098766;
When I tried getElementById to access the parameter, it didn't show any details:
var idInput = document.getElementById("courseId").value;
var regNoInput = document.getElementById("regNo").value;
I also tried accessing the parameter as a PHP variable, but still no details:
var idInput = "${courseId}";
var regNoInput = "${regNo}";
this is my first page script, the parameter is pass using url:
success: function(json_results){
$('#list').append('<ul data-role="listview" data-inset="true"</ul>');
listItems = $('#list').find('ul');
$.each(json_results.rows, function(key) {
html = "<li data-mini='true' id='icon'><a href='MRegisteredClassesDetail.html?
courseId=" + [json_results.rows[key].courseId] + "®No=" +
[json_results.rows[key].regNo] +"' rel='external'>" +
json_results.rows[key].courseName+ "</a>" + "<a
href='http://137.57.102.146:8080/Training/MRateCourse.phone?courseId="+
[json_results.rows[key].courseId] + "®No=" +
[json_results.rows[key].regNo] + "' rel='external'>RATE THIS COURSE</a>
</li>" ;
listItems.append(html);
});
and this is my second page, it should read the parameter value:
var idInput = "${courseId}";
var regNoInput = "${regNo}";
success: function(json_results){
$('#list').append('<ul data-role="listview" data-inset="true"</ul>');
listItems = $('#list').find('ul');
$.each(json_results.rows, function(courseId) {
html ='<h1 align=center>'+json_results.rows[courseId].courseName+'</h1>';
html +='<li>Registration Number:'+json_results.rows[courseId].regNo+'</li>';
html +='<li>Registration Date:'+json_results.rows[courseId].regDate+'</li>';
listItems.append(html);
});
if the parameter in the url,try this:
var params=window.location.search.substr(1).split("&"),
idInput=params[0].split("=")[1],
regNoInput=params[1].split("=")[1];
i declare a variable
var idInput = getParameterByName('courseId');
and define the function
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
it works well.
Related
I'm using jQuery to get values from ajax rest call, I'm trying to concatenate these values into an 'a' tag in order to create a pagination section for my results (picture attached).
I'm sending the HTML (divHTMLPages) but the result is not well-formed and not working, I've tried with double quotes and single but still not well-formed. So, I wonder if this is a good approach to accomplish what I need to create the pagination. The 'a' tag is going to trigger the onclick event with four parameters (query for rest call, department, row limit and the start row for display)
if (_startRow == 0) {
console.log("First page");
var currentPage = 1;
// Set Next Page
var nextPage = 2;
var startRowNextPage = _startRow + _rowLimit + 1;
var query = $('#queryU').val();
// page Link
divHTMLPages = "<strong>1</strong> ";
divHTMLPages += "<a href='#' onclick='getRESTResults(" + query + "', '" + _reg + "', " + _rowLimit + ", " + _startRow + ")>" + nextPage + "</a> ";
console.log("Next page: " + nextPage);
}
Thanks in advance for any help on this.
Pagination
Rather than trying to type out how the function should be called in an HTML string, it would be much more elegant to attach an event listener to the element in question. For example, assuming the parent element you're inserting elements into is called parent, you could do something like this:
const a = document.createElement('a');
a.href = '#';
a.textContent = nextPage;
a.onclick = () => getRESTResults(query, _reg, _rowLimit, _startRow);
parent.appendChild(a);
Once an event listener is attached, like with the onclick above, make sure not to change the innerHTML of the container (like with innerHTML += <something>), because that will corrupt any existing listeners inside the container - instead, append elements explicitly with methods like createElement and appendChild, as shown above, or use insertAdjacentHTML (which does not re-parse the whole container's contents).
$(function()
{
var query=10;
var _reg="12";
var _rowLimit="test";
var _startRow="aa";
var nextPage="testhref";
//before divHTMLPages+=,must be define divHTMLPages value
var divHTMLPages = "<a href='#' onclick=getRESTResults('"+query + "','" + _reg + "','" + _rowLimit + "','" + _startRow + "')>" + nextPage + "</a>";
///or use es6 `` Template literals
var divHTMLPages1 = `` + nextPage + ``;
$("#test").append("<div>"+divHTMLPages+"</div>");
$("#test").append("<div>"+divHTMLPages1+"</div>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test"></div>
At the moment i've got this code, which replaces a span class whith a hyperlink. The hyperlink includes a abbreviation and the alternate texxt for the hyperlink includes the same abbreviation. Now what i want to do is, to somehow replace the second abbreviation in the alternate text of the hyperlink. So that there isn't "click here to visit + 'name of'abbreviation" but instead an alias. So if the abbreviaton is ggl, the alias should be google. But the hyperlink shouldn't use this alias. Can sb help me? thx
(function($) {
var number = "1234567";
function linkBuilder(abbreviation) {
return "<a href='https://www.test.com/" + abbreviation + "?sitenumber=" + number + "default'>Click here to visit " + abbreviation + "</a>";
}
function linkBuilder2(abbreviation2) {
return "<a href='https://www.test.com/" + abbreviation2 + "?sitenumber=" + number + "default'>Click here to visit " + abbreviation2 + "</a>";
}
jQuery(document).ready(function() {
var fl = $(".first-link");
if (fl.length > 0) {
fl.html(linkBuilder(fl.data("abbreviation")));
}
var sl = $(".second-link");
if (sl.length > 0) {
sl.html(linkBuilder2(sl.data("abbreviation2")));
}
});
})(jQuery);
Here is a working jsfiddle:
https://jsfiddle.net/e7qdx031/1/
linkBuilder() should be re-usable, as kalsowerus mentioned.
Another thing that should be mentioned is that the following code returns a collection of elements, not just a single element.
var fl = $(".first-link");
...
var sl = $(".second-link");
The code you have provided will not function properly if there are multiple .first-link classes on the page. So instead I would iterate over each element using $.each() and run the linkBuilder() function on them individually.
As for the linkBuilder function I would modify it to accept the element object, then read the properties to retrieve alias and name. Full name is something that you seemed to indicate you need, but was not present in the code.
(function($) {
var number = "123456";
function linkBuilder($obj) {
var abbreviation = $obj.data('abbreviation');
var name = $obj.data('name');
return "<a href='https://www.test.com/" + abbreviation + "?sitenumber=" + number + "default'>Click here to visit " + name + "</a>";
}
jQuery(document).ready(function() {
$('.first-link, .second-link').each(function(index, obj){
$(obj).html(linkBuilder($(obj)));
});
});
})(jQuery);
What you probably want is something like this:
function linkBuilder(abbreviation, alias) {
return "<a href='https://www.test.com/" + abbreviation + "?sitenumber=" + number + "default'>Click here to visit " + alias + "</a>";
}
Just pass the display-name you want for your link as the second argument.
I have a class assigned to an anchor tag called status_button. On click of the image associated with the anchor tag it runs the attached function. Two variables are passed to a php script and a 3 piece data response is echo'ed back separated by semicolon's. I have set up alerts to ensure the correct data is coming back from php.
The thing I need help with is how to change the anchor tag title value using the echo'ed response. There are 5 examples out of probably 20 that I have tried. None of them work, but I get no error's either. Any help would be greatly appreciated.
$(".status_button").on('click', function () {
var element = $(this);
var I = element.attr("id");
var id = $("#id" + I).val();
var sname = $(this).attr("title");
$.post("openclose.php", {
id: id,
sname: sname
},
function (data) {
var response = (data).split(";", 3);
alert(response[0]);
alert(response[1]);
alert(response[2]);
$("#messageA" + I).innerhtml = (response[0]);
$("#messageA" + I).hide();
$("#messageA" + I).fadeIn(1500);
$("#messageB" + I).html(response[1]);
$("#messageB" + I).hide();
$("#messageB" + I).fadeIn(1500);
***$(this).attr("title",(response[2]));
***$(I).attr("title", (response[2]));
***$("#id" + I).attr("title" , (response[2]));
***document.getElementById(I).title = (response[2]);
***document.getElementById("#id" +I).setAttribute("title",(response[2]));
});
return false;
});
This will work:
$("#1").attr("title", (response[2]));
Your attempts:
***$(this).attr("title",(response[2])); //this is no longer referring to the clicked element when inside the callback
***$(I).attr("title", (response[2])); //Missing # for ID
***$("#id" + I).attr("title" , (response[2])); //Not your element ID
***document.getElementById("#id" +I).setAttribute("title",(response[2])); //Not your ID
Well.... I had to change a few things around to get this to work the way I needed it to. First off I removed the title from my anchor tag and placed it in my div tag. I then reduced my response from my php file from 3 down to 2 pieces of data.
$(".status_button").on('click', function () {
var element = $(this);
var I = element.attr("id");
var id = $("#id" + I).val();
var xname = $("#messageA" + I).attr('title');
$.post("openclose.php", {
id: id,
xname: xname
},
function (data) {
var response = (data).split(";", 2);
$("#messageA" + I).attr('title', (response[0]));
$("#messageB" + I).html(response[1]);
$("#messageB" + I).hide();
$("#messageB" + I).fadeIn(1500);
});
return false;
});
Basically, on clicking any image on a html page I want the id associated to be passed to a function.
This is what I have tried. It seems I am making a minor mistake here as I am getting the first id passed no matter what image I click from the array. I tried $(this).attr("id") as well, but did not work.
for(var i=0;i<jsonObj.length-1;i++){
var rows = '';
var bg_img = jsonObj[i].img;
var bg_img = decodeURIComponent(bg_img);
rows = "<img id='" + jsonObj[i].source_id + "' src='" + bg_img + "'/>";
document.getElementsByClassName('subscription')[i].innerHTML = rows;
}
$("body").delegate(".subscription", "click", function() {
// var id = $(this).attr("id");
alert("Welcome Test " + $('img').attr("id"));
return false;
});
$("img").click(function()
{
var id = $(this).attr("id");
});
Your $('img') selector is not confined to any specific area, so it will give you the first image on the entire page.
Try $('img',this) instead.
We are generating a dynamic url from the data entered into a form. We are currently able to append this dynamic form data into the url, but need to include static data at the END of the dynamic data.
Here is the last part of the jQuery that appends the data:
var inputs = $('#form1').find('input[type=text]').not('#url');
var str = "http://yoururlhere.com/dispatch.aspx?"
var str2 = "&promoid=5030385&option1=999"
inputs.each(
function (i, item) {
str += encodeURIComponent(item.name) +
"=" +
encodeURIComponent(item.value) +
"&";
});
$('http://yoururlhere.com/dispatch.aspx?').val(str+str2);
});
The end result from what we get:
http://yoururlhere.com/dispatch.aspx?address=1290 atlantis ave&zip=80026
And this is what we are trying to achieve:
http://yoururlhere.com/dispatch.aspx?address=1290 atlantis ave&zip=80026&promoid=5030385&option1=999
The last bit (promoid=5030385&option1=999) will be constant for every form entry.
*EDIT*
I solved it by putting the static data as a hidden field in the html:
<input type="hidden" name="promoid" value="5030385" id="promoid"/>
Thank you all for your comments and help!
try this
var inputs = $('#form1').find('input[type=text]').not('#url');
var str = "http://yoururlhere.com/dispatch.aspx?"
var str2 = "&promoid=5030385&option1=999"
inputs.each(function (i, item) {
str += encodeURIComponent(item.name) + "=" + encodeURIComponent(item.value) + "&";
});
str = str+str2;
});