I have a little problem with a test program I wrote with Javascript,Jquery and ajax.
This is my code:
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>
<button> Push here </button>
</body>
</html>
JS
$(document).ready(function(){
$('button').on('click',function(e){
callPage()
})
});
function callPage(){
$.ajax({
url: "http://events.restdesc.org/",
type: "GET",
dataType:'json',
succes: function (response) {
var data = response;
console.log("hey");
console.log(data.title);
},
error: function(error){
console.log("the page was not loaded", error);
},
});
}
However if I check the network, I see that I got the request, but
I don't get the the succes, so the console does not log anything.
How is this possible?
Use .done() instead success
function callPage(){
$.ajax({
url: "http://events.restdesc.org/",
type: "GET",
dataType:'json',
error: function(error){
console.log("the page was not loaded", error);
},
}).done(function(response) {
var data = response;
console.log("hey");
console.log(data.title);
});
}
Related
https://developer.tfgm.com/
I was trying to access data from the TFGM api using the sample javascript code which is using ajax.
And I try to fix the CORS problem using jsonp. But then it gives me 401 error. Here's my code
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function () {
$.ajax({
url: "https://api.tfgm.com/odata/Accidents?$top=10",
beforeSend: function (xhrObj) {
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", "d6bba5f0e3f244bc97b7c5aa4745aae2");
},
type: "GET",
// Request body
data: "{body}",
dataType: "jsonp"
})
.done(function (data) {
console.log("success");
})
.fail(function () {
console.log("error");
});
});
</script>
</body>
</html>
why it isn't working. Am trying to call a php file when onclick of a button occurs with some parameters. It is getting executed till alert statement in jsfile.js. After that the ajax part is not getting executed.. Help me out.. Thanks in advance..
main.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="jsfile.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<button onclick="cart(0)"> hi </button>
<p id="disp"></p>
</body>
</html>
jsfile.js
function cart(id1)
{
var id=id1;
alert("enterd "+id);
document.getElementById("disp").innerHTML ="hi";
$.ajax({
url:"/add.php ",
type:"POST",
data:{
item_id: id,
},
success:function(response) {
//document.getElementById("total_items").value=response;
document.getElementById("disp").innerHTML =response;
},
error:function(){
alert("error");
}
});
}
add.php
<?php
if(isset($_POST['item_id']) && !empty($_POST['item_id'])){
//if(count($_POST)>0)
echo "success";
exit();
}
?>
In your jsfile.js file, please correct the following points which I have mentioned as comments on the following code.
function cart(id1)
{
var id=id1;
alert("enterd "+id);
document.getElementById("disp").innerHTML ="hi";
$.ajax({
url:"/add.php ",
method:"POST", //First change type to method here
data:{
item_id: id,
},
success:function(response) {
document.getElementById("disp").innerHTML =response;
},
error:function(){
alert("error");
}
});
}
Change it and try
type:"POST" -> method: "POST"
If your jquery version is >= 1.5 use it this way.
$.ajax({
url: "add.php",
method: "POST",
data: { item_id: id},
}).done(function(response) {
......
}).fail(function( jqXHR, textStatus ) {
......
});
Load Jquery Before your JS file.
HI i have call a json file and show some error can u please help me
show error Uncaught ReferenceError: marketlivedata is not defined
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!DOCTYPE html>
<html xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:g="http://base.google.com/ns/1.0">
<head>
<title>Data Call to json</title>
<script type="text/javascript">
// =====================
$(document).ready(function(e) {
// alert('hello');
// var marketlivedata ;
});
// =====================
function getUserData() {
$.ajax({
type: "GET",
url: "http://xxxxxxxxx.xxxxxxx.com/xxxxxxx.json",
dataType: 'jsonp',
crossDomain: true,
success: function(data) {
// $('#ajexLoaderSec').hide();
console.log(data);
},
error: function(e) {
alert("There is an error while connecting to the server. Please try after some time");
}
});
};
getUserData();
</script>
</head>
<body>
gsdf sdf sdfsd sdf sd
</body>
</html>
My json format is
marketlivedata([{"sensex":{"trend":"equal","CloseIndexValue":"24893.81","premarket":"false","DateTime":"11:41 AM | 08 Sep 2015","CurrentIndexValue":"24958.31","Segment":"BSE","OpenIndexValue":"24972.01","PercentChange":"0.26","IndexName":"SENSEX","NetChange":"64.50"},"nifty":{"trend":"equal","CloseIndexValue":"7558.80","premarket":"false","DateTime":"11:41 AM | 08 Sep 2015","CurrentIndexValue":"7582.85","Segment":"NSE","OpenIndexValue":"7587.70","PercentChange":"0.32","IndexName":"CNX NIFTY","NetChange":"24.05"},"gold":{"ClosePrice":"26500.00","trend":"negative","OpenPrice":"26499.00","ExpiryDate":"2015-10-05","SpotSymbol":"SGOLDAHM","LastTradedPrice":"26441.00","DateTime":"8-September-2015 11:34:22","Symbol":"GOLD","PercentChange":"-0.22","CommodityName":"Gold","NetChange":"-59.00","PriceQuotationUnit":"10 GRMS ","SpotPrice":"26401.0"},"silver":{"ClosePrice":"35193.00","trend":"equal","OpenPrice":"35176.00","ExpiryDate":"2015-12-04","SpotSymbol":"SSILVERAHM","LastTradedPrice":"35070.00","DateTime":"8-September-2015 11:34:0","Symbol":"SILVER","PercentChange":"-0.35","CommodityName":"Silver","NetChange":"-123.00","PriceQuotationUnit":"1 KGS ","SpotPrice":"34815.0"},"USD/INR":{"DateTime":"2015-09-08 11:36:02.0","percentChange":"-0.27","netChange":"-0.18","name":"USD/INR","bidprice":"66.65"},"DXY Index":{"DateTime":"2015-09-08 11:39:40.0","percentChange":"-0.1","netChange":"-0.1","name":"DXY Index","bidprice":"96.13"},"marketstatus":{"currentMarketStatus":"Live"}}])
The returned data is marketlivedata(...). This is calling the marketlivedata function, which is not defined in your script. Since, you've used dataType as jsonp, the function is executed.
To solve this you can change the data format from the JSON server(which might not be possible as this looks like third party service) or you can define a function of that name which will be called when the response has arrived.
function getUserData() {
$.ajax({
type: "GET",
url: "http://mobilelivefeeds.indiatimes.com/homepagedatanew.json",
dataType: 'jsonp',
crossDomain: true,
success: function(data) {
// $('#ajexLoaderSec').hide();
console.log(data);
},
error: function(e) {
console.log(e);
}
});
};
getUserData();
function marketlivedata(data) {
console.log(data);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
As you are using json data which comes from another domain so there would be a callback function needed to access this:
Uncaught ReferenceError: marketlivedata is not defined
Here marketlivedata is a Callback Wrapper function which is returned from the service you are hitting, so Either a reference of a global function has to be set with the name of marketlivedata or make use of jsonpCallback: 'callback'(much better one) where "callback" is the function from the response. This function is actually carrying the data which you want to use, So this has to be done:
function getUserData() {
$.ajax({
type: "GET",
url: "http://mobilelivefeeds.indiatimes.com/homepagedatanew.json",
dataType: 'jsonp',
crossDomain: true,
jsonpCallback: 'marketlivedata', // call the returned function here.
success: function(data) {
document.body.innerHTML = '<pre>' + JSON.stringify(data) + '</pre>'; // use the data as you need to.
}, // you can refere it here
error: function(e) {
console.log(e);
}
});
};
getUserData();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I using this code
function testfunction(ttl){
jQuery.ajax({url:"index.php",
type: "POST",
cache : false,
data: { 'data1': ttl},
success:function(res){
//Do something
},error: function(requestObject, error, errorThrown) {
console.log(error);
}});
}
I got a error = 'error' and errorThrown = ""
This issue is only in Google chrome.
How to solve this issue ?
Following code works for me - might be problem with parameter ttl which you send via ajax call
index.php:
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script language="JavaScript">
$('document').ready(function(){
$('button').click(function() {
$.ajax({
url: "index2.php",
type: "POST",
cache: false,
data: { 'data1': $(this).attr('rel')},
success: function (res) {
console.log(res);
},
error: function (requestObject, error, errorThrown) {
console.log(error);
}
});
});
});
</script>
</head>
<body>
<button rel="test">test</button>
</body>
</html>
and index2.php
<?php
echo json_encode($_POST);
I am having this ajax request but success portion is not working I have been working from past one hour but not able to get is there any thing I am missing.
$.ajax({
url: "ajaxsearch",
type: 'POST',
dataType: "jsonp",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
data: JSON.stringify(eval({
name_startsWith: request.term
})),
success: function (data) {
alert("yoo"); //What ever I write do not get executed is any thing wrong
}
});
url: "ajaxsearch" is most likely something like url: "ajaxsearch.php" / url: "ajaxsearch.ashx"
Are you sure that the dataType is jsonp and not json?
Don't eval() - it's evil
Inspect the error on why you aren't ending up in the success handler:
error: function(jqXhr, status, error) { /* handle error here */ }
Since it's a search, you should use type: 'GET' instead of POST. POST is usually used when saving data to the server (like when submitting a form, for example. This is just a general guideline. GET is default, so you could just remove the property.
I will suggest you to first try to make the jQuery Ajax working with simple code then do modification. You can try the below code snippet:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src="jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(function() {
$("#btnSend").click(function(){
var args = {
url : "http://localhost:8080/JqueryAjaxPrj/CustomerServlet",
type : "POST",
success : handleResponse,
dataType : "json",
data : {my-status: "test", my-name: "xyz"}
};
$.ajax(args);
});
});
function handleResponse(response) {
alert(response);
}
</script>
</head>
<body>
<button id="btnSend">Send Request</button>
<br>
</body>