vscode live server extension cuts off JavaScript code - javascript

I am trying to make a online booking system. And I am using vscode live server for live web for testing. I noticed that it cuts off a huge chunk of js code. I am using the newest version of vscode and google chrome. If you need any more information, feel free to ask me :).
Expected Behaviour:
<script>
window.addEventListener("DOMContentLoaded", function () {
// get the form elements defined in your form HTML above
var form = document.getElementById("my-form");
// var button = document.getElementById("my-form-button");
var status = document.getElementById("status");
// Success and Error functions for after the form is submitted
function success() {
form.reset();
status.classList.add("success");
status.innerHTML = "Thanks!";
}
function error() {
status.classList.add("error");
status.innerHTML = "Oops! There was a problem.";
}
// handle the form submission event
form.addEventListener("submit", function (ev) {
ev.preventDefault();
var data = new FormData(form);
ajax(form.method, form.action, data, success, error);
});
});
// helper function for sending an AJAX request
function ajax(method, url, data, success, error) {
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.setRequestHeader("Accept", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState !== XMLHttpRequest.DONE) return;
if (xhr.status === 200) {
success(xhr.response, xhr.responseType);
} else {
error(xhr.status, xhr.response, xhr.responseType);
}
};
xhr.send(data);
}
</script>
Actual Behavior:
<script>
window.addEventListener("DOMContentLoaded", function () {
// get the form elements defined in your form HTML above
var form = document.getElementById("my-form");
// var button = document.getElementById("my-form-button");
var status = document.getElementById("status");
// Success and Error functions for after the form is submitted
function succe</script>

Reload the webpage and it should work.

Related

location.href not working after ajax response

I have an form that when it sumits the data it echo "success", I used the success to trigger a redirect to another page but it is not working. I have tried everything. The else statement works fine but whatever i write in the if(data == "success") is not working including console.log and alert.`
continueBtn.onclick = () =>{
//Ajax code
let xhr = new XMLHttpRequest();// this will create a new XML Object
xhr.open("POST", "php/signup.php", true );
xhr.onload = () =>{
if(xhr.readyState === XMLHttpRequest.DONE){
if(xhr.status === 200){
let data = xhr.response;
if(data == "success"){
errorTxt.textContent = "Thuinsowofnd wsikenon";
window.location.href = 'users.php';
}else{
errorTxt.textContent = data;
errorTxt.style.display = "block";
}
}
}
}
//let's send form data through Ajax to Php
let formData =new FormData(form);//this will create a new form object
xhr.send(formData);// this will the form data
`
I have tried using windows.location.href = "users.php" but it still doesn't work

PHP Redirect and Ajax

I have a registration form. The register.php is checking for errors such as short password
AJAX gives an alert with the echo error from PHP.
With PHP, after an if else statement
the user will be registered and redirected successfully to Location:index.php (good)
register.php
The problem is, if there is any error, the user will be redirected to register.php
and the echo alert shows there (on white page)
AJAX
var form = document.querySelector('.register form');
form.onsubmit = function(event) {
event.preventDefault();
var form_data = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open('POST', form.action, true);
xhr.onload = function() {
document.querySelector('.msg').innerHTML = this.responseText;
};
if (xhr.status >= 200 && xhr.status <= 299) {
var response = JSON.parse(xhr.responseText);
if (response.location) {
window.location.href = response.location;
} else {
xhr.send(form_data);
}
}
Example 2: the alerts will display properly at <div class="msg"></div> position
(But will also throw the index.php on the msg div(same page where the alerts go)
var form = document.querySelector('.register form');
form.onsubmit = function(event) {
event.preventDefault();
var form_data = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open('POST', form.action, true);
xhr.onload = function() {
document.querySelector('.msg').innerHTML = this.responseText;
};
xhr.send(form_data);
};
So, i want the user to be redirected to index.php & also the echo errors (register.php) to be handled by AJAX
Please understand that im new & learning, i spent a week in this.
If you choose to resolve this, please fix based off register.php and ajax code

How get steam nickname via javascript

Hello i now using this php code for get steam nicknames
function EchoPlayerName($steamid){
$xml = simplexml_load_file("http://steamcommunity.com/profiles/$steamid/?xml=1");//link to user xml
if(!empty($xml)) {
$username = $xml->steamID;
echo $username;
}
}
or
$steam = file_get_contents("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key={API_KEY}&steamids=$steamid64", true);
$steamarray = json_decode($steam, true);
$name = $steamarray['response']['players'][0]['personaname'];
but i this using for listing players and loading page is slow
so i want this data load via javascript after full load page
any ideas?
API example
{"response":{"players":[{"steamid":"76561197964477177","communityvisibilitystate":3,"profilestate":1,"personaname":"The [G]amerX #π—™π—¨π—‘π—£π—Ÿπ—”π—¬.𝗽𝗿𝗼","lastlogoff":1558765863,"commentpermission":1,"profileurl":"https://steamcommunity.com/id/gamerxcz/","avatar":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/66/6673d6df066386d232164e8f9a5d9b36cad1d013.jpg","avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/66/6673d6df066386d232164e8f9a5d9b36cad1d013_medium.jpg","avatarfull":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/66/6673d6df066386d232164e8f9a5d9b36cad1d013_full.jpg","personastate":0,"realname":"Community Owner","primaryclanid":"103582791433644720","timecreated":1076786008,"personastateflags":0,"loccountrycode":"CZ"}]}}
First, you should get Data using ajax of pure javascript or jquery. Then you should target an HTML element that you want to fill it using this retrieved data. Imagine element with ID target.
jQuery:
$(document).ready(function () {
$.ajax({
url: "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key={API_KEY}&steamids=$steamid64",
}).done(function (data) {
var json = JSON.parse(data);
$('#target').text(json['response']['players'][0]['personaname']);
});
});
pure javascript:
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key={API_KEY}&steamids=$steamid64');
xhr.onload = function () {
if (xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
document.getElementById('target').innerHTML = json['response']['players'][0]['personaname'];
} else {
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send();
Remember to place these scripts at the end of your document.

Trouble with PHP form and Ajax

I’m trying to submit a form with data to a php file without reloading the page. I also have some js code that changes the form name and values when the next btn is clicked. I had 10 questions all on 1 page and I got it to work with PHP but now I’m trying to get 1 question per page. I looked in the network tab and it looks like the xhr requests are being sent but in my database.php file I wrote $user_anwser = $_POST[β€˜quiz_1’]; and var dumped it and I get a NULL value. Here is the ajax code.
form.addEventListener("submit", function(e){
if (ind < 10){
e.preventDefault();
} else {
form.setAttribute("action", "results.php");
}
let data = new FormData(form);
let xhr = new XMLHttpRequest();
xhr.open('POST', '../private/database.php');
xhr.onload = function() {
if (xhr.status === 200) {
// if the response is json encoded
let response = JSON.parse(xhr.responseText); // i get a parse error there
if (response.message == 'valid') {
// redirect here
}
}
// }
xhr.send(data);
}
});

Passing values from javascript to servlet not working in chrome

Im trying to pass parameters to servlet from javascript with :
function selectHandler() {
var selection = table.getChart().getSelection()[0];
var topping = data.getValue(selection.row, 0);
var answer=confirm("Delete "+topping+"?");
if(answer){
document.location.href="/item?_method=delete&id="+topping;
alert(topping+" has been deleted");
location.reload();
}
else return false;
}
The values are getting passed to the servlet and is working fine when I'm using firefox as in I'm getting the url as: http://XXXXXXX/item?_method=delete&id=xxxx
But when I'm using chrome the URL that is send is http://XXXXXXX/item. as the values are not getting passed!! I have tried with window.location.href also with no change. what could be the issue?
What you need is ajax call or say XMLHttpRequest as below:
<script type="text/javascript">
function doAjax () {
var request,
selection = table.getChart().getSelection()[0],
topping = data.getValue(selection.row, 0),
answer=confirm("Delete "+topping+"?");
if (answer && (request = getXmlHttpRequest())) {
// post request, add getTime to prevent cache
request.open('POST', "item?_method=delete&id="+topping+'&time='+new Date().getTime());
request.send(null);
request.onreadystatechange = function() {
if(request.readyState === 4) {
// success
if(request.status === 200) {
// do what you want with the content responded by servlet
var content = request.responseText;
} else if(request.status === 400 || request.status === 500) {
// error handling as needed
document.location.href = 'index.jsp';
}
}
};
}
}
// get XMLHttpRequest object
function getXmlHttpRequest () {
if (window.XMLHttpRequest
&& (window.location.protocol !== 'file:'
|| !window.ActiveXObject))
return new XMLHttpRequest();
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) {
throw new Error('XMLHttpRequest not supported');
}
}
</script>
You can also do it easily by jquery,
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" />
<script type="text/javascript">
function doAjax () {
...
$.ajax({
url: "item?_method=delete&id="+topping+'&time='+new Date().getTime()),
type: "post",
// callback handler that will be called on success
success: function(response, textStatus, jqXHR){
// log a message to the console
console.log("It worked!");
// do what you want with the content responded by servlet
}
});
}
</script>
Ref: jQuery.ajax()

Categories

Resources