Issue with Ajax is not being called - javascript

I am a beginner learning Ajax and javascript. After hours trying to find out whats was the problem, I gave up and brought the issue here. In tutorials from W3 schools, ajax works fine. My code has a form with a list and an input box. I want to collect the item selected in the list and the text entered in the input box. Then when a button is clicked, a function with ajax is called. It seems that my function is not being recognized or the function does nothing. The code is bellow. I wll be grateful on any light on this. Thank you.
function showCustomer() {
const xhttp = new XMLHttpRequest();
var selcriteria = document.getElementById('tcriteria');
var selcriteriavalue = selcriteria.options[selcriteria.selectedIndex].value;
var criteriavalue = document.getElementById('bananas').value;
alert(selcriteriavalue + ' ' + criteriavalue);
xhttp.onload = function() {
document.getElementById("txtHint").innerHTML = this.responseText;
}
xhttp.open("GET", "action_page.py?tycriteria=" + tcriteria + "&vacriteria=" + vcriteria);
xhttp.send();
}
<h2>Get Contact using Ajax </h2>
<form action="">
<select name="tcriteria">
<option value="">Select a criteria:</option>
<option value="Name">Name</option>
<option value="Phone 1 - Value">Telephone</option>
<option value="Notes">Notes</option>
</select>
<input type='text' id='apples' value=''>
<button type="button" id="bananas" onclick="showCustomer()">Get info</button>
</form>
<br>
<div id="txtHint">Contact data will be shown here...</div>

On your line 3 you are trying to get element with id tcriteria:
var selcriteria = document.getElementById('tcriteria');
But there isnt any element with that id so you need to replace it with this:
var selcriteria = document.querySelector('[name="tcriteria"]');
Note: If you don't need support for very old browsers you can use fetch instead of XMLHttpRequest, use ${var} text ${var2} (only in backticks) instead of tens of +-s and let-s and const-s instead of var-s. You can also use arrow functions.

Related

Simple share text between two different browsers running the same website

I'm making a website that needs to have an interface where I can select an option and push that option, which updates text on that same website running in a different browser. So far I have the code that allows me to update the text on the first browser, but not the other one.
HTML
<select id="currentEvent">
<option value="" disabled selected>Current Event</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
<button type="button" onclick="GetSelectedText()">Push Changes</button>
JS
function GetSelectedText() {
var e = document.getElementById("currentEvent");
var result = e.options[e.selectedIndex].text;
document.getElementById("selectedEvent").innerHTML = result;
}
I only need to update one line of text on each browser, so please keep this as simple as possible as I'm still learning HTML and am new to web development.
Thanks in advance :)
took me a bit.. made an example with repl.it.. don't mind the C file, I just like the C for the free environment.. focus on the backend.js and frontend.html
The concept is that each tab/client gets a new key, the client sends its key, looking for data in return in a loop, when there is data, it puts the element document.getElementById("selectedEvent") .innerHTML with the response text. In the button however, it sends a post that will put text into server object's key of the tab that shares the inputted key. That combination of scouting data and placing data makes it work like a charm
backend.js
var http=require('http')
var fs=require('fs')
function randomChar(){
var m=Math.random; var f=Math.floor
var arr=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
0,1,2,3,4,5,6,7,8,9,"!","#","$","&","*","(","-","_","=","+","[","]","'","~"]
var newChar=""
for(var i=0; i<f(m()*100+20); i++){newChar+=arr[f(m()*arr.length)]}
return newChar
}
var obj={}
function frontEnd(){
var specialChar=randomChar(); obj[specialChar]=""
return `<script>window.key="${specialChar}"</script>`+
fs.readFileSync(__dirname + '/frontend.html')
.toString().split('')
.map(a=>{if(a=="\\"){return(specialChar)}return(a)})
.join('')
}
//server stuff below
var server=http.createServer((req,res)=>{
if(req.method=="GET"){res.write(frontEnd())}
else if(req.method=="POST"){
if(req.headers.pw&&req.headers.inp){
if(obj[req.headers.pw]!=undefined){obj[req.headers.pw]=req.headers.inp}
}
else if(req.headers.receive&&req.headers.key){
res.write(obj[req.headers.key]||"")
}
else if(req.headers.end=="yes"&&req.headers.key){
delete(obj[req.headers.key])
console.log(`a key ${req.headers.key} was deleted`)
}
}
res.end()
})
server.listen(8080)
frontend.html
<html>
<h3>for this tab manipulation, so that you cannot edit all tabs connected to this site, you need to know the <bold>KEY</bold> of someone else's tab</h3>
<p>your key is <bold>\</bold></p>
<input placeholder="enter other tab's key here" id="inp" />
<select id="currentEvent">
<option value="" disabled selected>Current Event</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
<button type="button" onclick="GetSelectedText()">Push Changes</button>
<h4 id="selectedEvent"></h4>
<script>
//loop checking for incoming changes (empty input("") means it would me treated as no input)
var select=document.getElementById("selectedEvent");
(async()=>{
var options={
method:'POST',
headers:{'receive':'true','key':key}
}
while(true){
let x=await fetch(location.href,options)
let text=await x.text()
if(text){select.innerHTML=text}
}
})()
//now for the button
function GetSelectedText() {
var e = document.getElementById("currentEvent");
var result = e.options[e.selectedIndex].text;
select.innerHTML = result;
//sends an outgoing request that will edit the other tab
var xhr=new XMLHttpRequest()
xhr.open('POST',location.href,true)
var inp=document.getElementById('inp')
xhr.setRequestHeader('pw',inp.value)
xhr.setRequestHeader('inp',result)
xhr.send()
}
//now for a listener that will attempt to delete the key from the server as it closes
window.onbeforeunload = async function(){
await fetch(location.href,{method:'POST',headers:{'end':'yes'}})
//put return in front of the 'await' word in line above
//and a confirm would appear when you try to close
}
</script>
</html>

