I am working on get json from server in javascript.
i used pure javascript, jquery but i am getting status 0.
$(document).ready(function() {
$("#btn").click(function(event){
$.getJSON('http://myhost/myapp/data.json', function(jd) {
alert(jd);
});
});
});
<body>
<input type="button" id="btn" value="Load Data" />
</body>
getJSON() block not called.
can anyone help me?
Check if you allow CORS on your host or if your response was empty!
You might also try to use $.ajax().
$.ajax("http://myhost/myapp/data.json", function (data) {
console.log(data);
}
use jQuery.getJSON()
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
read more from http://api.jquery.com/jquery.getjson
Related
I am trying to make a simple website that posts information to an api and shows output as alert. But I can't get any alert.
Code:
<!DOCTYPE html>
<html>
<body>
<b>Enter name</b>
<br>
<input type="text" id="name">
<br>
<button id="button1">Submit</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>$('#button1').click(function(){
$.ajax({
type: "POST",
url: "http://(api url)",
data :{name:$('#name').value()},
});
});
</script>
</body>
</html>
You're very close, there are a few issues in your code. Your data: {} throws a syntax error since .value() doesn't exist it's instead .val() that you're looking for.
To display the results after a successful request to the API endpoint, you need to have a success callback which can be written as below. I am using a test dummy POST endpoint at the URL https://jsonplaceholder.typicode.com/posts in the code below, replace it as needed with the actual URL you're requesting :
$('#button1').click(function(){
$.ajax({
type: "POST",
url: "https://jsonplaceholder.typicode.com/posts",
data :{name:$('#name').val()},
success: function (data) {
alert(data);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<b>Enter name</b>
<br>
<input type="text" id="name">
<br>
<button id="button1">Submit</button>
If you want to show the result in alert, in that case you need to handle the success callback like following.
$.ajax({
type: 'POST',
url: "http://(api url)",
data: {name:$('#name').val()}
success: function(result) { alert(result) }
});
success Type: Function( Anything data, String textStatus, jqXHR jqXHR
) A function to be called if the request succeeds. The function gets
passed three arguments: The data returned from the server, formatted
according to the dataType parameter or the dataFilter callback
function, if specified; a string describing the status; and the jqXHR
(in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the
success setting can accept an array of functions. Each function will
be called in turn
Note that, value() is nothing in jQuery, you need to use val()
I suggest, along with success, you should also handle the error like following.
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Some error occurred");
}
For more details on $ajax, I suggest you to go through the documentation here
Hello there I am totally new to ASP.NET and learning it to my own. I am good at Java J2EE (Struts2 Framework)! I know how can i update or change any control/text inside any div element using struts2 and ajax code.
My Problem
Actaully, I'm trying to do the same thing in ASP.NET just for the learning! Suppose that I have a Default.aspx page with the javascript and ajax methods as:
<head runat="server">
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<script type="text/javascript">
function Change() {
$.ajax({
type: "GET",
url: "temp.aspx",
dataType: "text/html;charset=utf-8",
success: function(msg) {
$("#changer").html(msg);
}
});
}
</script>
<title>Untitled Page</title>
</head>
<body>
<div id="changer">//this is the div i want to update it using ajax
Hello Old Text
</div>
<input type="button"id="but" value="Hello Changer" onclick="Change()"/>
</body>
and suppose that I have my temp.aspx as:
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<div id="changer">
Hello New Text
</div>
</body>
I just want to know if this is possible in ASP.NET because with Java I am familiar with such an operation but I don't know why this is not working in case of ASP.NET!
Any hints or clues are favorable for me, Please don't mind for my question because I am totally new to ASP.NET but I am good at Java
Thanks in Advance!
dataType must define as html like this;
function Change() {
$.ajax({
type: "GET",
url: "temp.aspx",
dataType: "html",
success: function(msg) {
$("#changer").html(msg);
}
});
}
From jQuery Docs;
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
Additionally, you can inspect errors using error.
function Change() {
$.ajax({
type: "GET",
url: "temp.aspx",
dataType: "html",
success: function(msg) {
$("#changer").html(msg);
},
error: function(xhr, status, err) {
console.error(status, err.toString());
}
});
}
This is not related to ASP.NET or other web frameworks. It is just related to jQuery and Javascript. jQuery didn't recognise this "text/html;charset=utf-8". If you didn't use dataType, the ajax request worked successfully. It is just verification and result is interpreted according to dataType. For example, you are returning a JSON and the mime type of the your endpoint is not json (considering its mime type is html) just changing of the dataType as "JSON" you can parse the result as object.
I wrote a little script, in first example, I set dataType as HTML and in other example, I set dataType as JSON.
You could add a generec handler called Temp.ashx wich return the new text.
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Hello New Text");
}
In your ajax call you need to specify you are expecting a text.
<script type="text/javascript">
function Change() {
$.ajax({
type: "GET",
url: "temp.ashx",
dataType: "text/plain",
success: function(msg) {
$("#changer").html(msg);
}
});
}
</script>
this is my html code:
<form id="form" action="javascript:void(0)">
<input type="submit" id="submit-reg" value="Register" class="submit button" onclick="showtemplate('anniversary')" style='font-family: georgia;font-size: 23px;font-weight: normal;color:white;margin-top:-3px;text-decoration: none;background-color: rgba(0, 0, 0, 0.53);'>
</form>
this is my javascript code:
function showtemplate(temp)
{
$.ajax({
type: "POST",
url: 'ajax.php',
data: "section="+temp ,
success: function(data)
{
alert(data);
}
});
}
this is my ajax.php file:
<?php
$ajax=$_POST['section'];
echo $ajax;
?>
The above html and javascript code is included in a file named slider.php. In my index file i have included this slider.php file and slider.php is inside slider folder. So basically index.php and slider.php are not inside the same folder.
Javascript code alerts the data properly. But in my php code (ajax.php file) the value of $_POST['section'] is empty. What is the problem with my code. I tried googling everything and tried a few codes but it still doesn't work. Please help me out
Try this instead:
$.ajax({
type: "POST",
url: 'ajax.php',
data: { 'section': temp},
success: function(data)
{
alert(data);
}
});
It is quite possible that your server does not understand the string you have constructed ( "section="+temp ). When using ajax I prefer sending objects since for an object to be valid it requires a certain format.
EDIT1:
Try this and let me know if it doesn't work either:
$.post('ajax.php', {'section': temp}, function(data}{
alert(data);
});
Add jquery plugin(jQuery library) ,then only ajax call works
for eg
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
check your input data , whether it contain '&,/' charators,then use encodeURIComponent()
for Ajax Call Eg:
var gym_name = encodeURIComponent($("#gym_name").val());
$.ajax({
type: "POST",
url: "abc.php",
data:string_array,
success: function(msg) {
console.log(msg);
}
});
In abc.php
<?php
$id = $_POST['gym_name'];
echo "The id is ".id;
?>
Give a try to the following (although I cannot work out why #Grimbode's answer is not working):
$("#submit-reg").on( "click", function() {
$.ajax({
type: "POST",
url: 'ajax.php',
data: {'section': 'anniversary'},
success: function(data)
{
alert(data);
}
});
});
Note: I don't know what your underlying code is doing. However, I would suggest not using HTML element properties to handle events for numerous reasons, but separate the JS/event handling appropriately (separate js file(s) (recommended) or inside <script> tags). Read more...
I receive a json file from a python server, which I try to parse using ajax to display the values according to the categories(e.g.data_provider,census) in separate drop down menus .But i constantly get the following error:
Uncaught Error: Syntax error, unrecognized expression: [{"data_provider":"census","data_year":"2010","data_series":"sf1","tb_name":"h1","summ_level":"160"},{"data_provider":"census","data_year":"2010","data_series":"sf1","tb_name":"p1","summ_level":"050"}]
Kindly help me out ! Below is the code I wrote.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
function codeAddress() {
var ajax = $.ajax({
//data : params,
type : "GET",
crossDomain: true,
dataType: "json",
//jsonp: "callback",
//callbackParameter: "callback",
//contentType : "application/x-www-form-urlencoded",
url : "http://0.0.0.0:8080/"
});
ajax.done(function() {
var response=ajax.responseText;
var json = jQuery.parseJSON(response);
$(json).each(function(i,val){
$.each(val,function(k,v){
console.log(k+" : "+ v);
});
});
});
ajax.fail(function() {
alert("fail");
});
ajax.always(function() {
alert("done");
});
}
</script>
</head>
<body id="b1" onload="codeAddress();">
</body>
</html>
Because you're setting datatype to json, I'd guess you do not need to parse the JSON yourself. Please note that the parsed response is provided in the done method's first argument, see this example from the jQuery docs:
$.ajax({
url: "http://fiddle.jshell.net/favicon.png",
})
.done(function( data ) {
console.log( "Sample of data:", data.slice( 0, 100 ) );
});
If you're already using jQuery, just let them do the grunt work for you!
$.getJSON("http://0.0.0.0:8080/", function(json){
// do your JSON work here
});
If for whatever reason you can't use $.getJSON, in your $.ajax request, set a success callback function like the one i have over here.
I'm sending form data to a PHP file via AJAX, using jquery I hoped I could send the data easily seeing as it's only one text box etc. On submit click event the form data should be serialised and sent to submit.php, then I should get an alert from the php file with the response. Why doesn't it work?
Thanks.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
$('#submit').click(function (e) {
e.preventDefault();
$.ajax({type:'POST', url: 'submit.php', data:$('#myform').serialize(), success:
function(response) {
alert(response);
}});
});
</script>
Then the HTML:
<form id="myform" >
<input type="text" name="content" value="button should be on same line" /><input
type="submit" class="button" value="Submit" id="submit" />
</form>
You haven't initalized the DOM ?
$(document).ready(function(){
// do your work here
});
EDIT :
Try this:
$("#submit").live("click", function (e) {
e.preventDefault();
$.ajax({type:'POST', url: 'submit.php', data:$('#myform').serialize(), success:
function(response) {
alert(response);
}});
});
});
First, try to determine that the form is submitting correctly. try submitting to
url: '/submit.php'
instead, as that may not have been the correct path.
Second, try sending the value unserialized and see if you get a correct.