How can I send a text area content to my server? - javascript

I have been studying about ajax and this as far as I can get, I would like to send the text area's content to my server and save it in a text file, but I'm a little bit confused on how to do it, BTW my server is apache tomcat. I've heard that I need a piece of code on server side. Can you help me?
Thanks in advance.
$(document).ready(function() {
var data = new FormData();
var cssData = $("#custom-css-text").val();
data.append("custom_css", cssData);
$.ajax({
url: 'myserver',
type: 'POST',
data: {value:data},
cache: false,
dataType: 'json',
processData: false,
contentType: false,
success: function(response) {
alert(cssData);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('ERRORS: ' + textStatus);
}
});
});
#custom-css-text {
border-style: outset;
}
<!DOCTYPE html>
<html>
<head>
<title>HTML5, CSS3 and JavaScript demo</title>
</head>
<body>
<textarea id="custom-css-text">testing</textarea>
</body>
</html>

Related

How to post Json by .Ajax?

i want to post two items into server by using ajax in java-script; based on server-side document the post url is like this
http://example.com/h/{first-item}/{second-item}
this is my java-script code:
$('#add-order').on('click', function() {
var name = $('#name');
var drink = $('#drink');
var order = ?? // my question is this part what should i add
$.ajax({
type: 'POST',
url: 'http://example.com/h/',
data: order,
contentType: 'application/json',
success: function(data) {
console.log("Data added!", data);
}
});
});
and this is my HTML:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="input-group">
<h4>Add a Coffee Order</h4>
<p>name: <input type="text" id="name"></p>
<p>name_space: <input type="text" id="drink"></p>
<button id="add-order">Add!</button>
</div>
<script src="jquery.js"></script>
<script src="script.js"></script>
</body>
</html>
i am a new in ajax, thanks for your help.
You have to set the contentType to application/json in your Ajax request.
i.e as following:
$.ajax({
type: 'POST',
url: 'http://example.com/h/',
data: order,
contentType: "application/json",
dataType: "json",
success: function(data) {
console.log("Data added!", data);
}
});
});
here is an example for creating and encoding a json object.
var myObj = {
"name": $('#name').val(),
"drink": $('#drink').val()
};
var order = JSON.stringify(myObj);
Hard to really understand the post here, but it seems to me you simply forgot to mark the ajax requests contentType as json. See example below.
$.ajax({
type: 'POST',
url: 'http://example.com/h/',
data: order,
contentType: 'application/json'
dataType: 'json',
success: function(data) {
console.log("Data added!", data);
}
});

How to list results from JSON using Ajax

I have my first Ajax code and I am a little bit confused how to get all values from certain
<html>
<head>
<script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<title>My first Ajax</title>
</head>
<body>
<script type="text/javascript">
$(submit).click(function getResults() {
return $.ajax({
type: "GET",
url: "https://www.cs.kent.ac.uk/people/staff/lb514/hygiene/hygiene.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: "true",
cache: "false",
success: function(msg) {
// success
},
Error: function(x, e) {
// On Error
}
});
});
}
</script>
<input id="submit" name="submit" type="submit" value="Submit">
</input>
</body>
</html>
url. Following papers I have made code down below, but it does nothing to be honest. I would like to know how can I list certain data from this url?
There's many things you need to change (most of them are reference here: http://api.jquery.com/jquery.ajax/):
Use a newer version of jquery:
http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js
JS snipper should come after the element, as there's no element defined when JS executed
$(submit) is invalid. It should be $('#submit') as valid selector.
use evt.preventDefault() to prevent default browser behavior
url: you can't make request on another domain unless that url has enabled CORS (cross origin resource sharing), otherwise the request will work only on the same domain as your page. See an option on how to test locally: Jquery .ajax() local testing
async: true -> that's default so you can ommit
dataType -> that's fine if you expect JSON from server
contentType -> that's fine, but you don't send anything to the server, so it's not really needed
error: starts with lower letter
Here' the code updated:
<html>
<head>
<script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<title>My first Ajax</title>
</head>
<body>
<input id="submit" name="submit" type="submit" value="Submit">
<script type="text/javascript">
$("#submit").click(function(evt) {
evt.preventDefault();
$.ajax({
type: "GET",
url: "https://www.cs.kent.ac.uk/people/staff/lb514/hygiene/hygiene.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: "false",
success: function(msg) {
// success
},
error: function(x, e) {
// On Error
}
});
});
</script>
</body>
</html>
try this:
$('#submit').click(function() {
$.getJSON(url,function(data){
// Do whatever you need
});
});
First of all, your script should be defined after input tag. Also, make sure you have proper headers to access the url or it will give error related to Access-Control-Allow-Headers.
use loop for-in
$(submit).click(function getResults() {
return $.ajax({
type: "GET",
url:"https://www.cs.kent.ac.uk/people/staff/lb514/hygiene/hygiene.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: "true",
cache: "false",
success: function (msg) {
for (var i in data){
// data[i].something, etc
}
},
Error: function (x, e) {
// On Error
}
});
});

