Uncaught Reference:$ is not defined - javascript

I'm new to coding...just wanted to know what am i doing wrong in this
<script type="text/javascript">
// This example loads the "Canadian Parliament 2012"
// dataset from a CSV instead of from JSON. // System.import('app').catch(function (err) { console.error(err); });
$(function() {
Dimensions = "sector_type";
Measures = "";
tblname = "sample";
$.ajax({
method: "GET",
url: "http://localhost:5000/api/values/5"
headers: {
'Content-Type': 'application/json'
},
traditional: true,
async: false,
}).success(function results(data) {
chartdata = data.data;
alert("SUCCESS");
});
});
</script>
This is giving me Uncaught Reference :$ is not defined.Also is this the right way of writing a small script for retrieving data from localhost:5000 and what should i do to display the data
Any Help would be deeply appreciated

It's worked for me.
You should put the reference jQuery link.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
Then replace the code
<script type="text/javascript">
$(document).ready(function(){
Dimensions = "sector_type";
Measures = "";
tblname = "sample";
data = $(this).serialize();
$.ajax({
method: "GET",
url: "http://localhost:5000/api/values/5",
headers: {
'Content-Type': 'application/json'
},
traditional: true,
async: false,
success:function(data){
chartdata = data.data;
alert("SUCCESS");
}
});
});
</script>

Try my code.. I think it will work fine
(function () {
Dimensions = "sector_type";
Measures = "";
tblname = "sample";
$.ajax({
method: "GET",
url: "http://localhost:5000/api/values/5",
headers: {
'Content-Type': 'application/json'
},
traditional: true,
async: false
}).success(function results(data) {
chartdata = data.data;
alert("SUCCESS");
});
})();

check whether you've included the jquery library in your html code.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

$ is not defined means you have not added jQuery plugin in your page.
Download jQuery plugin from jquery.com and add in your project. Reference that file in your page header.
For displaying data, it depend on what data you are retrieving. According to return data add control and bind.
$(function() {
Dimensions = "sector_type";
Measures = "";
tblname = "sample";
$.ajax({
method: "GET",
url: "http://localhost:5000/api/values/5"
headers: {
'Content-Type': 'application/json'
},
traditional: true,
async: false,
success:function (data) {
chartdata = data.data;
alert("SUCCESS");
}
});
});

Use $(document).ready(function(){});
<script type="text/javascript">
// This example loads the "Canadian Parliament 2012"
// dataset from a CSV instead of from JSON. // System.import('app').catch(function (err) { console.error(err); });
$(document).ready(function() {
Dimensions = "sector_type";
Measures = "";
tblname = "sample";
$.ajax({
method: "GET",
url: "http://localhost:5000/api/values/5"
headers: {
'Content-Type': 'application/json'
},
traditional: true,
async: false,
}).success(function results(data) {
chartdata = data.data;
alert("SUCCESS");
});
});
</script>

Related

I get a problem with ajax get request can someone help me?

My code do not response any data to me..
bellow some code:
<script type="text/javascript">
function matriculaFn(mat) {
$.ajax({
method: 'GET',
url:'My url API,
async: true,
crossDomain: false,
contentType: 'application/json;charset=utf-8',
dataType: 'json',
headers: {
"Authorization": "Token xxxprivatexxxxx"
},
options: {
useSSL: true
},
success: function(data) {
console.log(data);
var dados = JSON.stringify(data);
console.log(dados);
$("#IDDOCAMPO").val(data.AlgumaCoisa);
},
//error : function(xhr, status, error) {
// do stuff here
//var data = jQuery.getJSON(xhr.responseText);
//console.log(data);
//}
});
};
</script>
here is the error:
jquery-3.3.1.min.js:2 OPTIONS https://url net::ERR_CERT_DATE_INVALID
Can't comment yet because I don't have enough rep but it looks as though this error is Chrome specific. Have you tried other browsers? If so, try some of the methods listed here: link
Other things you could try are:
crossDomain: true,
or adding:
xhrFields: {
withCredentials: true
},
or because it's a GET request try:
dataType: 'jsonp',

How do I need to convert this to plain javascript or jquery?

