I want to get Json data offered by 'http://localhost:8080/api/printer?exclude=temperature' [HTTP/1.1].
This is the Json data to be provided.
{
"state": {
"text": "Operational",
"flags": {
"operational": true,
"paused": false,
"printing": false,
"sdReady": true,
"error": false,
"ready": true,
"closedOrError": false
}
}
}
The type is 'GET' and Content-Type is 'application/json'
And below is my JSP whole source code.
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript" language="javascript">
function print_stat(){
jQuery.ajax({
type: 'GET',
async: false ,
url: 'http://localhost:8080/api/printer?exclude=temperature&apikey=1234567...',
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert("TEST");
},
error : function(x, e) {
alert('server error occoured');
if(x.status==0){ alert('0 error');
}else if(x.status==404){ alert('404 error');
}else if(x.status==500){ alert('500 error');
}else if(e=='parsererror'){ alert('Error.nParsing JSON Request failed.');
}else if(e=='timeout'){ alert('Time out.');
}else { alert(x.responseText); }
}
});
}
</script>
<body>
<input type="button" onclick="print_stat()" value="test">
</body>
I can't see "TEST" pop-up window.
And nothing happens.
What should I do for getting the data?
Please help me.
Can you try this,
Syntax:
$.ajax({
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
type: "POST",
url: uri,
data: jsonStrJson,
dataType: "json",
success: function(json){
console.log(json);
}
});
You code should be like this 100% working and tested code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript" language="javascript">
function print_stat(){
jQuery.ajax({
type: 'GET',
async: false ,
url: 'http://localhost:8080/api/printer?exclude=temperature&apikey=1234567...',
dataType: 'json',
success: function (data) {
alert("TEST");
console.log(data);
},
error : function(x, e) {
alert('server error occoured');
if(x.status==0){ alert('0 error');
}else if(x.status==404){ alert('404 error');
}else if(x.status==500){ alert('500 error');
}else if(e=='parsererror'){ alert('Error.nParsing JSON Request failed.');
}else if(e=='timeout'){ alert('Time out.');
}else { alert(x.responseText); }
}
});
}
</script>
<body>
<input type="button" onclick="print_stat()" value="test">
</body>
</body>
</html>
Related
I am getting error saying: SyntaxError: Unexpected token ':'. Parse error."
whether I do
url = 'http://api.openweathermap.org/v3/uvi/20,77/current.json?appid=c0d8761ca979157a45651a5c7f12a6be';
function getJSONP(url, success) {
var ud = '_' + +new Date,
script = document.createElement('script'),
head = document.getElementsByTagName('head')[0]
|| document.documentElement;
window[ud] = function(data) {
head.removeChild(script);
success && success(data);
};
script.src = url.replace('callback=?', 'callback=' + ud);
head.appendChild(script);
}
getJSONP(url, function(data){
console.log(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html><body>
or if I do :
url = 'http://api.openweathermap.org/v3/uvi/20,77/current.json?appid=c0d8761ca979157a45651a5c7f12a6be';
function CallURL() {
$.ajax({
url: url,
type: "GET",
dataType: "jsonp",
async: false,
success: function(msg) {
console.log(msg);
JsonpCallback(msg);
},
error: function() {
// ErrorFunction();
// break ;
}
});
}
function JsonpCallback(json) {
alert(json);
//document.getElementById('summary').innerHTML = json.result;
}
CallURL();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html>
<body>
</body>
</html>
This url doesn't return JSONP, it's return JSON:
{"time":"2017-02-25T12:00:00Z","location":{"latitude":18.75,"longitude":76.75},"data":10.8}
OpeanWeather API support JSONP only for few calls, like http://api.openweathermap.org/data/2.5/weather?q=London,uk&callback=test&appid=c0d8761ca979157a45651a5c7f12a6be, other call support only JSON, XML or HTML (see https://openweathermap.org/current for details).
So use json in ajax type call:
url = 'http://api.openweathermap.org/v3/uvi/20,77/current.json?appid=c0d8761ca979157a45651a5c7f12a6be';
function CallURL() {
$.ajax({
url: url,
type: "GET",
dataType: "json",
async: false,
success: function(msg) {
console.log(msg);
},
error: function() {
// ErrorFunction();
// break ;
}
});
}
CallURL();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html>
<body>
</body>
</html>
Trying to figure out how to report inside this popup only on failure. Currently this works, but it alerts for both success and failure:
<script>
function Unlock() {
var pin=prompt("You must enter pin to unlock");
$.ajax(
{
url: 'pin.php',
type: 'POST',
dataType: 'text',
data: {data : pin},
success: function(response)
{
alert(response);
console.log(response);
}
});
}
</script>
I have tried the following, but so far with no luck:
<script>
function Unlock() {
var pin=prompt("You must enter pin to unlock");
$.ajax(
{
url: 'pin.php',
type: 'POST',
dataType: 'text',
data: {data : pin},
success: function(response)
{
console.log(response);
},
error: function(response)
{
alert(response);
console.log(response);
}
});
}
</script>
Any help would be appreciated. Thanks!
* EDIT *
Here is the full code:
<?php
$static_password = "1234";
if(isset($_POST['data'])){
$submit_password = $_POST['data'];
if($submit_password == $static_password){
die("UNLOCK THE RECORD");
}
else{
die("SORRY WRONG PIN");
}
}
?>
<html>
<head>
<script src="js/jquery-3.1.1.min.js" type="text/javascript"></script>
</head>
<body>
<h2>Simple AJAX PHP Example</h2>
UNLOCK
<p>Pin is "1234"</p>
<script>
function Unlock() {
var pin=prompt("You must enter pin to unlock");
$.ajax(
{
url: 'pin.php',
type: 'POST',
dataType: 'text',
data: {data : pin},
success: function(response)
{
alert(response);
console.log(response);
}
});
}
</script>
</body>
</html>
For the error callback to be executed, server must respond with status of 404, 500 (internal error), etc. When you write die('blah'); server responds with a status of 200, and the message that it died with. This is a successfull request as far as both AJAX and PHP are concerned.
You have to check the response
if($submit_password == $static_password){
die("UNLOCK THE RECORD");
}
then:
success: function(response)
{
if (response == 'UNLOCK THE RECORD') { /* success */ }
else { /* failure, do what you will */ }
}
I'm calling a external JS file having some sample JSON code, when I try to put sample json code in the file, it throws me error at ":", but when I validate that using online tools, it says as valid json. What is going wrong in this code?
Here is my code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#click').click(function() {
$.ajax({
url: "json.js",
method: "GET",
dataType: 'application/json',
contentType: "application/json",
success: function(result){
console.log(result);
},
error:function() {
alert("Error")
}
});
});
});
</script>
My external json.js
{
"data": [{ ------> throwing error at ":" as Syntax error on token ":", ; expected
"Service": "INSTACC",
"Create Date": "30-Jul-2016"
}, {
"Service": "INSTACC",
"Create Date": "30-Jul-2016"
}]
}
Change your file type to json and dataType to "json"
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#click').click(function() {
$.ajax({
url: "json.json",
method: "GET",
dataType: 'json',
success: function(result){
console.log(result);
},
error:function() {
alert("Error")
}
});
});
});
</script>
"application/json" is not a valid value for the dataType property. Change it to dataType: 'json',
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MyDemo</title>
</head>
<body>
<button id="click">Click Me</button>
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#click').click(function() {
$.ajax({
url: "json.js",
method: "GET",
dataType: 'json',
contentType: "application/json",
success: function(result){
console.log(result);
},
error:function(req, status, err) {
console.log(req);
console.log(status);
console.log(err);
}
});
});
});
</script>
</body>
</html>
I am trying to send a variable to PHP using JavaScript but I don't get any response whatsoever. Any ideas?
PHP/HTML:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="dashmenu.js"></script>
</head>
<body>
<?php
$selection = $_POST['selection'];
if($selection == 'profile'){
?>
<p> it works
<?php
}
?>
<button id="button"> profile </button>
</body>
JS file (dashmenu.js):
$('#button').click(function() {
var menuSelection = "profile";
$.ajax({
type: 'POST',
url: 'dashboard.php',
data: {selection: menuSelection},
success: function(response) {
alert('success');
}
});
});
In your html file (let's say index.html) you could have:
$('#button').click(function() {
var menuSelection = "profile";
$.ajax({
type: 'POST',
dataType: "html",
url: 'dashboard.php',
data: {selection: menuSelection},
success: function(response) {
alert(response);
},error: function(jqXHR, textStatus, errorThrown){
alert('Error: ' + errorThrown);
}
});
});
In your dashboard.php, you should ONLY have code that processes requests, and returns (echoes) the desired output:
<?php
$selection = $_POST['selection'];
if($selection == 'profile'){
echo "It works";
}else{
echo "It failed";
}
?>
$('#button').click(function() {
var menuSelection = "profile";
$.ajax({
type: 'POST',
url: 'dashboard.php',
data: {selection: menuSelection},
success: function(response) {
alert('success');
}
});
});
Run this in your console in your browser.
Right-click > Console tab.
If you want to check whether this function has successfully bind to the button. If your browser returns you 'success' alert, meaning you include it wrongly I guess.
If nothing happen when you click, please include .fail() in your $.ajax()
Which will look like this:
$.ajax({
type: 'POST',
url: 'dashboard.php',
data: {
selection: menuSelection
},
success: function(response) {
alert(response);
},
error: function(jqXHR, textStatus, errorThrown){
}
});
I have a problem on ajax call.
Here is my code regarding the ajax:
$('#Subjects').click(function() {
$.ajax({
type: 'POST',
url: '../portal/curriculum.php',
data: 'studentNumber='+$('#StudentID').val(),
success: function(data)
{
$('#curriculum').html(data);
}
});
});
When I echo studentNumber on another page, the studentNumber is undefined. Why is that?
Simply modify your code like this:
JS
$('#Subjects').click(function() {
$.ajax({
type: 'POST',
url: '../portal/curriculum.php',
data: { studentNumber: $('#StudentID').val() },
success: function(data)
{
$('#curriculum').html(data);
}
});
});
PHP
<?php
$var = $_POST['studentNumber'];
?>
If you still can not make it works.. other things you should consider..
url: '../portal/curriculum.php',
1) Please use full URL http://yourdomain.com/portal/curriculum.php or absolute path like /portal/curriculum.php
2) Add an error callback to check out the error message
$('#Subjects').click(function() {
$.ajax({
type: 'POST',
url: '../portal/curriculum.php',
data: { studentNumber: $('#StudentID').val() },
success: function(data)
{
$('#curriculum').html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.post("test1.php",
{
name: "Makemelive Technologies",
city: "Mumbai"
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>
<button>Send an HTTP POST request to a page and get the result back</button>
</body>
</html>
The above will make a call to test1.php and its code will be
<?php
$fname=$_REQUEST['name'];
$city= $_REQUEST['city'];
echo "Company Name is ". $fname. " and it's located in ". $city ;
?>
$('#Subjects').click(function() {
$.ajax({
type: 'POST',
url: '../portal/curriculum.php',
data: { studentNumber: $('#StudentID').val() },
success: function(data)
{
//here data is means the out put from the php file it is not $('#StudentID').val()
$('#curriculum').html(data);
}
});
});
as exsample if you echo some text on php it will return with data $('#curriculum').html(data);
try to change
//change
success: function(data)
{
$('#curriculum').html(data);
//to
success: function(result)
{
$('#curriculum').html(result);
check what will happen.
post us php file too curriculum.php
You can use through Jquery,Ajax and php
step 1. index.php
<div id="div_body_users">
</div>
<form method="post" id="frm_data" action="">
<input type="button" id="target" name="submit" value="submit">
<input type="key" id="key" name="key" value="1234">
</form>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
$(document).ready(function(){
$( "#target" ).click(function() {
// alert("test");
var frm_mail = document.getElementById("frm_data");
var frm_mail_data = new FormData(frm_mail);
$.ajax({
url: "http://localhost/test.php",
data: frm_mail_data,
cache: false,
processData: false,
contentType: false,
type: 'POST',
success: function (result) {
document.getElementById('div_body_users').innerHTML=result;
}
});
});
});
</script>
step 2. create test.php
<?PHP
//print_r($_POST);
if($_POST['key']=='1234'){
echo "success";
exit(0);
}
?>
$.ajax({
type: "GET",
url: "view/logintmp.php?username="+username+"&password="+password,
}).done(function( msg ) {
var retval = printmsgs(msg,'error_success_msgs');
if(retval==1){
window.location.href='./';
}
});