This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 3 years ago.
So I want to pass my JS array to my PHP code with AJAX, and I am facing a problem.
My problem is the following: When I send my array to the php, it gives me the following error:
Notice: Undefined index: foods_added in
C:\xampp\htdocs\etterem\order-food.php on line 2
My codes are the following:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Rendelés felvétele</title>
<style type="text/css">
body{
font-family: Arail, sans-serif;
}
.search-box{
width: 300px;
position: relative;
display: inline-block;
font-size: 14px;
}
.search-box input[type="text"]{
height: 32px;
padding: 5px 10px;
border: 1px solid #CCCCCC;
font-size: 14px;
}
.result{
position: absolute;
z-index: 999;
top: 100%;
left: 0;
}
.search-box input[type="text"], .result{
width: 100%;
box-sizing: border-box;
}
.result p{
margin: 0;
padding: 7px 10px;
border: 1px solid #CCCCCC;
border-top: none;
cursor: pointer;
}
.result p:hover{
background: #f2f2f2;
}
.list {
padding-top: 20px;
}
.result {
background-color: white;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
// var fields = 1;
// function add_fields() {
// fields++;
// var objTo = document.querySelector('.search-box')
// var divtest = document.createElement("div");
// divtest.innerHTML = '<input type="text" autocomplete="off" placeholder="Étel keresése"/><div class="result"></div>';
// objTo.appendChild(divtest)
// }
var foods_added = [];
function add_food() {
var food_name = document.getElementById('food_name').value;
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(food_name));
list.appendChild(entry);
foods_added.push(food_name);
document.getElementById('food_name').value = "";
}
function submit_list() {
$.ajax({
url: "order-food.php",
method: "post",
data: { foods_added : JSON.stringify(foods_added) },
success: function(res) {
console.log(res);
}
})
window.location.href = "order-food.php";
}
$(document).ready(function(){
$('.search-box input[type="text"]').on("keyup input", function(){
var inputVal = $(this).val();
var resultDropdown = $(this).siblings(".result");
if(inputVal.length){
$.get("backend-search.php", {term: inputVal}).done(function(data){
resultDropdown.html(data);
});
} else{
resultDropdown.empty();
}
});
$(document).on("click", ".result p", function(){
$(this).parents(".search-box").find('input[type="text"]').val($(this).text());
$(this).parent(".result").empty();
});
});
</script>
</head>
<body>
<!-- <input type="button" onclick="add_fields();" value="Hozzáad"> -->
<div class="search-box">
<input id="food_name" type="text" autocomplete="off" placeholder="Étel keresése" />
<div class="result"></div>
<input style="width: 130px;" type="button" onclick="add_food();" value="Hozzáad">
<input style="width: 130px;" type="button" onclick="submit_list();" value="Rendelés felvétele">
</div>
<div class="list">
<ol id="list" name="food"></ol>
</div>
</body>
</html>
<?php
$added_foods = json_decode($_POST['foods_added']);
?>
The second code is order-food.php, which I would use to work with the array (in the end it would submit the items of the array into a database)
You start the ajax request but then you refresh the page by calling
window.location.href = "order-food.php";
so the ajax request is halted and the page reloads, with no post values. Just delete that line, to let the request finish.
Then the method is set with the "type" parameter, not "method". So change the line in the ajax request from
method:"POST"
to
type:"POST"
Related
I found a GAS that will search a column for an ID number that has been entered to a Google Sheet by means of an HTML form. Once the ID# is found it will check a date in a different column and will return a message based on the date in the column relative to today's date. When I run the GAS I get the message returned to me from the result of the script but what I am looking to do is return the result of the script back to the webform to notify a user of the message after they submit the form. It doesn't have to be a GAS ... if anyone can do the same with Javascript I am all ears. Thanks in advance.
I have already tried to figure out how to call on the GAS from the html page but have had no success.
GAS:
<!-- Search Sheet for Bottle Expiration date -->
var ss = SpreadsheetApp.openByUrl("GSURL");
var sheet = ss.getSheetByName("Entries");
function doGet(e){
return search(e) ;
}
function doPost(e){
return search(e) ;
}
function search(e){
var id = e.parameter.last_name;
var values = sheet.getRange(2, 2, sheet.getLastRow(),sheet.getLastColumn()).getValues();
for(var i = 0;i<values.length; i++){
if(values[i][0] == id ){
i=i+2;
var name = sheet.getRange(i,4).getValue();
var hydroDate = Date.now()+14;
var hydroalert = ContentService.createTextOutput("Bottle is due for Hydro").setMimeType(ContentService.MimeType.TEXT)
if (hydroDate <= name)
return hydroalert;
}
}
return ContentService.createTextOutput("Id not found").setMimeType(ContentService.MimeType.TEXT);
}
HTML Page
<!DOCTYPE html>
<html>
<head><meta name="viewport" content="width=device-width, initial-scale=1" />
<title>UFD Tour 2 Monthlies</title>
<!-- <link rel="stylesheet" type="text/css" href="style.css" media="screen, handheld"/> -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js?rev=<?php echo time();?>"></script>
<script type="text/javascript" src="ufd_tour_2_monthlies.js?rev=<?php echo time();?>"></script>
<script type="text/javascript" src="qrscan.js?rev=<?php echo time();?>"></script>
<script src="https://rawgit.com/sitepoint-editors/jsqrcode/master/src/qr_packed.js">
</script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<!-- Place this within the <head> tag or just before the end of your <body> tag. -->
<script src="https://awesome-table.com/AwesomeTableInclude.js"></script>
</head>
<style>
h2 {
text-align: center;
}
input[type=text], input[type=password] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}
button {
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
}
.cancelbtn {
padding: 14px 20px;
background-color: #f44336;
}
.cancelbtn,.signupbtn {
float: left;
width: 50%;
}
.container {
padding: 16px;
}
.clearfix::after {
content: "";
clear: both;
display: table;
}
#media screen and (max-width: 300px) {
.cancelbtn, .signupbtn {
width: 100%;
}
}
.form_container { width: 90%; max-width:450px; margin:20px 30px 40px 30px; padding:15px 20px; font-size:15px; line-height:25px; text-align:left; background:#EBEBEB; }
.form_field { display:block; width:100%; height:30px; margin:5px 0px 10px 0px; padding:0px 10px; color:#333; font-size:16px; border:1px solid #999; border-radius:3px; -webkit-appearance:none; }
.form_button { display:block; width:100%; height:35px; margin:20px 0px; padding:0px 0px; color:#FFF; font-size:16px; font-weight:bold; border:1px solid #3E7998; border-radius:3px; background:#3E7998; -webkit-appearance:none; }
.form_message { }
body, input {font-size:14pt}
input, label {vertical-align:middle}
.qrcode-text { display:block; width:90%; height:30px; margin:5px 0px 10px 0px; padding:0px 10px; color:#333; font-size:16px; border:1px solid #999; border-radius:3px; -webkit-appearance:none; }
.qrcode-text-btn { display:block; text-align:center; width:90%; height:35px; margin:20px 0px; padding:0px 0px; color:#FFF; font-size:16px; font-weight:bold; border:1px solid #3E7998; border-radius:3px; background:#3E7998; -webkit-appearance:none; }
.qrcode-text-btn > input[type=file] {position:absolute; overflow:hidden; width:1px; height:1px; opacity:0}
</style>
<body>
<h2>Tour 2 Monthlies</h2>
<div class="container">
<form id="sheets" name="sheets" class="form_body">
<label for="first_name">Date</label>
<input id="first_name" name="first_name" type="date" class="form_field" value="" placeholder="Select Date"/>
<label for="last_name">Bottle Number</label>
<input id="last_name" name="last_name" class="form_field" onfocus="this.value='';" value="" placeholder="Select here to scan or enter manually"/>
<input type="button" name="btnScanBarcode" id="btnScanBarcode" class="form_button" value="Scan Bottle" onclick="javascript:openQRCamera(this);"></button>
<!-- <input id="last_name" name="last_name" type=text placeholder="Select here to scan or enter manually" class="qrcode-text"><label class="qrcode-text-btn"><input type=file accept="image/*" capture=environment onclick="openQRCamera(this);" tabindex=-1>Scan Bottle</label>
<script>function openQRCamera(node) {
var reader = new FileReader();
reader.onload = function() {
node.value = "";
qrcode.callback = function(res) {
if(res instanceof Error) {
alert("No QR code found. Please make sure the QR code is within the camera's frame and try again.");
} else {
node.parentNode.previousElementSibling.value = res;
}
};
qrcode.decode(reader.result);
};
reader.readAsDataURL(node.files[0]);
}</script> -->
<script>
function startBarcodeScanner()
{
window.location.href = 'bwstw://startscanner?field=last_name';
}
</script>
<label for="email">Bottle Location</label>
<select id="email" name="email" class="form_field" value="" placeholder="Bottle Location"/>
<option>ENGINE 1</option>
<option>ENGINE 2</option>
<option>ENGINE 3</option>
<option>SQUAD 4</option>
<option>SQUAD 41</option>
<option>LADDER 1</option>
<option>TRUCK 1</option>
<option>TRUCK 2</option>
<option>TRUCK 3</option>
<option>ENGINE 5</option>
<option>ENGINE 6</option>
<option>ENGINE 7</option>
<option>RESCUE 1</option>
<option>RESCUE 2</option>
<option>RESCUE 3</option>
<option>STATION 1 SPARE</option>
<option>STATION 2 SPARE</option>
<option>STATION 3 SPARE</option>
<option>SPECIAL OPS</option>
<option>BC</option>
<option>COD</option>
<option>DC</option>
<option>EMSC</option>
<option>FINV</option>
<option>COMM</option>
<option>TRAIN</option>
<option>BOAT</option>
<option>SPARE MASK</option>
<option>O/S</option>
<option>OTHER LOCATION</option>
<option>OTHER VEHICLE</option>
</select>
<input id="gs_code" name="gs_code" type="hidden" class="" value="=VLOOKUP(B:B,HydroBottles,4,FALSE)" placeholder=""/>
<div class="clearfix">
<input id="submit" name="submit" type="button" class="form_button" value="Enter Bottle" onClick="submit_form(); document.getElementById('last_name').value = ''; playAudio()"/>
<audio id="beep">
<source src="bleep.mp3" type="audio/mpeg">
</audio>
<div class="form_message" id="message">
<script>
var gs_hydrosearch = 'https://script.google.com/macros/s/AKfycby0VsXuYk-dODBhKpL-zFUeb5xI79Y8jGR0e20I/exec?id=gs_field';
var gs_field = ['last_name'];
function HydroSearch() {
doPost(
</script>
</div>
</div>
</div>
<!-- Place this tag where you want the Awesome Table Widget to render -->
<div data-type="AwesomeTableView" data-viewID="-LfNI2wu42vUdIl5oy9c"></div>
</form>
</body>
</html>
JS file that sends the data from the form to the Google Spreadsheet:
function submit_form() {
// Check Fields
var complete = true;
var error_color = '#FFD9D9';
var fields = ['first_name','last_name','email','gs_code'];
var row = '';
var i;
for(i=0; i < fields.length; ++i) {
var field = fields[i];
$('#'+field).css('backgroundColor', 'inherit');
var value = $('#'+field).val();
// Validate Field
if(!value) {
if(field != 'message') {
$('#'+field).css('backgroundColor', error_color);
var complete = false;
}
} else {
// Sheet Data
row += '"'+value+'",';
}
}
// Submission
if(complete) {
// Clean Row
row = row.slice(0, -1);
// Config
var gs_sid = 'GSID'; // Enter your Google Sheet ID here
var gs_clid = 'Client ID'; // Enter your API Client ID here
var gs_clis = 'API Client Secret'; // Enter your API Client Secret here
var gs_rtok = '0Auth RT'; // Enter your OAuth Refresh Token here
var gs_atok = false;
var gs_url = 'https://sheets.googleapis.com/v4/spreadsheets/'+gs_sid+'/values/Entries!A1:append?includeValuesInResponse=false&insertDataOption=INSERT_ROWS&responseDateTimeRenderOption=SERIAL_NUMBER&responseValueRenderOption=FORMATTED_VALUE&valueInputOption=USER_ENTERED';
var gs_body = '{"majorDimension":"ROWS", "values":[['+row+']]}';
// HTTP Request Token Refresh
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://www.googleapis.com/oauth2/v4/token?client_id='+gs_clid+'&client_secret='+gs_clis+'&refresh_token='+gs_rtok+'&grant_type=refresh_token');
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
var response = JSON.parse(xhr.responseText);
var gs_atok = response.access_token;
// HTTP Request Append Data
if(gs_atok) {
var xxhr = new XMLHttpRequest();
xxhr.open('POST', gs_url);
xxhr.setRequestHeader('Content-length', gs_body.length);
xxhr.setRequestHeader('Content-type', 'application/json');
xxhr.setRequestHeader('Authorization', 'OAuth ' + gs_atok );
xxhr.onload = function() {
if(xxhr.status == 200) {
// Success
$('audio#beep')[0].play();
$('#message').hide().html("Bottle has been Entered! Scan next Bottle.").fadeIn().delay('1000').fadeOut().delay('7000');
}
else {
// Fail
$('#message').html('<p>Row Not Added</p><p>Response:<br/>'+xxhr.responseText+'</p>');
}
};
xxhr.send(gs_body);
}
};
xhr.send();
}
}
The answer to your question is encapsulated in this documentation It's called client to server communication. Presently your question is far to broad you need to do more research and perhaps some of your own debugging. I also recommend that you take this opportunity to take the [tour] and learn how to [ask] and [mcve].
I am working on a project, and cant figure out how to hide my welcome2 and welcome2-0 html code, then once the button is pressed show that information. im new with jquery, and am really confused tried looking this stuff up and still have little idea on how to fix this issue. i appreciate any help or input guys, sorry if anything poorly formatted.
var name ;
var nameFormat=true;
function submission() {
var name = document.getElementById("textbox").value;
if (name.length > 0) {
alert("Welcome "+name);
$("#name").fadeOut(1000);
$("#welcome").fadeOut(1000);
}
else{
nameFormat==false;
alert("Please enter the name again");
}
}
#welcome{
top:30px;
left: 30px;
color: antiquewhite;
border: 2px solid blue;
background: blue;
padding: 25px;
}
#name{
top:30px;
left: 500px;
color: antiquewhite;
background: blue;
border: 25px solid blue;
}
body {
background-color: lightblue;
}
#welcome2{
position: relative;
top:30px;
left: 30px;
color: antiquewhite;
border: 2px solid blue;
background: blue;
padding: 25px;
}
HTML
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Welcome!</title>
<link rel="stylesheet" href="includes/styles1.css" type="text/css" media="screen" />
</head>
<p>
<body>
<div id="welcome"><b>Welcome to the Myanmar Trivia Quiz</b><br> please enter your name and click on "Begin Quiz" to start</div>
<div id ="name"><b>Name:</b>
<input type="text" id="textbox">
<button id=”myButton” type="button" onclick="submission()" >submit</button>
</p>
<div id="welcome2">Myanmar Trivia Quiz </div>
<div id="welcome2-0">Test your Demographic Knowledge<br>--------------------------------------------------------------------------------------</div>
</div>
</body>
<script src="includes/project.js"></script>
</html>
3 things:
Your HTML was malformed
You need to set display: none on the css
for what you want to be hidden at the start
You need to call fadeIn
(or show) on the element AFTER fadeOut (or hide) has finished, you
can do that using promises and the fadeIn callback function
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
http://api.jquery.com/fadein/
var name ;
var nameFormat=true;
function submission() {
var name = document.getElementById("textbox").value;
if (name.length > 0) {
alert("Welcome "+name);
fadeOutWelcome().then(() => fadeInWelcome());
}
else{
nameFormat==false;
alert("Please enter the name again");
}
}
const fadeOutWelcome = () => {
return new Promise((resolve, reject) => {
$("#name").fadeOut(1000, () => resolve());
$("#welcome").fadeOut(1000);
});
}
const fadeInWelcome = () => {
$("#welcome2").fadeIn(1000);
$("#welcome2-0").fadeIn(1000);
}
#welcome{
top:30px;
left: 30px;
color: antiquewhite;
border: 2px solid blue;
background: blue;
padding: 25px;
}
#name{
top:30px;
left: 500px;
color: antiquewhite;
background: blue;
border: 25px solid blue;
}
body {
background-color: lightblue;
}
#welcome2{
display: none;
position: relative;
top:30px;
left: 30px;
color: antiquewhite;
border: 2px solid blue;
background: blue;
padding: 25px;
}
HTML
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Welcome!</title>
<link rel="stylesheet" href="includes/styles1.css" type="text/css" media="screen" />
</head>
<p>
<body>
<div id="welcome"><b>Welcome to the Myanmar Trivia Quiz</b><br> please enter your name and click on "Begin Quiz" to start</div>
<div id ="name"><b>Name:</b>
<input type="text" id="textbox">
<button id=”myButton” type="button" onclick="submission()" >submit</button>
</p>
</div>
<div id="welcome2">Myanmar Trivia Quiz
<div id="welcome2-0">Test your Demographic Knowledge<br>--------------------------------------------------------------------------------------</div>
</div>
</body>
<script src="includes/project.js"></script>
</html>
A few things:
Javascript is case-sensitive, so true is a reserved word, True is not. So instead of var nameFormat=True , you should do: var nameFormat= true .
Then, you're saying you want to hide welcome2 and welcome2-0 divs, but in your javascript code you're not doing this. If you want do this, do the following:
$("#welcome2").hide();
$("#welcome2-0").hide();
// or
$("#welcome2").fadeOut(100);
$("#welcome2-0").fadeOut(100);
There is another issue in your else block: you're doing nameFormat==false , which is just comparing if nameFormat is false. If you want to assign false to nameFormat variable, do this:
nameFormat = false;
Include the .hide() at the beginning of your javascript code (so that it executes at the very beginning) which would hide those 2 divs.
Then when the button is pressed, use .show() to show those 2 divs again.
Also, where you had nameFormat == false;, you need to change that to nameFormat = false;. == is the comparison operator, so it would look at that and say "Oh nameFormat is not false", and move on. If you wanted to make nameFormat be false (which I assume you did), you must use the assignment operator (which is =)
var name;
var nameFormat = true;
$("#welcome2").hide();
$("#welcome2-0").hide();
function submission() {
var name = document.getElementById("textbox").value;
if (name.length > 0) {
alert("Welcome " + name);
$("#name").fadeOut(1000);
$("#welcome").fadeOut(1000);
$("#welcome2").show();
$("#welcome2-0").show();
} else {
nameFormat == false;
alert("Please enter the name again");
}
}
#welcome {
top: 30px;
left: 30px;
color: antiquewhite;
border: 2px solid blue;
background: blue;
padding: 25px;
}
#name {
top: 30px;
left: 500px;
color: antiquewhite;
background: blue;
border: 25px solid blue;
}
body {
background-color: lightblue;
}
#welcome2 {
position: relative;
top: 30px;
left: 30px;
color: antiquewhite;
border: 2px solid blue;
background: blue;
padding: 25px;
}
HTML
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Welcome!</title>
<link rel="stylesheet" href="includes/styles1.css" type="text/css" media="screen" />
</head>
<p>
<body>
<div id="welcome"><b>Welcome to the Myanmar Trivia Quiz</b><br> please enter your name and click on "Begin Quiz" to start</div>
<div id="name"><b>Name:</b>
<input type="text" id="textbox">
<button id=”myButton” type="button" onclick="submission()">submit</button>
</div>
<div id="welcome2">Myanmar Trivia Quiz </div>
<div id="welcome2-0">Test your Demographic Knowledge<br>--------------------------------------------------------------------------------------</div>
</div>
</body>
<script src="includes/project.js"></script>
</html>
To achieve what you are trying to do, it's simply as:
var name;
var nameFormat=true;
function submission() {
name = document.getElementById("textbox").value;
if (name.length > 0) {
alert("Welcome "+name);
$("#name").fadeOut(1000);
$("#welcome").fadeOut(1000);
$("#welcome2").fadeIn(1000);
$("#welcome2-0").fadeIn(1000);
}
else{
nameFormat=false;
alert("Please enter the name again");
}
}
Since you showed up in your code fadeOut, I made my answer with that. Otherwise you can replace fadeIn with show.
About your CSS code, try to set display: none; for those elements that should be hidden when the page loads.
For more info look at:
http://api.jquery.com/show/
My website has a simple messaging system where users write messages and the recipients answer back, which is defined as chatting.
I'm using an HTML to keep the page refreshing until the person receives a new message.
<meta http-equiv="refresh" content="15;URL=chat_5999468.php"/>
It keeps refreshing the page in every 15 seconds, so if a new message intrudes, it pops up. BUT it reloads the page even whilst the recipient is typing.
How do I prevent this reload when a user is typing his message in jQuery?
Edit: Page HTML (Similar to this):
<!DOCTYPE html> <head> <title>Untitled</title> <meta charset="UTF-8"/> <meta http-equiv="refresh" content="15;URL=chat_5999468.php"/> <style> #b { color: #000; } .chat-input input[type="text"] { width: 65%; height: 30px; border: 1px solid #999999; border-top-right-radius: 10px; border-bottom-left-radius: 15px; padding: 10px; color: #0084ff; margin-left: 5px; margin-top: 10px; margin-bottom: 10px; } input:focus,button:focus,input,button { outline: none!important; } .chat-input input[type="submit"] { color: #000; background: url(https://i.stack.imgur.com/NAjD2.jpg) no-repeat; height: 47px; width: 47px; border: none; } .chat77 ul{ list-style: none; margin: 0; padding: 0; } .chat77 ul li{ display:inline-block; clear: both; padding: 8px; border-radius: 30px; margin-bottom: 2px; font-family: Helvetica, Arial, sans-serif; } .message-2 { background: #eee; float: left; } .message-me { float: right; background: #0084ff; color: #fff; } .message-2 + .message-me{ border-bottom-right-radius: 5px; } .message-2 + .message-me{ border-top-right-radius: 5px; border-bottom-right-radius: 5px; } .message-me:last-of-type { border-bottom-right-radius: 30px; } </style> </head> <body> <div class="chat-input"><label><form method="post" action="chat_5999468.php" ><input type="text" name="txt" placeholder="Write here..." /><input type="submit" name="submit_msg" value="" /></form></label></div><center><div id="chat-status">Online Mark Zuckerberg | Refresh</div></center><br /><div class="chat77"><ul><script>var book="Me: 3";if(book=="Me: 3" ){document.write("<li class='message-me'>3</li>");}else{document.write("<li class='message-2'><a href='/profile_12.php?u=Mark+Zuckerberg' id='b' target='_top'>3</a></li>");}</script><script>var book="Mark Zuckerberg: 2";if(book=="Me: 2" ){document.write("<li class='message-me'>2</li>");}else{document.write("<li class='message-2'><a href='/profile_12.php?u=Mark+Zuckerberg' id='b' target='_top'>2</a></li>");}</script><script>var book="Me: Message1";if(book=="Me: Message1" ){document.write("<li class='message-me'>Message1</li>");}else{document.write("<li class='message-2'><a href='/profile_12.php?u=Mark+Zuckerberg' id='b' target='_top'>Message1</a></li>");}</script></ul></div><br /> </body> </html>
All I can think is jQuery.ajax(). See here for the jQuery API Documentation
This answer is for you if you want a alternative for your meta tag.
You could get the content of the updated site, search for a specific div or something like that and check if there's a new entry.
This is just an example how you could do it!
First of all, create a loop function:
setInterval(function(){
}, 15000); // The loop function will check every 15 seconds
After that, create the ajax() call.
$.ajax({
url: 'YOUR URL HERE',
type: 'GET',
success: function(data) {
var check = $(data).find('#chat');
// Here you get the `div` -> `#chat`
// Now you could check if there is something new
}
});
I dont know how your chat is coded, but I think there's something with timestamps. Just check if there's a div(?) with a newer timestamp than your opened site:
var compareMe = $('#chat').find('.entry span').last().attr('class');
var compareOther = $(data).find('.entry span').last().attr('class');
In my case there's a div with id="chat" and this have div's which have a class="entry which got a span with a class="1504155239" (thats the timestamp for the message).
Here's an example:
var compareMe = $('#chat').find('.entry span').last().attr('class');
console.log(compareMe);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="chat">
<div class="entry">
<span class="1504155239">1504155239: </span>
Hello There! First!
</div>
<div class="entry">
<span class="1504155254">1504155254: </span>
Hey! Ah, I'm second?
</div>
</div>
So the only thing that you have to do now is to check if compareMe and compareOther is the same or newer.
// Lets cast them first to int because of reasons.
// Just kidding, it's safer to cast them and then check if they are newer
compareMe = parseInt(compareMe);
compareOther = parseInt(compareOther);
if (compareMe != compareOther && compareMe > compareOther) {
// Now you can reload.
}
At the end it would look like this:
THIS SNIPPET DON'T WORK! It's just here to visualize how it can be done!
setInterval(function(){ // This is the loop function
$.ajax({
url: '<YOUR URL HERE>',
type: 'GET',
success: function(data) {
var check = $(data).find('#chat');
// Here you get the `div` -> `#chat`
var compareMe = $('#chat').find('.entry span').last().attr('class');
var compareOther = $(check).find('.entry span').last().attr('class');
// Now you could check if there is something new
// Lets cast them first to int because of reasons.
// Just kidding, it's safer to cast them and then check if they are newer
compareMe = parseInt(compareMe);
compareOther = parseInt(compareOther);
if (compareMe != compareOther && compareMe > compareOther) {
// Now you can reload.
}
}
});
}, 15000); // The loop function will check every 15 seconds
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="chat">
<div class="entry">
<span class="1504155239">1504155239: </span>
Hello There! First!
</div>
<div class="entry">
<span class="1504155254">1504155254: </span>
Hey! Ah, I'm second?
</div>
</div>
EDIT
Since you've copied your HTML in here, I can help you more specifically.
This is an example for your code.
setInterval(function() {
$.ajax({
url: '/',
type: 'GET',
success: function(data) {
var check = $(data).find('.chat77');
var compareMe = $('.chat77').find('li').last().text();
var compareOther = $(check).find('li').last().text();
if (compareMe != compareOther && $('.chat-input').find('input').first().val() == "") {
location.reload();
}
}
});
}, 3000);
I would prefer that you add a timestamp to the messages and check this instead of strings.
I'm making a site where the user will be able to search for a country and the city or cities in that country will show on the page. I'm able to show one city now for each country but if the country have two or more cities only one of the cities shows. I tried the "+=" to create several cards that will show on the page. That created some issues for me. I'm thinking that I have to use the "appendChild()" function to append each city card to a new div in the DOM. But i'm not 100% sure how to do that, with this code.
If I type in "USA" in the searchfield and USA both have LA and NY as cities. The first one shows now, but I want both to show. I've tried using document.createElement('cityCard') and append cityCard to the container where the cards show. But I did not get it to work as I wanted, I might have done some syntax mistake.
Is this the rigth mindset for this task? Or is it a better way?
Don't mind the CSS, its not done.
Link to a fiddle where all the code is.
https://jsfiddle.net/uzfb852g/12/
added the code under aswell(its the same as in the fiddle)
HTML CODE:
<!DOCTYPE html>
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Martel:400,700,900"
rel="stylesheet">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>FINN DITT FERIESTED!</h1>
<form id="inputForm">
<input type="text" id="sokFelt">
<button id="btn">Search</button>
<button id="allBtn">Alle steder</button>
</form>
<div id="break"></div>
<div id="searchWord"></div>
<div id="cardContainer">
<div id="cityCards">
<h2 id="country"></h2>
<h4 id="city"></h4>
<img id="cityImg">
</div>
</div>
<button id="btnTwo"></button>
<script src="content.js"></script>
</body>
</html>
CSS CODE:
body{
margin: auto;
width: 100%;
height: 100%;
}
h1{
text-align: center;
margin: 25px;
color: tomato;
font-family: 'Martel', serif;
text-shadow: 1px 2px #333;
font-weight: 900;
}
#inputForm{
text-align: center;
margin: 25px;
}
#break{
width: 80%;
margin: auto;
height: 1px;
text-align: center;
background-color: #333;
}
#btn{
padding: 5px 15px;
}
#sokFelt{
padding: 5px 15px;
}
#searchWord{
font-size: 24px;
margin: 40px;
color: #333;
font-weight: bold;
}
#cardContainer{
width: 100%;
margin: auto;
display: flex;
flex-direction: column;
flex-wrap: wrap;
}
#cityCards{
padding: 12px 22px;
background-color: aqua;
border-radius: 5px;
width: 20%;
height: 250px;
}
#cityImg{
width: 100%;
height: 200px;
}
#allBtn{
padding: 5px 15px;
}
JS CODE:
var form = document.getElementById('inputForm');
var input = form.querySelector('input');
var country = document.getElementById("country");
var city = document.getElementById("city");
var cityImg = document.getElementById("cityImg");
var searchWord = document.getElementById("searchWord");
/*IMAGES*/
var place = [
{land: 'Norge', by: 'Oslo', img: 'img/Oslo.jpg'},
{land: 'USA', by: 'Los Angeles', img: "img/LA.jpg"},
{land: 'USA', by: 'New York', img: "img/NewYork.jpg"},
{land: 'Tyskland', by: 'Berlin', img: 'img/berlin.jpg'},
{land: 'Frankrike', by: 'Paris', img:'img/berlin.jpg'}
];
form.addEventListener('submit', (e) => {
e.preventDefault();
for(var i = 0; i < place.length; i += 1){
if(input.value === place[i].land) {
searchWord.innerHTML = input.value;
document.createElement('cityCards');
country.innerHTML = place[i].land;
city.innerHTML = place[i].by;
cityImg.src = place[i].img;
}
}
});
document.getElementById("btnTwo").addEventListener("click", function(){
document.createElement("")
});
Try this to see the problem:
country.innerHTML += place[i].land;
city.innerHTML += place[i].by;
citycards is not an HTML element
You must use an array with div´s (array[i]=document.createElement('div'))
Then create images with img[i] = document.createElement('img')
Set the img.src, and append this with appendChild to cardcontainer.
Using createElement and appendChild would be the right way to go, but you could also use a template tag instead.
Then you could just fill the template with the filtered information and import the template to the DOM.
Here is an example on how this could look like. You may want to take a look at the array function filter, map and forEach.
var form = document.getElementById('inputForm');
var input = form.querySelector('input');
var searchWord = document.getElementById("searchWord");
var template = document.querySelector('#cardContainer');
var getAllBtn = document.getElementById('allBtn');
var place=[{land:"Norge",by:"Oslo",img:"http://www.telegraph.co.uk/travel/destination/article137625.ece/ALTERNATES/w460/oslocityhall.jpg"},{land:"USA",by:"Los Angeles",img:"http://www.zocalopublicsquare.org/wp-content/uploads/2015/10/DistantLASkylineBIG-levinson.jpg"},{land:"USA",by:"New York",img:"https://www.city-journal.org/sites/cj/files/New-York.jpg"},{land:"Tyskland",by:"Berlin",img:"http://www.telegraph.co.uk/content/dam/Travel/Destinations/Europe/Germany/Berlin/Berlin%20cathedral-xlarge.jpg"}];
form.addEventListener('submit', (e) => {
e.preventDefault();
});
getAllBtn.addEventListener("click", function() {
// clear your container div to empty all previous added elements.
searchWord.innerHTML = "";
// filter your place data on the land property of each item.
place.filter( item => item.land === input.value )
// set the img src attr and text content for the elements in the template.
.map( item => {
template.content.getElementById("country").textContent = item.land;
template.content.getElementById("city").textContent = item.by;
template.content.getElementById("cityImg").src = item.img;
return document.importNode(template.content, true);
})
// append them to your container element.
.forEach( item => {
searchWord.appendChild(item)
})
});
body{margin:auto;width:100%;height:100%}h1{text-align:center;margin:25px;color:tomato;font-family:'Martel',serif;text-shadow:1px 2px #333;font-weight:900}#inputForm{text-align:center;margin:25px}#break{width:80%;margin:auto;height:1px;text-align:center;background-color:#333}#btn{padding:5px 15px}#sokFelt{padding:5px 15px}#searchWord{font-size:24px;margin:40px;color:#333;font-weight:700}#cardContainer{width:100%;margin:auto;display:flex;flex-direction:column;flex-wrap:wrap}#cityCards{padding:12px 22px;background-color:aqua;border-radius:5px;width:20%;height:250px}#cityImg{width:100%;height:200px}#allBtn{padding:5px 15px}
<h1>VACATION</h1>
<form id="inputForm">
<input type="text" id="sokFelt">
<button id="btn">Search</button>
<button id="allBtn">All places</button>
</form>
<div id="break"></div>
<div id="searchWord"></div>
<template id="cardContainer">
<div id="cityCards">
<h2 id="country"></h2>
<h4 id="city"></h4>
<img id="cityImg">
</div>
</template>
i want to transfer the selected value from listbox 1 to listbox 2 viceversa using jquery
I have sample code below but it is not working.
Hi guys please, i want to transfer the selected value from listbox 1 to listbox 2 viceversa using jquery
I have sample code below but it is not working.
Hi guys please, i want to transfer the selected value from listbox 1 to listbox 2 viceversa using jquery
I have sample code below but it is not working.
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Listbox.js Demo</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"> </script>
<script>
$(function () {
$('select#planets').listbox();
$('select#country').listbox({'searchbar': true});
});
</script>
<script language="javascript" type="text/javascript">
//this will move selected items from source list to destination list
function move_list_items(sourceid, destinationid)
{
$("#"+sourceid+" option:selected").appendTo("#"+destinationid);
}
</script>
<!-- include listbox.js -->
<link href="../src/listbox.css" rel="stylesheet">
<script src="../src/listbox.js"></script>
<style>
* {
margin: 0px;
padding: 0px;
}
html, body {
font-size: 12px;
font-family: sans-serif;
background: #f5f5f5;
}
.cover {
padding: 20px 30px;
border: 1px solid #dedede;
border-radius:4px;
background: #f9f9f9;
box-shadow: 0px 0px 10px #a8a8a8;
/* centering */
position: absolute;
top: 50%;
left: 50%;
margin-top: -180px;
margin-left: -222px;
}
.lbjs { float: left; }
.lbjs:last-of-type { margin-left: 20px; }
</style>
<body>
<div class="cover">
<select id="country" name="country" >
<option>Afghanistan</option>
<option>Albania</option>
<option>Algeria</option>
<option>Andorra</option>
</select>
<input id="moveright" type="button" value=" > " onclick="move_list_items('country','planets');" />
<select id="planets" multiple="multiple" name="planets">
<option>Alderaan</option>
<option>Corellia</option>
<option>Endor</option>
<option>Kashyyyk</option>
</select>
</div><!-- .cover -->
</body>
</html>
$(document).ready(function () {
$("#moveright").click(function(){
$("#country > option:selected").each(function(){
$(this).remove().appendTo("#planets");
});
});
});
Demo:
http://jsfiddle.net/Rc7qP/
Update:
http://jsfiddle.net/fLAy6/1/
Please have a look into the following link it seems working
$("#moveright").on('click' , function(){
alert("test");
var obj = ($("#country option:selected"));
$.each(obj, function(index , item){
$("#planets").append($(this));
});
});
$("#moveleft").on('click' , function(){
alert("test");
var obj = ($("#planets option:selected"));
$.each(obj, function(index , item){
$("#country").append($(this));
});
});