Here is a code to POST JSON data. It should work . But I am not sure where I did the mistake . probably a silly one, but unable to detect
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script language="javascript" type="text/javascript">
<!--
function greeter() {
var accx = 5;
var accy = 6;
var accz = 7;
var output = [];
output[0] = {
name: "Accel_X",
value: accx.toString(), // retrieve x
};
output[1] = {
name: "Accel_Y",
value: accy.toString(), // retrieve y
};
output[2] = {
name: "Accel_Z",
value: accz.toString() // retrieve z
};
var fromData = {};
fromData.output = output;
var fromDatan = JSON.stringify(fromData);
alert(fromDatan);
$.ajax({
url: "http://posttestserver.com/post.php",
type: "POST",
headers: {
"content-type": "application/json"
},
data: fromDatan,
dataType: "JSON",
success: function(fromDatan, status, jqXHR) {
alert(JSON.stringify(fromData));
},
error: function(jqXHR, status) {
alert(JSON.stringify(jqXHR));
}
});
return false;
}
//-->
</script>
</head>
<body>
<button onclick="greeter();">Click me</button>
</body>
</html>
I am unable to POST. I tried with POSTman chrome extension to POST data. It was working. WHy it is not working here I am not able to detect.
Your code worked for me when I removed the headers parameter from the $.ajax() call.
Related
So, I made updates to this code to fix some issues that were pointed out in another question. The function runs, but returns {"readyState":0,"status":0,"statusText":"error"}. I switched from $.getJSON to $.ajax so I could send headers to hopefully fix the error, but it's still giving me the same error without much detail.
<HTML>
<head>
<title>Ecobee API PIN TEST</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function PINCode() {
apiKey = 'kmkbJCrEUbMBpO2I6E90QeYcueAz1p00'
// set all apiKey inputs to have apiKey value entered
$(".apiKey").each(function() {
$(this).val(apiKey);
});
var url = 'https://api.ecobee.com/authorize?response_type=ecobeePin&client_id=' + apiKey + '&scope=smartWrite';
$.ajax({
dataType: "json",
url: url,
headers: { 'Access-Control-Allow-Origin': '*' },
success: function(data) {
$("#authCode").val(data.code);
alert("JSON Ran");
var response = JSON.stringify(data, null, 4);
$('#response1').html(response);
}
})
// $.getJSON(url,function(data) {
// // set authCode to be code attribute of response
// $("#authCode").val(data.code);
// alert("JSON Ran")
// var response = JSON.stringify(data, null, 4);
// $('#response1').html(response);
// })
.fail(function(jqXHR, textStatus) {
$('#response1').html("The following error was returned: <br><br>" + JSON.stringify(jqXHR) + "<p>Please Contact <b>M2 AV Consulting</b> at <a href=mailto:support#m2avc.com?subject='EcobeePINSupport'>support#m2avc.com</a>")
console.log(textStatus);
});
})
</script>
<pre id="response1" class="code-json">(Response JSON will appear here...I hope.)</pre>
</body>
</HTML>
I need to make an AJAX request to API to get the word for a hangman game. Also struggling, on reading the word length and displaying it with placeholders. I referenced this link enter link description here , but am still stuck.
//function to get the word from the API using AJAX
jQuery.extend({
getValues: function(url) {
var result = null;
$.ajax({
url: url,
type: 'get',
dataType: 'xml',
async: false,
success: function(data) {
result = data;
}
});
return result;
}
});
//accessing global variable (word)
var results = $.getValues("https://hangman-api.lively.software");
for (var i < 0; i < word.length; i++) {
results[i] = "_";
}
Hopefully my snippet can help you in some ways. have a nice day!
$(function(){
$.ajax({
url: "https://hangman-api.lively.software/",
type: 'get',
success: function(data) {
//how to access word
console.log(data.word)
//how to create placeholders
placeHolder = " _ ";
placeHolders = placeHolder.repeat(data.word.length)
//how to print place holder
$(".placeHolder").text(placeHolders)
}
});
})
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
Placeholders : <span class="placeHolder"></span>
</body>
</html>
I´m quite new to Javascript and jQuery. For a project I want to check if a Sharepoint list contains any duplicates, without using build in function, to expand it later on to compare more than one column. In my current code I'm retrieving the value of a lookup field and try to match it to all my results in my table. While I properly got my lookup value, my matching variable (x) shows multiple "undefined" entries. When manually typing in the URL, the XML-document shows all the necessary values in my list.
How can I properly retrieve each of my current list values and pass it to a variable?
<script src="https://ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js" type="text/javascript"></script>
<!-- reference jQuery from Miscrosoft CDN -->
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"></script><script type="text/javascript">
function PreSaveItem() {
if (CheckExists()) {
alert('KU in USE');
return false;
} else {
return true;
}
}
function CheckExists() {
var gnr= $("select[title='Test']").find("option:selected").text();
alert(gnr)
var listUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('My List')/items?$select=*,Test/Test&$expand=Test";
var c = false;
$.ajax({
url: listUrl,
type: "GET",
async: false,
headers: { "Accept": "application/json;odata=verbose" },
success: function(data){
$.each(data.d.results, function(i, item) {
var x = item["Test"].text ;
alert(x);
if (x!= undefined) {
if (gnr === x) {
c = true;
}
}
}); // each
},
error: function(error) {
alert(JSON.stringify(error));
}
});
return c;
}
</script>
I expect the output of an alert, if a duplicate is found, but nothing happens.
The following example for your reference.
1.Create custom list "My List".
2.Add lookup field "Test", column look up values from another custom list with the column "ID".
3.Add the code below into script editor web part in new form page in "My List".
<script src="https://code.jquery.com/jquery-1.12.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
function PreSaveItem() {
if (CheckExists()) {
alert('KU in USE');
return false;
} else {
return true;
}
}
function CheckExists() {
var gnr= $("select[title='Test']").find("option:selected").text();
//alert(gnr)
var listUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('My List')/Items?$select=Test/Id&$filter=Test/Id eq "+gnr+"&$expand=Test/Id";
var c = false;
$.ajax({
url: listUrl,
type: "GET",
async: false,
headers: { "Accept": "application/json;odata=verbose" },
success: function(data){
if(data.d.results.length>0){
c=true;
}
},
error: function(error) {
alert(JSON.stringify(error));
}
});
return c;
}
</script>
If you want to retrieve a property/column called "Test" from List "Test".
Instead of using:
var x = item["Test"].text
Try to use:
var x = item.Test.Test
I want to make an html5 select with data given by javascript, and inside this javascript an ajax calling a Json URL. I mean, I´ve got this:
--index.html
<!DOCTYPE html>
<html>
<head>
<script src="functions_app.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body onload="getData()">
<p>Sessions:
<select id="Select"></select>
</body>
</html>
functions_apps.js
function getData(){
$.ajax({
type: "GET",
url: 'http://.../json_offers.php',
async: false,
dataType: "json",
success: function(data){
//alert(data);
$.each(data,function(key, registro) {
var id = "";
var name = "";
$.each(registro, function(key, value) {
//alert(campo + ": " + valor);
if (key == "id") { id = value; }
if (key == "name") { name = value; }
});
});
$("#select").append('<option value='+id+'>'+nombre+'</option>');
},
error: function(data) {
alert('error');
}
});
}
json_offers.php
Json data:
[{"id":"6","name":"FLOWERS"},{"id":"8","name":"GROCERY"}]
But It does not work. It always return:
error: function(data)
I can´t load data given inside html select.
Any Help?
Best Regards
You have <select id="Select"></select>, but you are trying to put options into $("#select_zcas")
When I execute this JavaScript file in Firefox;
<script type="text/javascript" >
$(function () {
$(".comsubmit").click(function () {
var comsn = $("#comsn").val();
var comrn = $("#comrn").val();
var compic = $("#compic").val();
var comment = $("#comment").val();
var eventid = $("#eventid").val();
var dataString = 'comsn=' + comsn + '&comrn=' + comrn + '&compic=' + compic + '&comment=' + comment + '&eventid=' + eventid;
if (comment == '') {
alert('Must Type Comment to Post Comment');
} else {
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="assets/uploading.gif" />Loading Comment...');
$.ajax({
type: "POST",
url: "comments_post.php",
data: dataString,
cache: false,
success: function (html) {
$("ol#update").append(html);
$("ol#update li:last").fadeIn("slow");
$("#flash").hide();
}
});
}
return false;
});
});
</script>
I get this error
Error: missing } in XML expression
Line: 31, Column: 2
Source Code:
}); });
The arrow points inbetween the first semi colon and the space.
What can I do to fix this error?
Few remarks about your code:
You don't need the cache: false option as you are performing a POST request.
Instead of concatenating the parameters into dataString let jQuery handle formatting and escaping:
$.ajax({
type: "POST",
url: "comments_post.php",
data: {
comsn: comsn,
comrn: comrn,
compic: compic,
comment: comment,
eventid: eventid
},
success: function (html) {
$("ol#update").append(html);
$("ol#update li:last").fadeIn("slow");
$("#flash").hide();
}
});
Check the Content-Type header returned by comments_post.php. If it is not properly set (for example if it is set to text/xml), jQuery might try to parse the returned XML, while in reality you are returning HTML.
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
<font family="Arial" color="red" ><span style="font-size: x-small;"><script style="text/javascript" src="http://sites.google.com/site/attachanu/home/scrollingnew.js?attredirects=0&d=1"> </script>
<script style="text/javascript">
var nMaxPosts = 20;
var sBgColor;
var nWidth;
var nScrollDelay = 75;
var sDirection="left";
var sOpenLinkLocation="N";
var sBulletChar="•";
</script>
<script style="text/javascript" src="http://hackerz7.blogspot.com/feeds/posts/default?alt=json-in-script&callback=RecentPostsScrollerv2">
</script></span></font>
I think the HTML you are passing from the Ajax call is not properly formated. Can you add an alert and make sure it looks OK?