I'm new to JavaScript and jQuery. I'm currenly having the following code in my javascript file, however it doesn't seem to be working. I'm using this from prototype.js :
var url = '/sip/TnsViewScreenResponse';
var myAjax = new Ajax.Request(url, {
method: "post",
headers:{
'X-Requested-By': 'XMLHttpRequest'
},
parameters: "tin=" + tin,
success: function transResult(response) {
document.getElementById('tinVersionsOf_' + tin).innerHTML
= response.responseText;
document.getElementById('ajax_loading_img').style.display
= 'none';
document.getElementById('tinVersionsOf_' + tin).style.display =
'block';
},
error: function transResult(response) {
document.getElementById('ajax_loading_img').style.display = 'none';
alert('Failure: Problem in fetching the Data');
},
}
);
return false;
This seems to be conflicting with the other jQuery files being used in the file, so I want to convert this to plain JavaScript or jQuery. I have tried the below but it doesn't seem to be working. How can I make this right ?
var url = '/sip/TnsViewScreenResponse';
var myAjax = $.ajax({
type: "POST",
url: url,
data: tin,
success: function transResult(response) {
$('#tinVersionsOf_' + tin).html(response.responseText);
$('ajax_loading_img').css("display","none") ;
$('#tinVersionsOf_' + tin).css("display","block");
},
error: function transResult(response) {
$('#ajax_loading_img').hide();
alert('Failure: Problem in fetching the Data');
},
}
});
The above code is getting skipped while being parsed in the browser, which I had checked with inspect element option in Google chrome.
Try This
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "/sip/TnsViewScreenResponse",
data: JSON.stringify({ mydata: tin }),//where tin is ur data
success: function (result) {
//include your stuff
},
error:function(error)
{
// include your stuff
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

jQuery Ajax get value via function?

I have created a save(id) function that will submit ajax post request. When calling a save(id). How to get value/data from save(id) before going to next step. How to solve this?
For example:
function save(id) {
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
return data;
},
error: function (error) {
return data;
}
});
}
Usage:
$('.btn-create').click(function () {
var id = 123;
data = saveArea(id); //get data from ajax request or error data?
if (data) {
window.location = "/post/" + data.something
}
}
You have two options, either run the AJAX call synchronously (not recommended). Or asynchronously using callbacks
Synchronous
As #Drew_Kennedy mentions, this will freeze the page until it's finished, degrading the user experience.
function save(id) {
return $.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
async: false,
data: JSON.stringify({
id: id,
})
}).responseText;
}
$('.btn-create').click(function () {
var id = 123;
// now this will work
data = save(id);
if (data) {
window.location = "/post/" + data.something
}
}
Asynchronous (recommended)
This will run in the background, and allow for normal user interaction on the page.
function save(id, cb, err) {
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
cb(data);
},
error: err // you can do the same for success/cb: "success: cb"
});
}
$('.btn-create').click(function () {
var id = 123;
save(id,
// what to do on success
function(data) {
// data is available here in the callback
if (data) {
window.location = "/post/" + data.something
}
},
// what to do on failure
function(data) {
alert(data);
}
});
}
Just make things a bit simpler.
For starters just add window.location = "/post/" + data.something to the success callback.
Like this:
function save(id) {
return $.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success:function(data){
window.location = "/post/" + data.something
}
}).responseText;
}
Or by adding all your Ajax code within the click event.
$('.btn-create').click(function () {
var id = "123";
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
window.location = "/post/" + data.something
},
error: function (error) {
console.log(error)
}
});
}

how to get the json string in a variable

i got my json string inside the ajax as function like this way
$.ajax({
type: "POST",
url: "http://localhost/./Service/GetPageInfo",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
filename: filename
}),
success: function (data) {
alert('Success');
},
error: function () {
alert('Error');
}
});
here i get data like
[{"main":{"sub":[],"tittle":"manu","startvalue":"","stopvalue":"","status":"","accumalated":"","comment":""}}]
i want it in a variable like
var myjsonobject =[{"main":{"sub":[],"tittle":"manu","startvalue":"","stopvalue":"","status":"","accumalated":"","comment":""}}]
There you go :
$.ajax({
type: "POST",
url: "http://localhost/./Service/GetPageInfo",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
filename: filename
}),
success: function (data) {
alert('Success');
var jsonobject = data;
},
error: function () {
alert('Error');
}
});
Also I strongly advise you to use promises to make API calls: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Promise
var jsonobject= null;
$.ajax({
type: "POST",
url: "http://localhost/./Service/GetPageInfo",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
filename: filename
}),
success: function (data) {
jsonobject=data;
alert('Success');
},
error: function () {
alert('Error');
}
});
If you want wait for ajax response and fill up variable then pass async: false in ajax request options.
Based on your comment, you need to parse the JSON in your success handler,
success: function (data) {
alert('Success');
var myjsonobject = JSON.parse( data );
},

Post files with AJAX + jQuery with input element ID

I am trying to POST form data with AJAX + jQuery using the code below
<script>
$("#submit1").click(function(){
testSubmit(event);
});
function testSubmit(event) {
event.preventDefault();
var data = new FormData();
var file_data = $('input[type="file"]')[0].files; // for multiple files
for(var i = 0;i<file_data.length;i++){
data.append("file_"+i, file_data[i]);
}
var other_data = $('#form_id').serializeArray();
$.each(other_data,function(key,input) {
data.append(input.name,input.value);
});
$.ajax({
url: 'test.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
}
</script>
Here submit1 is a button on form form_id
This code is working fine, however the below line
data.append("file_"+i, file_data[i]);
as you can see posts the file with id of file_0, file_1 and so on. How can I get this to be the actual id of the input element rather than being a generic file_0, file_1 etc ?
Thanks for reading this
If you are using jQuery then why not something like this
$('input[type="file"]').each(function($i){
data.append($(this).prop("id"), $(this)[0].files[0]);
});
Entire Code :-
<script>
$("#submit1").click(function(){
testSubmit(event);
});
function testSubmit(event) {
event.preventDefault();
var data = new FormData();
$('input[type="file"]').each(function($i){
data.append($(this).prop("id"), $(this)[0].files[0]);
});
var other_data = $('#form_id').serializeArray();
$.each(other_data,function(key,input){
data.append(input.name,input.value);
});
$.ajax({
url: 'test.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
}
</script>

Categories