Send a Json object to server with javascript function

I try to send a json object to a distant server, but I didnt receive success message. please what's wrong with this code:
function sendSMS(){
var input = '{"header":"****","****":*****,"****":"*****"}';
var url = "https://**********&username=*****&password=*******";
jQuery.ajax({
type: "POST",
crossDomain:true,
url: url,
data: JSON.stringify(input),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function(){
alert("success");
}
});
}
// html code
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.json.org/json2.js"></script>
<script type="text/javascript" src="sendSMS.js"></script>
</head>
<body>
<button onclick="sendSMS()">sendSMS</button>
</body>
</html>
Any help please.
You have to simple change your ajax call to this:
function sendSMS(){
var input = '{"header":"Ooredoo","msisdn":21620117297,"SMS":"Hello"}';
var url = "https://**********&username=*****&password=*******";
jQuery.ajax({
type: "POST",
crossDomain:true,
url: url,
data: JSON.parse(input),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function(){
alert("success");
}
});
}
The main changes are JSON.stringify to JSON.parse this will help you to parse the JSON data into a JSON object, and the second change is the actual payload in which you missed a " at the end, just after Hello.
If you have any other question, just ask :)
Also I would recommend not to send the username and password as querystring parameter, use a POST request with a proper payload and last, if you can go through ssl

Weather.asmx web service from JavaScript- No output returns

I call http://wsf.cdyne.com/WeatherWS/Weather.asmx web service from JavaScript. And I pass data ZIP code as 10007(Hard coded). Want to get some output data. But when I run the code success message come as alert and then alert pop up says none. Seems there is no data returned. Can anyone edit the code to return proper output?
<html>
<head>
<title>Calling Web Service from jQuery</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#btnCallWebService").click(function (event) {
$.ajax({
type: "POST",
url: "http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityWeatherByZIP",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "10007",
success: processSuccess,
error: processError
});
});
});
function processSuccess(data, status, req) { alert('success');
if (status == "success")
$("#response").text($(req.responseXML).find("Result").text());
alert(req.responseXML);
}
function processError(data, status, req) {
alert('err'+data.state);
//alert(req.responseText + " " + status);
}
</script>
</head>
<body>
<h3>
Calling Web Services with jQuery/AJAX
</h3>
<input id="btnCallWebService" value="Call web service" type="button" />
<div id="response" ></div>
</body>
</html>
Did you enabled CORS
themessage i am getting when i tested in firebug is as below
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityWeatherByZIP. This can be fixed by moving the resource to the same domain or enabling CORS.
these links might help you
http://enable-cors.org/client.html
Firefox setting to enable cross domain ajax request
Try This
$.ajax({
url: "URL",
dataType: "json",
data: {term: request.term},
success: function(data) {
alert(data);
var dData = JSON.parse(data);
alert(dData.Name); //get your stuff
}
});

jquery ajax request success portion not working

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>

Categories

Resources