Retrieve select value from form without an ID

I'm trying to create a cookie to store a value from a select form field - I'v been trying different options but unsuccessful everytime 😥 - can someone please help me?
The site is currently on Drupal but I'm wanting to add via Tag Manager, so any help with vanilla JS would be amazing
The Hubspot form in question can be located: https://www.huddle.com/get-started
The select field is : Comapany Size
The value I'm trying to target is the first option: 1-10
This is my code:
<script>
var formField = document.querySelector('form["name="size_of_organisation__c"]').value;
var formValue = "1-10";
var cookieName = sizeOfOrg;
var cookieValue = smb;
if (formField == formValue) {
 document.cookie = "cookieName=cookieValue";
}
</script>
Any help would be much appreciated
Humm,
it seems you are using react, so it will be definitely nice to create this process in a react fonction inside your form component, etc.
I'm not really sure of your needs, but this code retrieve the value of the dropdown on change and add it in a cookie :
<html>
<body>
<form>
<select name="size_of_organisation__c">
<option value="" disabled="" selected="">Please Select</option>
<option value="1-10">1-10</option>
<option value="11-50">11-50</option>
<option value="51-200">51-200</option>
<option value="201-500">201-500</option>
<option value="501-1000">501-1000</option>
<option value="1001-5000">1001-5000</option>
<option value="5001-10000">5001-10000</option>
<option value="10001+">10001+</option>
</select>
</form>
</body>
<script src="./temp.js"></script>
</html>
//selector to select dropdown. return an array so take the first one
var select = document.getElementsByName("size_of_organisation__c")[0];
console.log(select);
// add event handler to update the cookie each time you change the select
select.addEventListener("change", function() {
document.cookie = "sizeOfOrg=" + select.value;
console.log(document.cookie);
});
edit: add the html and the console.log() to debug

php Dropdown Realtime Update

My apologies if this has been answered before but I did do a search and haven't seen any answers for the questions asked in other posts. The answers I did see didn't relate to my question (mostly to do with dropdowns getting results from mysql).
I have a php dropdown list where you need to select a value (1, 2 or 3). Based on what you select, the list should update a variable and show a hidden div tag. Now from the information I gathered it seems like this cannot be done with php alone but requires a javscript or ajax script.
php:
<form>
<select name="options" onchange="{dosomething}">
<option value="0">[Select value]</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select><br>
</form>
This should then update this variable and div in REALTIME:
<div id="test" style="display:none">
$answer= 1 + $value
<?php
echo "1 + $value = $answer";
</div>
javascript/ajax:
<script>
function dosomething {
#update $value based on dropdown and do calculation
#unhide div with id "test"
}
</script>
I need to mention that I have no knowledge of javascript or ajax.
If you only need to view the new result in the same page without requesting something to the server add this script below your last div:
<script>
var element = document.getElementsByName('options');
if( element.length > 0 ){
element[0].addEventListener('change',update_text,false);
//element[0].addEventListener('change',function(){update_text(param)},false);
}
function update_text(evt){
console.log(evt);
var first_element = evt.target;
var selection = first_element.options[first_element.selectedIndex].value;
//do math:
selection = +selection + 1; //this cast selection as number and not as String
console.log(selection);
var test = document.getElementById('test');
test.style.display = 'block';
test.innerHTML = `<p>${selection}</p>`;
};
</script>

AJAX POST Won't Work With document.getElementById Variables

