I have an html form from which I need to collect data and call a POST on a rest api. I am trying to do this using javascript and $.ajax but confused on how to setup the URL and collect data as I am very new to it. Could someone explain this fully, with an example if possible as I'm having trouble finding detailed documentation.
Try this:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<input type="text" value="3" name="id" id="GetId">
<button id="LoginBtn">login</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<script>
$("#LoginBtn").click(function (e){
e.preventDefault();
var settings = {
"url": "http://192.168.1.3:8071/user/login",
"method": "POST",
"headers": {
"Content-Type": "application/json"
},
"data": JSON.stringify({"username":"user","password":"123456"}),
};
$.ajax({
...settings,
success: function (result) {
alert("success")
},
error : function (){
alert("error")
}
})
})
</script>
</body>
</html>
Please read this simple article
https://javascript.info/fetch
You could use axios or jquery but fetch api is really simple
Related
I am trying to run an ajax script from javascript inside a PHP file :
$(document).on('click', '.goto_date', function(){
var datechosen= $('#pickdate').val();
alert(datechosen);
$.ajax({
url:"vdater.php",
method:"POST",
dataType:"json",
data:{'datechosen':datechosen},
success:function(data){
alert('success');
}
});
});
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<div align="center">
<input type="button" name="gotodate" value="Go to date" id="gotodate" class="btn btn-danger btn-xs goto_date" />
<input type="date" name='pickdate' id='pickdate' />
</div>
</body>
</html>
But when I run the code nothing happens apart from the alert box referring that the ajax script is reachable in the code..
The PHP file may contain the following code:
echo $_POST['datechosen'];
Surprisingly, It worked by removing the line:
dataType:"json",
Try this one. It must be worked!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Get Ajax Response</title>
</head>
<body>
<div align="center">
<input type="button" name="gotodate" value="Go to date" id="gotodate" class="btn btn-danger btn-xs goto_date" />
<input type="date" name='pickdate' id='pickdate' />
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
let dateBtn = document.querySelector('#gotodate');
let getDate = document.querySelector('#pickdate');
dateBtn.addEventListener('click',(event)=>{
event.preventDefault();
if(getDate.value.trim() !== ""){
console.log(getDate.value.trim());
dateBtn.style.borderColor = "transparent"
jQuery.ajax({
type: "POST",
url: "vdater.php",
data:{
datechosen: getDate.value.trim()
},
success: ((response,status, object) => {
response = JSON.parse(response);
if(response.status){
alert(`Date Chosen: ${response.PickedDate}`);
}
})
});
}else{
dateBtn.style.border = "1px solid #fb5757";
}
});
</script>
</body>
</html>
<?php
if(isset($_POST['datechosen'])){
$date = $_POST['datechosen'];
echo json_encode(["PickedDate"=> $date,"status"=>true]);
}
I am trying post a Webhook using javascript. My goal is to allow the user to type their Webhook URL, and when they click "send", it should send my Webhook message.
I am new to Javascript and not sure what I am doing wrong!
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div class="background">
<input type="text" id="input" placeholder="paste webhook here">
<button id="send" onclick="sendMessage()">send</button>
</div>
</body>
<script src="index.js"></script>
</html>
Javascript:
function sendMessage() {
let grabData = document.getElementById("input");
var request = new XMLHttpRequest();
request.open("POST", grabData);
request.setRequestHeader('Content-type', 'application/json');
var myEmbed = {
title: "Test Successful! 🥳",
color: hexToDecimal("#2A67E8")
}
var params = {
username: "objexive",
avatar_url: "https://i.ibb.co/7X9szNY/exhbition-webhookicon1.png",
embeds: [ myEmbed ]
}
request.send(JSON.stringify(params));
// function that converts a color HEX to a valid Discord color
function hexToDecimal(hex) {
return parseInt(hex.replace("#",""), 16)
}
}
for anyone that has the problem, it was a very simple fix. add .value to "grabData"
I am new to programming.
My question is the following:
Is there some kind of template for subpages, for example on the homepage of the website.
I would like to create a few sub-pages that have the same structure, but deal with a different topic.
Is there something I can read into or something I can find out about?
PHP is a programming language and it is also a template engine. There are several ways to tackle the problem you have outlined.
Index.php would look like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Hello</h1>
<div>Lions</div>
<div>Narwhals</div>
<div>Chimps</div>
<div>Hawk</div>
</body>
</html>
topic.php
<?php
class TopicData
{
// Use a static function to get the data for a keyword
public static function text($keyword){
$file = "topics.json";
// If the file doesn't exist, just say there is no data
if ( ! file_exists($file) ) {
return "No information on topic";
}
$topics = json_decode(file_get_contents($file));
$text = $topics->{$keyword} ?? "No information on topic";
return $text;
}
}
$text = TopicData::text($_GET['a']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div style="">
<?= $text ?>
</div>
</body>
</html>
topic.json
I use a json file to store some test data.
{
"lions": "Lions go here",
"narwhals": "Narwhals have tusks",
"chimps": "Chimps can't read",
"hawk": "Hawks fly iini the day time"
}
Right now I am just trying to get the API call to work, nothing fancy. In the end I will only want some basic info like name, runtime, rating and description... but that is all later. I can't even get the API call to work.
I have done several tutorials and I seem to be missing something.
HTML
<head>
<title>Watch a movie!</title>
<meta charset = "UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta name="description" content="">
<meta name="keywords" content="">
<link href="css/bootstrap.css" rel="stylesheet" type="text/css">
<link href="css/style.css" rel="stylesheet" type="text/css">
<script src="js/angular.min.js"></script>
<script src="http://code.angularjs.org/1.2.0rc1/angular-route.min.js"></script>
<script src="controllers/movies.js"></script>
</head>
<body>
<div id="wrapper">
<button type="button" class="btn btn-primary btn-lg btn-block">NOW PLAYING</button>
<button type="button" class="btn btn-default btn-lg btn-block">COMING FRIDAY</button>
<!-- PLACEHOLDER -->
<div id="movieInfoBox">
<div ng-controller = "movieController">{{movies}}</div>
</div>
</div> <!-- END WRAPPER -->
JS
var movies = angular.module("movies", []); //quotes are name of this file
movies.controller("movieController", function ($scope, $http){ //quotes are name of function called in index
$http.jsonp("http://api.rottentomatoes.com/api/public/v1.0/movies/155655062.json?apikey=wq98h8vn4nfnuc3rt2293vru")
.sucess(function(data)
{$scope.movies = data;})
.error(function(data){});
});
You have to include the JSON_CALLBACK in the URL. Otherwise the API returns JSON instead of JSONP. In the code below I use a config object instead of the parameters directly in the query string. It's just because it's easier to read, you can also use your version and add &callback=JSON_CALLBACK to the URL. See 'jsonp' in the docs
Working Fiddle: http://jsfiddle.net/pascalockert/fM7jb/
Code in the controller:
$http.jsonp('http://api.rottentomatoes.com/api/public/v1.0/movies/155655062.json', {
params: {
apikey: 'wq98h8vn4nfnuc3rt2293vru',
callback: 'JSON_CALLBACK'
}
})
.success(function (data) {
$scope.movies = data;
});
I have a simple login page that sends the login information to the servlet, and in response receives one parameter which is interpreted in jQuery.
Data is sent correctly, goes to the servlet which also sets the parameter correctly (I can see that in the Firebug in the response header).
The problem is when I want to retrieve data from the returned response and assign it to a JavaScript variable. The request object is empty, while in Chrome inspect I see an alert:
Uncaught TypeError: Object has no method 'getResponseHeader'.
When I display it using console.log () does not return anything to me, no value.
<!DOCTYPE html>
<html lang="en">
<head>
<%#page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="../../assets/ico/favicon.png">
<link
href="http://minikomi.github.io/Bootstrap-Form-Builder/assets/css/lib/bootstrap.min.css"
rel="stylesheet">
<link
href="http://minikomi.github.io/Bootstrap-Form-Builder/assets/css/lib/bootstrap-responsive.min.css"
rel="stylesheet">
<link
href="http://minikomi.github.io/Bootstrap-Form-Builder/assets/css/custom.css"
rel="stylesheet">
<script src="http://code.jquery.com/jquery-2.0.3.js"></script>
<script src="../js/jquery.validate.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Logowanie</title>
<!-- Bootstrap core CSS -->
<link href="../css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="../css/signin.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="../../assets/js/html5shiv.js"></script>
<script src="../../assets/js/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<form class="form-signin" action="Login" method="post">
<h2 class="form-signin-heading">Logowanie</h2>
<input type="email" name="email" class="form-control" id="email"
placeholder="Adres email" autofocus>
<input type="password" id="password"
name="password" class="form-control" placeholder="Haslo">
</form>
<button id="zaloguj" value="zaloguj" class="btn btn-success btn-large">
<i class="icon-white icon-th-list"></i>Zaloguj
</button>
</div>
<!-- /container -->
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script type="text/javascript">
$('#zaloguj').click(function() {
var email = $("#email").val();
var password = $("#password").val();
console.log(email+password);
var data = "email=" + email + "&password=" + password;
$.ajax({
url : "Login",
type : "POST",
data : data,
success : function(request) {
console.log(request);
var log = request.getResponseHeader("log");
console.log(log);
if (log == 1) {
$( ":header" ).after("Poprawne logowanie").css({ background: "#ccc", color: "green" });
document.location.href = '/landing.html';
} else {
$( ":header" ).after("Błędne logowanie").css({ background: "#ccc", color: "red" });
}
},
});
});
</script>
</body>
</html>
Looks like your using the wrong overload for success.
success : function(request) {
console.log(request);
var log = request.getResponseHeader("log");
should be:
success : function(data, status, xhr) {
console.log(data);
var log = xhr.getResponseHeader("log");
See the docs
success Type: Function( PlainObject data, String textStatus, jqXHR
jqXHR )
Then
The jqXHR Object
The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of
jQuery 1.5 is a superset of the browser's native XMLHttpRequest
object. For example, it contains responseText and responseXML
properties, as well as a getResponseHeader() method.
The success function returns ( PlainObject data, String textStatus, jqXHR jqXHR ). What you are looking for is the last parameter and not the response itself.
success: function(request, status, xhr) {
console.log(xhr.getResponseHeader("log"));
}