I have code that creates the body of a html-file.
I create it with JQuery.
The code is as followed:
SCRIPT JS
$(document).ready(function(){
homePage();
});
function homePage(){
$.ajax({
url: "http://events.restdesc.org/",
type: "GET",
dataType:'json',
success: function (response) {
var data = response;
var html = $("<h1></h1>").text(data.title);
var br = $("<br>");
var eventbtn = $('<input />', {
type : 'button',
id : 'eventbutton',
value : 'Events',
on : {
click: getevents(data.events)
}
});
html.append(br,eventbtn).appendTo($("body"));
},
error: function(error){
console.log("the page was not loaded", error);
},
});
}
function getevents(url){
console.log(url);
}
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
<script src="https://code.jquery.com/jquery-2.1.1.js"></script>
<script src="script.js"></script>
</head>
</body>
</html>
The function homePage is directly called when you open the index.html.
It does work, I see a header and a button, however the code is automatically triggers, it prints the url in the console. But when I click on it, it doesn't print it in the console.
How do I need to change my code in order to get a button that only prints the given url when I click on the button?
Try setting data-url attribute and then access it using $(this):
function homePage(){
$.ajax({
url: "http://events.restdesc.org/",
type: "GET",
dataType:'json',
success: function (response) {
var data = response;
var html = $("<h1></h1>").text(data.title);
var br = $("<br>");
var eventbtn = $('<input />', {
type : 'button',
id : 'eventbutton',
value : 'Events',
});
eventBtn.addClass('dynamic-btn');
eventbtn.data('url', data.events);
html.append(br,eventbtn).appendTo($("body"));
},
error: function(error){
console.log("the page was not loaded", error);
}
});
}
$(document).on('click', '.dynamic-btn',
function (e) {
console.log($(this).data('url'));
});
Add click function to the button after it has already been appended to the body:
function homePage(){
$.ajax({
url: "http://events.restdesc.org/",
type: "GET",
dataType:'json',
success: function (response) {
var data = response;
var html = $("<h1></h1>").text(data.title);
var br = $("<br>");
var eventbtn = $('<input />', {
type : 'button',
id : 'eventbutton',
value : 'Events',
on : {
click: getevents(data.events)
}
});
html.append(br,eventbtn).appendTo($("body"));
eventbtn.click(getevents(data.events));
},
error: function(error){
console.log("the page was not loaded", error);
}
});
}
$(document).ready(function(){
homePage();
});
function homePage(){
$.ajax({
url: "http://events.restdesc.org/",
type: "GET",
dataType:'json',
success: function (response) {
var data = response;
var html = "<h1>"+data.title+"</h1>";
html += "<br>";
html += '<input type="button" id="eventbutton" value="Events"/> ';
$("body").append(html);
$('input').click(function(){
getevents(data.events);
});
},
error: function(error){
console.log("the page was not loaded", error);
},
});
}
function getevents(url){
console.log(url);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Related
Good day, I have a SharePoint form the has a Originator Completed Dropdown with Yes or No as options. If the dropdown is yes, I would like to use JavaScript to set the OriginatorSignature (Text Field) to the loginName or current user. Can someone assist with this function?
<script src="/SiteAssets/jquery-3.2.1.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
GetUserLogin();
});
var userid = _spPageContextInfo.userId;
function GetUserLogin() {
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
var requestHeaders = { "accept" : "application/json;odata=verbose" };
$.ajax({
url : requestUri,
contentType : "application/json;odata=verbose",
headers : requestHeaders,
success : QuerySuccess,
error : QueryError
});
}
function QuerySuccess(data, request){
var loginName = data.d.LoginName.split('|')[1];
$("input[title='Originator Signature']").val(loginName);
}
function QueryError(error) {
alert(error);
}
</script>
The following code for your reference.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
if($("select[title='Originator Completed Dropdown']").val()=="Yes"){
GetUserLogin();
}
$("select[title='Originator Completed Dropdown']").change(function(){
if($(this).val()=="Yes"){
GetUserLogin();
}else{
$("input[title='Originator Signature']").val("");
}
});
});
function GetUserLogin(){
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + _spPageContextInfo.userId + ")",
type: "GET",
headers: {
"Accept": "application/json;odata=verbose",
},
success: function (data) {
var loginName = data.d.LoginName;
if(loginName.indexOf("|")!=-1){
loginName = loginName.split('|')[1];
}
$("input[title='Originator Signature']").val(loginName);
},
error: function (data) {
//alert("Error");
}
});
}
</script>
I'm trying to get the profile image from delve and display it on a Sharepoint page using Javascript,the problem i'm getting is that the image isn't loading always
var profileimage="https://eur.delve.office.com/mt/v3/people/profileimage?userId="+userInfo["SPS-ClaimID"]+"&size=L";
If you want to display the profile image, we can use the url as below.
var profileimage="/_layouts/15/userphoto.aspx?size=L&username=lz#tenant.onmicrosoft.com";
Example code:
<script src="//code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/siteusers?$select=Id,Title,Email";
$.ajax({
url: url,
method: "GET",
async: false,
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
var items=data.d.results;
var options="<option>--select a user--</option>";
for(var i=0;i<items.length;i++){
if(items[i].Email!=""){
options+="<option value='"+items[i].Email+"'>"+items[i].Title+"</option>";
}
}
$("#SiteUsers").html(options);
},
error: function (data) {
}
});
$("#SiteUsers").change(function(){
var html="";
if($(this).val()!=null&&$(this).val()!=""){
html+="<img src='/_layouts/15/userphoto.aspx?size=L&username=" + $(this).val() + "'/>";
}
if($(this).children(':selected').text()!=""){
html+="<p><span>Name:"+ $(this).children(':selected').text()+"</span></p>";
}
$("#UserInfomation").html(html);
});
});
</script>
<select id="SiteUsers"><option>--select a user--</option></select>
<div id="UserInfomation"></div>
we are using javascript code to load more event on photo gallery, and on each thumb click we are opening the gallery in fancybox. initial load thumbs is working with fancybox. but after load more button click we are returning partial view from controller and AJAX and when we are click on new thumb to open the gallery its open in blank new tab like href. kindly let us know the issue, we are giving the code here. Any help appreciated.
<link href="/css/jquery.fancybox.css" rel="stylesheet" />
<link href="/css/photo-gallery.css" rel="stylesheet" type="text/css">
<section id="p-tab-item-1">
#Html.Partial("PhotoGalleryList", new ViewDataDictionary { {"CatParameter", "Gujarati" }})
</section>
See More....
#* Load more coding*#
<script type="text/javascript" src="/scripts/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="/scripts/jquery.fancybox.js"></script>
<script type="text/javascript">
$("input[id=p-tab-1]").click(function () {
pageIndx = 1;
if (Gtabflg == false) {
$("#loadMoreBtnG").show();
loadImage('#CurrentPage.Id', 'Gujarati', pageIndx)
}
$("#loadMoreBtnE").hide();
Gtabflg = true;
Etabflg = false;
});
});
//Initial Image load
function loadImage(pageNo, thumbType, pageIndx) {
$.ajax({
type: "POST",
url: "/umbraco/surface/Controller/GalleryImages/",
dataType: "html",
data: { pgParam: pageNo, catparam: thumbType, index: pageIndx },
success: function (data) {
if (thumbType == "Gujarati") {
$('#p-tab-item-1').html(data);
}
},
error: function (result) {
console.log(result);
alert(result);
}
});
}
function LoadMore(){
$.ajax({
type: "POST",
url: "/umbraco/surface/Controller/GalleryImages/",
dataType: "html",
data: { pgParam: pageNo, catparam: thumbType, index: pageIndx },
success: function (data) {
if (thumbType == "Gujarati") {
$('#p-tab-item-1').append(data);
if (pageIndx == gujmax) {
$("#loadMoreBtnG").hide();
}
}
}
},
error: function (result) {
console.log(result);
alert(result);
}
});
}
$('#imgGallery').click(function(){
$(".fancybox-thumb").fancybox({
prevEffect: 'none',
nextEffect: 'none',
helpers: {
title: {
type: 'over'
}
}
});
});
// thumb click load lightbox image
function GetImages(nodeid){
$.ajax({
type: "POST",
url: "/umbraco/surface/Controller/GetImages/",
dataType: "html",
data: { imgParam: nodeid },
success: function (result) {
$('#imgGallery').html('');
$('#imgGallery').html(result);
$( "#imgGallery" ).click();
$( "#imgGallery a:first" ).click();
},
error: function (result) {
console.log(result);
alert(result);
}
});
}
</script>
}
partial view code:
#item.GetPropertyValue("title")
GalleryImage view code:
When I execute the below code all the img with the id of imgg will be replaced because they are in a foreach loop, but I want to apply that to the clicked one only. Can any one help?
Html:
<button type="submit" id="getRequest" class="btn btn-info btm-sm " role="button" style="width:100px;height:30px">
<p id="imgg">Add to Cart</p>
</button>
JS:
$(document).ready(function() {
$(document).on('submit', '#reg-form', function() {
var data = $(this).find("#post_id").val();
//var ln = $("#lname").val();
//var data = 'fname='+fn+'&lname='+ln;
// var data = $(this).serialize();
$.ajax({
type: 'POST',
url: '{{url("/ajax")}}',
data: {
'name': data,
'_token': $('input[name=_token]').val()
},
success: function(data) {
$(imgg).replaceWith('<img id=imgg src=img/ajax.gif> ');
setTimeout(function() {
$(imgg).replaceWith(' <p id="imgg">Add to Cart</p> ').hide('blind', {}, 500)
}, 1300);
console.log(data);
},
error: function(data) {
alert("You must Login First");
}
});
return false;
});
});
Thanks everyone i found the solution But you da real MVP, here it is
$(document).ready(function()
{
$(document).on('submit', '#reg-form', function()
{
var imgid = $(this).find("#imgg");
var data = $(this).find("#post_id").val();
//var ln = $("#lname").val();
//var data = 'fname='+fn+'&lname='+ln;
// var data = $(this).serialize();
$.ajax({
type : 'POST',
url : '{{url("/ajax")}}',
data: {'name':data, '_token': $('input[name=_token]').val()},
success: function(data) {
$(imgid).replaceWith('<img id=imgg src=img/ajax.gif> ');
var thisForm = this;
setTimeout(function() {
$(imgg).replaceWith(' <p id=imgg>Add to Cart</p> ').hide('blind', {}, 500)
}, 1300);
console.log(data);
},
error : function(data)
{
alert("You must Login First");
}
});
return false;
});
});
</script>
<script type="text/javascript">
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
Instead of using the $(imgg) use $(this), and you also missed the quotations when you where giving the id of iamge when you where using .replaceWith:
success: function(data) {
$(this).replaceWith('<img id="imgg" src="img/ajax.gif>" ');
var thisForm = this;
setTimeout(function() {
$(thisForm).replaceWith(' <p id="imgg">Add to Cart</p> ').hide('blind', {}, 500)
}, 1300);
console.log(data);
},
Reason?
Simple. The this object doesn't change. It is the owner of the function. See more about why here: Jquery - When to use "this" and when to use "$(this)"?
EDIT2
Now i have to put that in the upper level so this:
$(document).ready(function() {
$(document).on('submit', '#reg-form', function() {
var vm = this //Upper Level
var data = $(this).find("#post_id").val();
$.ajax({
type: 'POST',
url: '{{url("/ajax")}}',
data: {
'name': data,
'_token': $('input[name=_token]').val()
},
success: function(data) {
$(vm).replaceWith('<img id=imgg src=img/ajax.gif> ');
setTimeout(function() {
$(vm).replaceWith(' <p id="imgg">Add to Cart</p> ').hide('blind', {}, 500)
}, 1300);
console.log(data);
},
error: function(data) {
alert("You must Login First");
}
});
return false;
});
});
Please refer here about this particular problem:
Uncaught TypeError: Cannot read property 'createDocumentFragment' of undefined
I want to retrieve some data from Weather.asmx and wrote below code to get some data. There was no error from Javascript as I have seen but when the program runs it always go to groupPropertiesErrorHandler function. Any idea?
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#butCallAjax').click(function() {
jQuery.support.cors = true;
$.ajax({
url: "http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityWeatherByZIP?ZIP=10007",
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: groupPropertiesSuccessHandler,
error: groupPropertiesErrorHandler
});
});
function groupPropertiesSuccessHandler(data) {
var jsonObject = JSON.parse(data.body);
var properties = 'Group Properties:\n';
alert(properties);
}
// Error Handler
function groupPropertiesErrorHandler(data, errorCode, errorMessage) {
alert("Could not get the group properties: " + errorMessage);
}
});
</script>