I have an html form and ajax call that store data in MySQL via a PHP page.
The code for all three is copied below. (Please note the //)
All three work fine as long as I have the variables hard coded in the function where the ajax call stores them. However, when I comment out the hard coded variables and run it with the regular variables, it does not work.
JavaScript AJAX Call
$("#buttonSubmit").click(function() {
//var questionID = obj.Questions[i].questionID;
//var shortAnswerValue = document.getElementById('txtShortAnswerValue').value;
//var longAnswerText = document.getElementById('txtLongAnswerText').value;
var questionID = "SampleQID";
var shortAnswerValue = "Sample Short";
var longAnswerText = "Sample Long";
$.ajax({
type: "POST",
url: "SaveUpdatesTemplate.php",
data: "questionID=" + questionID + "&shortAnswerValue=" + shortAnswerValue + "&longAnswerText=" + longAnswerText,
}); // end ajax function
document.getElementById("txtLongAnswerText").reset();
}); // end button submit function
Associated HTML
Select Inspection or Project Phase
Select Inspection or Project Phase
<label for="selectSection">Select Inspection or Project Phase</label>
<select class="form-control" id="selectSection" name="selectSection">
<option> Select Inspection or Project Phase</option>
</select>
<button type="button" class="form-control" id="buttonStart" name="buttonStart" value="List Questions">Start - Click to Populate Question List</button>
<label for="selectQuestion">Select Task or Question to Update</label>
<select class="form-control" id="selectQuestion" name="selectQuestion" >
<option> Select Task or Question to Update </option>
</select>
<!-- short answer below -->
<label for="txtShortAnswerValue">Short Answer</label>
<select class="form-control" id="txtShortAnswerValue" name="txtShortAnswerValue">
<option value="1" selected>worst</option>
<option value="3">middle</option>
<option value="5">best</option>
</select>
<!-- long answer below -->
<label for="txtLongAnswerText">Long Answer / Notes</label>
<textarea class="form-control" name="txtLongAnswerText" id="txtLongAnswerText" rows=3>
</textarea>
Associated PHP Code
// Assign PHP variables to POST results from client
$questionID = htmlspecialchars(trim($_POST['questionID']));
$shortAnswerValue = htmlspecialchars(trim($_POST['shortAnswerValue']));
$longAnswerText = htmlspecialchars(trim($_POST['longAnswerText']));
//SQL STATEMENT
$sql="INSERT INTO Updates (questionID, shortAnswerValue, longAnswerText)
VALUES
('$questionID', '$shortAnswerValue', '$longAnswerText')";
You could do this:
data: encodeURI("questionID=" + questionID + "&shortAnswerValue=" + shortAnswerValue + "&longAnswerText=" + longAnswerText);
The problem is the spaces in var questionID, and so on. Also you have an unnecessary comma before the end of the Object you passed to $.ajax(), right after your data property value.

Form action incorrect when set with Javascript

I have a form on a page with two inputs. On submission, I would like the page redirected to a link that contains the values of the two inputs, plus a preceding string. The html is the following:
<form name="searchForm">
<label for="property_type">Property Type</label>
<select name="property_type" id="property_type_number">
<option value>- All Property Types -</option>
<option value="1432">Commercial</option>
<option value="1433">Land</option>
<option value="1434">MultiFamily</option>
<option value="1435">Rental</option>
<option value="1436">Residential</option>
<option value="1988">Residential / Condo</option>
<option value="1987">Residential / Single Family</option>
</select>
<label for="city">City</label>
<select name="city" id="city_number">
<option value>- All Property Types -</option>
<option value>--</option>
<option value="cambridge">Cambridge</option>
<option value="zanesville">Zanesville</option>
</select>
<input type="submit" value="Search for Properties" onclick="searchform()">
</form>
And the Javascript is the following:
function searchform()
{
var propertyType = document.getElementById("property_type_number").value;
var city = document.getElementById("city_number").value;
target = "/idx/?" + city + propertyType + "hi";
document.searchForm.action = target;
}
When I submit the form, it seems to only use the first string of the target variable ("/idx/?") but ignore the rest. It then inserts the values from the form automatically. I would like it to go to a custom target such as the one above.
If you want to see it on the web, the address is: http://lainegabriel.net/ (it is the last widget on the left).
Well, I can't explain why the form behaves as such, or why it doesn't work, since it would appear that every bit of information online says to do exactly what you're doing.. I can however, provide a work-around:
Firstly, change your html to this, deleting the 'onclick' from the submit button, and replacing the form tag:
<form name="searchForm" onsubmit="return searchform();">
Secondly, in your searchform() function:
function searchform() {
var propertyType = document.getElementById("property_type_number").value;
var city = document.getElementById("city_number").value;
target = "/idx/?" + city + propertyType + "hi";
document.searchForm.action = target; // I just left this in here just in case you wanted it.
window.location.href = target; // redirect the window to the new url/action
return false; // prevent the default submit action from occurring
}
Demo
change this:
var propertyType = document.getElementById("property_type_number").value;
var city = document.getElementById("city_number").value;
with this:
var select = document.getElementById("property_type_number");
var propertyType = select.options[ select.selectedIndex ].value;
select = document.getElementById("city_number");
var city= select.options[ select.selectedIndex ].value;
Any difference?
i know its bigger in code but i never had problems with that (before i switched to jquery and forget all these kind of problems..)

Categories

Resources