Html post is not working - javascript

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

Related

Ajax function only succeeds with "alert"

EDIT: My question is not a duplicate of No response from MediaWiki API using jQuery. Because even though it's a cross-domain request, I'm properly triggering JSONP behavior because jquery is automatically sending a callback parameter under the hood. (As you can see from the link I posted jQuery3100048749602337837095_1485851882249&_=1485851882253
EDIT2: Solved by #AnandMArora. Solution:
<input type="submit" onclick="getUserInput(event)" style="display:none"/>
and function
getUserInput(evt) { evt.preventDefault();
But since it's a comment I can't mark it as the answer. If there's an explanation why this method works (what is the default behavior that is prevented etc.) I will select it as the answer.
I assume that the "alert" method is buying time for the AJAX function since it's asynchronous. But I have no idea WHY do I need to buy time here. It should only be executed when getUserInput() calls getWiki() with the Input parameter.
In fact, I looked at the network monitor and even if we remove alert("") the proper URL is called (assuming "batman" was submitted).
Request URL: https://en.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&generator=search&exsentences=1&exlimit=max&exintro=1&explaintext=1&exsectionformat=wiki&gsrnamespace=0&gsrsearch=batman&callback=jQuery3100048749602337837095_1485851882249&_=1485851882253
If I open this link manually, it works fine.
But there's no status code returned and console logs "Error!"
function getUserInput(){
var Input = document.getElementById("searchBox").value;
getWiki(Input);
alert(""); //If we remove this line the request fails
}
function generatePage(rawData) {
console.log(rawData);
var mainData = rawData.query.pages;
$.each(mainData, function(value){
console.log((mainData[value].title + " " + mainData[value].extract));
});
}
function getWiki(Input){
$.ajax({
url: "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&generator=search&exsentences=1&exlimit=max&exintro=1&explaintext=1&exsectionformat=wiki&gsrnamespace=0&gsrsearch=" + Input,
dataType: "JSONP",
type: "GET",
success: function (rawData) {
generatePage(rawData);
},
error: function() {
console.log("Error!")
}
});
}
$(document).ready(function(){
})
The html I'm using to submit is:
<form class="searchForm">
<input type="text" name="searchRequest" id="searchBox" >
<input type="submit" onclick="getUserInput()" style="display:none"/>
</input>
</form>
My questions would be:
1) Why is this happening?
2) How can this be fixed without turning async off or using setTimeout() on the ajax function?
Wrap that console.log call inside a function:
function getWiki(Input){
$.ajax({
url: "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&generator=search&exsentences=1&exlimit=max&exintro=1&explaintext=1&exsectionformat=wiki&gsrnamespace=0&gsrsearch=" + Input,
datatype: "JSONP",
type: "GET",
success:
function (rawData){
generatePage(rawData);
},
error:
function(){
console.log("Error!")
}
});
}
Explanation:
The ajax call expects functions definitions to be passed to its event handlers ('success'/'error' in this case).
You do this for the success handler. For your error handler you are not pushing a function definition but a function that you are actually invoking (the console.log method).
Wrapping it in a function declaration (like what you did for the success event callback) allows you to define what happens on the callback when it is invoked rather than invoked it in-line.
You are using ajax, and the input control type of "submit" has a default action of postback for the form in which it is placed. So jQuery and most javascript code use the evt.preventDefault(); // evt is the object of event passed as a parameter for the click event function this prevents the default action i.e. submit the form.
Please make the changes as :
<input type="submit" onclick="getUserInput(event)" style="display:none"/>
and
function getUserInput(evt) { evt.preventDefault(); ...
this will most probably be the solution.
1)You have to specify a callback function, don't put code directly (otherwise it will be executed) but put it in a function
error: function(){console.log("Error!");}
2)In order to wait for the response, you have to specify that your request it synchronous
Set async option to false
If you need an asynchronous solution please see the following snippets (using done method instead of success property):
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>
<body>
<form class="searchForm">
<input type="text" name="searchRequest" id="searchBox" >
<input type="submit" onclick="javascript:getUserInput()" />
</input>
</form>
</body>
<script>
function getUserInput(){
var Input = document.getElementById("searchBox").value;
getWiki(Input);
//alert(""); //If we remove this line the request fails
}
function generatePage(rawData) {
console.log(rawData);
var mainData = rawData.query.pages;
$.each(mainData, function(value){
console.log((mainData[value].title + " " + mainData[value].extract));
})
}
function getWiki(Input){
$.ajax({
url: "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&generator=search&exsentences=1&exlimit=max&exintro=1&explaintext=1&exsectionformat=wiki&gsrnamespace=0&gsrsearch=" + Input,
dataType: "JSONP",
type: "GET",
async: true,
error: function(){console.log("Error!");}
}).done(
function (rawData) {
generatePage(rawData);
}
);
}
$(document).ready(function(){
})
</script>
</html>
I hope it helps you. Bye.

How to read json from url in javascript?

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

Changing a div/text using AJAX

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>

Display response to a GET & POST request in a textbox

I'm trying to get the response of a GET request inside a textfield on my webpage using jquery. Currently, I have the following code with which I can get the response on the console.
$(document).on('click', '#get-button', function(e) {
e.preventDefault();
$.ajax({
type: "GET",
url: $("#url").val(),
data: '',
success: function(response, textStatus, XMLHttpRequest) {
console.log(response);
}
});
return false;
});
$(document).on('click', '#post-button', function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: $("#url").val(),
data: $("#json-data").serialize(),
success: function(response, textStatus, XMLHttpRequest) {
console.log(response);
}
});
return false;
});
Below is a part of the HTML code where I want to fit the response(in JSON) format.
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="panel panel-danger">
<div class="panel-heading">JSON Response</div>
<div class="panel-body text-danger">
<textarea class="form-control" rows="8" placeholder="server response"></textarea>
</div>
</div>
</div>
</div>
Place your code in ready function, or add deffer to your script definition. In that way your script will execute after DOM is loaded.
Don't add events on docuemnt like this, it is too big. You are using id's, thats nice, so use it:) It depends on your DOM size, butin most cases find a element by id and then add event to it.
Add an id to your textbox, that will be more usable and faster.
.
$(document).ready(function(){
$('#get-button').on('click', function(e) {
e.preventDefault();
$.ajax({
type: "GET",
url: $("#url").val(),
success: function(response) {
console.log(response);
$('.form-control').val(response); // personally I would give your textbox an ID
}
});
return false;
});
$('#post-button').on('click', function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: $("#url").val(),
data: $("#json-data").serialize(),
success: function(response) {
console.log(response);
$('.form-control').val(response);
}
});
return false;
});
})
If your URL are correct, this will work.
Just remember that after you get the response, and you will get a JSON object, you will have to convert it to String using JSON.stringify().
I will try to explain. In Javascript we have Objects and simple types (boolean, String, float, etc). When we want to print a simple type, we just see it's value. But when we want to display a Object, JS engine has a problem, because each object can be very big, complex. Thats why when printing an object or JSON (witch is an Object) we get [Object]. Luckilly JSON is so popular that JS has an default methods for serializing String to JSON (JSON.parse(someString)) and other way around (JSON.stringify(JSONObject)).

Parse json using ajax

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.

Categories

Resources