I'm trying to get and display a field in a SharePoint list
using a Content Editor Web Part. This is just proof of concept, I want the CWP to display the Title (the currency) and the Currency Description. I think I just need a tweak and want to understand what I'm doing wrong. The var query URL displays the title fine.
Ultimately what I want to do is to store the returned value from the Exchange Rate column so that when a user selects a drop don in a separate list and an amount it will convert by the Exchange rate.
Any help is appreciated. Code below:
<script type="text/javascript">
DisplayExchangeRate();
function DisplayExchangeRate()
{
var listName = "Currency Exchange Rates";
var titleField = "Title";
var rateField = "Currency Description";
var query = "http://collaboration-dev.norgine.com/sites/it/Tools/IT- Contracts/_vti_bin/listdata.svc/CurrencyExchangeRates?
$select=Title,ExchangeRate&$filter=Title eq 'Dollars'";
var call = $.ajax({
url: query,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
call.done(function (data,textStatus, jqXHR){
$.each(data.d.results, function (i, result) {
$("#CurrencyExchangeRatesTitle").text(result.Title);
$("#CurrencyExchangeRatesCurrencyDescription").html
(result.CurrencyDescription);
});
});
call.fail(function (jqXHR,textStatus,errorThrown){
alert("Error retrieving Tips: " + jqXHR.responseText);
});
}
</script>
I don't believe you can put JavaScript directly in a Content Editor Web Part. Try using a Script Editor Web Part instead (housed in the same category of web parts as the CEWP), or pointing your CEWP to a local HTML page with the JavaScript.
http://info.summit7systems.com/blog/dont-script-in-the-wrong-web-part
Also, it looks like you're using JQuery. Do you have a reference to that library elsewhere that is loading successfully?
Below is my Working code , I have saved this code in a text file, and uploaded that file in "Site Assets" library and pointed my CEWP to this code file.
<script type="text/javascript" src="https://test.sharepoint.com/sites/devsite/SiteAssets/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var i,result;
$('#getEmployee').click(function () {
var dispalyResults="";
$.ajax({
url: "https://test.sharepoint.com/sites/devsite/_api/web/lists/getbytitle('Employee')/items",
method: "GET",
headers: { "Accept": "application/json;odata=verbose" },
success: function (data) {
var jsondata = JSON.stringify(data);
result = JSON.parse(jsondata).d.results;
for (i = 0; i < result.length; i++) {
dispalyResults+="<p><h1>"+ result[i].ID + " " + result[i].Title +"</h1></p>";
}
$('#displayResults').html(dispalyResults);
},
fail: function () {
alert("Response fails");
}
})
})
})
</script>
<input type="button" value="GET" name="GET" id="getEmployee"/>
<div id="displayResults"></div>
I have created a button and a DIV tag. When i click the button , it will display the list item Title and ID inside the DIV tag.
Related
I am trying to pass a variable from javascript to php, but it doesn't seem to be working and I can't figure out why.
I am using a function that is supposed to do three things:
Create a variable (based on what the user clicked on in a pie chart)
Send that variable to PHP using AJAX
Open the PHP page that the variable was sent to
Task one works as confirmed by the console log.
Task two doesn't work. Although I get an alert saying "Success", on test.php the variable is not echoed.
Task three works.
Javascript (located in index.php):
function selectHandler(e) {
// Task 1 - create variable
var itemNum = data.getValue(chart.getSelection()[0].row, 0);
if (itemNum) {
console.log('Item num: ' + itemNum);
console.log('Type: ' + typeof(itemNum));
// Task 2 - send var to PHP
$.ajax({
type: 'POST',
url: 'test.php',
dataType: 'html',
data: {
'itemNum' : itemNum,
},
success: function(data) {
alert('success!');
}
});
// Task 3 - open test.php in current tab
window.location = 'test.php';
}
}
PHP (located in test.php)
$item = $_POST['itemNum'];
echo "<h2>You selected item number: " . $item . ".</h2>";
Thanks to anyone who can help!
From what i can tell you don't know what ajax is used for, if you ever redirect form a ajax call you don't need ajax
See the following function (no ajax):
function selectHandler(e) {
// Task 1 - create variable
var itemNum = data.getValue(chart.getSelection()[0].row, 0);
if (itemNum) {
console.log('Item num: ' + itemNum);
console.log('Type: ' + typeof(itemNum));
window.location = 'test.php?itemNum='+itemNum;
}
}
change:
$item = $_GET['itemNum'];
echo "<h2>You selected item number: " . $item . ".</h2>";
or better you do a simple post request from a form like normal pages do :)
Try this:
success: function(data) {
$("body").append(data);
alert('success!');
}
Basically, data is the response that you echoed from the PHP file. And using jQuery, you can append() that html response to your body element.
you should change this code
'itemNum' : itemNum,
to this
itemNum : itemNum,
Seems contentType is missing, see if this helps:
$.ajax({
type: 'POST',
url: 'test.php',
dataType: "json",
data: {
'itemNum' : itemNum,
},
contentType: "application/json",
success: function (response) {
alert(response);
},
error: function (error) {
alert(error);
}
});
you can easily pass data to php via hidden variables in html for example our html page contain a hidden variable having a unique id like this ..
<input type="hidden" id="hidden1" value="" name="hidden1" />
In our javascript file contains ajax request like this
$.ajax({
type: 'POST',
url: 'test.php',
data: {
'itemNum' : itemNum,
}
success: function (data) {
// On success we assign data to hidden variable with id "hidden1" like this
$('#hidden1').val(data);
},
error: function (error) {
alert(error);
}
});
Then we can access that value eighter on form submit or using javascript
accessing via Javascript (Jquery) is
var data=$('#hidden1').val();
accessing via form submit (POST METHOD) is like this
<?php
$data=$_POST['hidden1'];
// remaining code goes here
?>
So I have on my page a div with id="machine-content", which I use to display various info about my machines. Mainly, I display information in tables. I am trying to use DataTables (https://datatables.net/), but I have problem initializing the table. After click on action (i.e. "show me repairs", "show me workhours"), I load a table element from external html and fill it with data through AJAX according to chosen action.
So here's how my files look.
In index.php (jquery and datatables are loaded in head):
<script src="data.js"></script>
...
<div id="machine-content" class="col-md-9" style="float:right">
</div>
...
External html is super simple:
<h1 id="machine-content-h1"></h1>
<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%"></table>
I then have data.js that controls index.php. There, I handle clicks to actions and loading of table through AJAX. All the data is loaded correctly but when I want to initialize a DataTable (to get search field, paging, etc.) it doesnt work. As far as I know, I have to initialise it after the data is loaded, anyway I also tried initialising it before. Here is data.js:
//EXAMPLE of handling chosen action with button click
//I TRIED putting //I TRIED putting $.('#example').DataTable(); HERE
//wrapped in $(document).ready
$('#arentals').click(function(){
$( '#machine-content' ).load("/gui/machines/machines/templates/table.html", function() {
load_service_table("RENTALS");
});
});
function load_service_table(action){
var action_url;
switch(action) {
case 'REPAIRS':
action_url='/gui/machines/machines/show_services.php';
break;
case 'RENTALS':
action_url='/gui/machines/machines/show_rentals.php';
break;
case 'REVENUES':
action_url='/gui/machines/machines/show_revenues.php';
break;
default:
action_url='/gui/machines/machines/show_hours.php';
}
$.ajax({
url: action_url,
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: "html",
type: "POST",
success: function(data) {
//I TRIED putting $.('#example').DataTable(); HERE
$( '#machine-content-h1' ).text(action);
$( '#example' ).html(data);
//I ALSO TRIED putting $.('#example').DataTable(); HERE
}
});
//AND HERE
}
PHP functions are simple and in AJAX return only head and body elements of table, so I guess there is no problem.
So my question is: How can I initialize this thing? I mean, if I am able to set html to #example in AJAX success function, why can't I initialise the same element there? Any help would be deeply appreciated.
EDIT
I always get this error:
jquery.dataTables.min.js:65 Uncaught TypeError: Cannot read property 'aDataSort' of undefined
SOLUTION
I only added $('#machine-content').find('#example').DataTable(); to AJAX success function which now looks like this:
$.ajax({
url: action_url,
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: "html",
type: "POST",
success: function(data) {
$( '#machine-content-h1' ).text(action);
$( '#example' ).html(data);
$('#machine-content').find('#example').DataTable();
}
});
datatable has a build-in ajax method
$('#myTable').DataTable( {
ajax: '/api/myData'
} );
https://datatables.net/manual/ajax#Loading-data
or use:
$('#machine-content').find('.table').DataTable();
I know this post is older so probably of no help to you now but for anyone else who comes across this.
Something like the following should work:
var adminUsers = {
list: () => {
var action = 'list_users';
var url = base_url+'index.php/admin/users/io';
var data = { }
var response = ajaxRequest.post(action, url, data);
response.then(
function(obj){
var data = JSON.parse(obj);
console.log(data);
//console.log(data.data.result);
$.each(data.data, function(i,e){
var html = '';
html = html + '<tr>';
html = html + '<td>'+e.id+'</td>';
html = html + '<td>'+e.username+'</td>';
html = html + '<td>'+e.first_name+' '+e.last_name+'</td>';
html = html + '<td>'+e.status+'</td>';
html = html + '<td>'+e.locked+'</td>';
html = html + '<td>'+e.uuid+'</td>';
html = html + '</tr>';
$('#users-list tbody').append(html);
});
$('#users-list').DataTable(adminUsers.dataTable());
},
function(jqXHR, textStatus, errorThrown){
ajaxRequest.error(jqXHR, textStatus, errorThrown);
});
},
dataTable: () => {
var config = {
initComplete : function() {
$("#users-list_filter").detach().appendTo('#search');
$("#users-list_length").detach().appendTo('#display_length');
$("#users-list_length").attr('style', 'margin-right:10px;');
$("#users-list_filter input").addClass('form-control');
},
language: {
search: "",
searchPlaceholder: 'Search...'
}
}
return config;
}
};
I am developing a website in which only 1 html page is there in which I first fethch the url & gets the id from url and send it to api using ajax call. On success, I displays data of the given id from url.My code is as-
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#main').hide();
var url = window.location.href;
var formno = url.substr(url.lastIndexOf('/') + 1);
if (formno != 'Login.html') {
var apiUrl = 'http://localhost:801/api/api/Patient/Get';
$.ajax({
url: apiUrl,
crossDomain: true,
contentType: "application/json",
type: 'GET',
data: { formNo: formno },
success: function (result) {
$('#main').show();
alert("Success" + result)
},
error: function (result) {
alert("error :: " + JSON.stringify(result))
}
});
}
});
</script>
when I use the url as abc.in#1 it displays the success alert but I want to give the url in format abc.in/1 at that time it gives
HTTP Error 404.0 - Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
Why it can not find the page? Is there any solution for this?
I want to give plain url as abc.in/1 where 1 is id and which is dynamic.
Is there any solution?
Your browser is probably trying to access document on location abc.in/1, which doesn't exist. You will need some server side logic for this, e.g. php router which will always serve your document, and additonal parameters will be processed by it. abc.in#1 anchor is different type of url parameter, which purpose is to be processed by document or javascript on client side.
I'm using the Javascript Dropbox Chooser https://www.dropbox.com/developers/dropins/chooser/js and with the help of #smarx (How to display selected file name when using the Dropbox API JS Chooser) I've managed to fetch the <img src="" to fetch images into the browser.
The next thing that I want to do is to POST those image url's into a json file stored on my localhost as: galeria.json via $.ajax after the submit button is clicked, however, I can't seem to accomplish it.
I'm relatively new with jQuery and AJAX so I don't understand the error response that I get on my console: Error: [object, Object].
Here's the code:
<body>
<form class="gallery-form" action="galeria.json" method="POST">
<input id="chooser" type="dropbox-chooser" name="selected-file" data-link-type="direct" data-multiselect="true" style="visibility: hidden;"/>
<div id="chosen" style="display:none"></div>
<input type="submit" id="submit" value="Enviar" disabled />
</form>
<script>
$(function () {
$('#chooser').on('DbxChooserSuccess', function (e) {
for (var i = 0; i < e.originalEvent.files.length; i++) {
var url = e.originalEvent.files[i].link;
var filename = e.originalEvent.files[i].name;
var linkTo = "<img src='" + url + "'" + ">" + "</img>";
$('#chosen').show();
$('#chosen').append(linkTo);
}
$('#submit').prop('disabled', false);
$(".gallery-form").submit(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "galeria.json",
dataType: "json",
data: {imgUrl: url},
success: function(response){
console.log("Success: " + response.imgUrl);
},
error: function(error){
console.log("Error: " + error);
}
});
});
});
});
</script>
</body>
If you would like to help me a little bit more, the goal of doing this is to later GET those img url's from the galeria.json file into my index.html and insert them on a gallery <section id="gallery">.
What code are you running on the server to receive the JSON request? I suspect you're missing a piece here. Your code to send the URL to the server looks right, but that's not the only step required. On the server, you need some code that's going to receive the request and write the URL to a file.
You might want to store the urls in an array and then submit that to the server. Note that in the AJAX request I'm assuming you have a server that accepts post requests to the resource "/images".
<script>
$(function () {
$('#chooser').on('DbxChooserSuccess', function (e) {
var urls = [];
for (var i = 0; i < e.originalEvent.files.length; i++) {
var url = e.originalEvent.files[i].link;
urls.push(url);
var filename = e.originalEvent.files[i].name;
var linkTo = "<img src='" + url + "'" + ">" + "</img>";
$('#chosen').show();
$('#chosen').append(linkTo);
}
$('#submit').prop('disabled', false);
$(".gallery-form").submit(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "/images",
dataType: "json",
data: {imgUrls: urls},
success: function(response){
console.log(response.message);
},
error: function(error){
console.log(error.message);
}
});
});
});
});
</script>
On the server side (Rails in my example since I know you have worked with it) you would process the array. JSON Data sent with an ajax request should be available in the params hash. The params[:imageUrls] would be the array of urls.
def create
params[:imgUrls].each do |url|
Image.create(path: url)
end
respond_to do |format|
format.html
format.json { render :json {message: 'Success!'} }
end
end
I am making a webapp with Jquery Mobile. I got my data back from a webservice function.
Now to get this data in my web page I am using a ajax call.
$('[data-role=page]').live('pageshow', function () {
var userId = $("#userId").val();
$.ajax({
url: "~SYSTEM.URL~~CAMPAIGN.URL~/SelligentMobile/Webservice/WebService.asmx/getNieuwtjes",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{'userId':'" + userId + "'}",
success: function (response) {
var nieuwtjes = response.d;
if (nieuwtjes.length > 0) {
$.each(nieuwtjes, function (i, entity) {
$('#nieuwtjesList').append(
//Here come's the data from web function
});
}
}
});
});
Now in #nieuwtjesList should come all the data that I get back from the server. These data is a newsTopic. And it should show it like this.
<li>~ITEM.ONDERWERP~ </li>
My question is, how can I create the line above for every record I got back from my webservice function.
Kind Regards.
Stef
You can use this code to create the HTML to append for each line
$("<li/>").append($("<a/>")
.attr("href", <HREF FROM YOUR DATA>)
.text(<TEXT FROM YOUR DATA>)
);
You can use jQuery.tmpl to easily implement this.
var nieuwtjes = response.d;
if (nieuwtjes.length > 0) {
var html ='';
$.each(nieuwtjes, function (i, entity) {
html += '<li>'+ i.ONODERWERP+'</li>';
});
$('#nieuwtjesList').append($(html));
}