Sending parameters with ajax not working - javascript

I'm trying to send some variables using ajax to a php page and then displaying them in a div but it isn't working.
Html code :
<div id="center">
<form>
<input type="text" id="toSearch" class="inputText" title="Search for ...">
<select name="thelist1" id="ecoElem" class="comboBox">
<option>-- Ecosystem Element --</option>
</select>
<select name="thelist2" id="ecoActor" class="comboBox">
<option>-- Ecosystem Actor --</option>
</select>
<input type="button" value="Search" id="searchButton" onclick="loadData();">
</form>
</div>
<div id="resBox">
</div>
The loadData function :
function loadData(){
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
searchT = document.getElementById('toSearch').value;
ecoElem = document.getElementById('ecoElem').value;
ecoActor = document.getElementById('ecoActor').value;
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById('resBox').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST","databaseRead.php",true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send("text=" + searchT + "&elem=" + ecoElem + "&actor=" + ecoActor);}
and finally the php page :
<?php
$searchT = $_POST['text'];
$ecoElem = $_POST['elem'];
$ecoActor = $_POST['actor'];
echo $searchT;
?>
That's it , I've been working on this for a few hours but still can't figure it out.

Try changing the button so that the onclick return false (in case that is submitting the form)...
<input type="button" value="Search" id="searchButton" onclick="loadData();return false;">
Also, you might want to URL encode the values from the textbox, otherwise somebody entering a = or a & will mess it all up...
xmlhttp.send("text=" + encodeURIComponent(searchT) + "&elem=" + + encodeURIComponent(ecoElem) + "&actor=" + + encodeURIComponent(ecoActor));}

You could also use JQuery.
function loadData(){
var searchT = $('#toSearch').val();
var toSearch = $('#ecoActor ').val();
var ecoActor = $('#ecoActor').val();
$.post("databaseRead.php"),{ text:searchT, elem:toSearch, actor:ecoActor },
function(data){
$('#resBox').html(data);
});
}

Related

javascript function with variable needed to trigger a url with value from within script

i have an html page with some inputs, i need to trigger a js function that will ultimately lead to triggering a url GET or POST (with out credentials) the problem is i need to see this in my url
http://restaubid.com/cgi-bin/mmcal.cgi?restaubid/keyword/oven
instead I see this
http://localhost:8080/?keyword=oven&email=
Don't worry about the email; I am using a thymleaf for front end and java for back end database to save email.
For now i really need to trigger the url with the right url which is this
http://restaubid.com/cgi-bin/mmcal.cgi?restaubid/keyword/oven
my code is as follows (index.html)
<div class="col span-2-of-2">
<form action="">
<input type="text" name="keyword" id="keyword" placeholder="Search">
<input type="text" name="email" id="email" placeholder="Email (Optional)">
<button type="submit" onclick="equipmentSearchFn()">Search</button>
</form>
</div>
for script i have within my html file (index.html)
<script>
function equipmentSearchFn() {
let keyword;
let email;
let url;
keyword = document.getElementById("keyword").value;
email = document.getElementById("email").value
document.getElementById("keyword").innerHtml = keyword;
document.getElementById("email").innerHtml = email;
let xmlHttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xmlHttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
}
}
url = "http://restaubid.com/cgi-bin/mmcal.cgi?restaubid/keyword/" + keyword;
//window.location = url + keyword;
xmlHttp.open('GET', url, true);
xmlHttp.send();
}
</script>
i am much obliged...
You have two problems here. The first it the "submit" button. Unless you stop the click event with javascript, the button will POST the values to your Form.
The second problem is the AJAX request, which I think you don't need at all.
function equipmentSearchFn() {
let keyword;
let email;
let url;
keyword = document.getElementById("keyword").value;
email = document.getElementById("email").value
url = "http://restaubid.com/cgi-bin/mmcal.cgi?restaubid/keyword/" + keyword;
window.location = url + keyword;
}
<div class="col span-2-of-2">
<form action="">
<input type="text" name="keyword" id="keyword" placeholder="Search">
<input type="text" name="email" id="email" placeholder="Email (Optional)">
<button type="button" onclick="equipmentSearchFn()">Search</button>
</form>
</div>

Second AJAX function fails when other AJAX function has already been executed

I have a file that shows a bunch of orders, each of which has a button with an ajax function that sends an email. Aside from that, every 30 seconds another ajax function runs and searches for new orders and loads them on top. When I first load the page, the send mail function works just fine. But once the function that searches for new orders has been executed for the first time, when I click the button that fires the mail ajax function, it doesn't send it and reloads the page
I have checked for repeated variable and function names that might conflict but there's none. The functions work just fine on their own, only when the order-searching one has been executed the other one starts to fail
this is the simplified html code for each form (there are many orders on the page with different ids)
<form role="form" id="contactForm4081">
<div class="form-group fg4081">
<label for="message" class="h4 ">Tiempo de entrega</label>
<!-- <textarea id="message" class="form-control" rows="5" placeholder="Enter your message" required></textarea> -->
<input type="hidden" value="Santiago" name="name4081" id="name4081" />
<input type="hidden" value="contacto#nodorojo.com" name="email4081" id="email4081" />
<select name="message4081" id="message4081" required>
<option value="15">15 min</option>
<option value="30">30 min</option>
<option value="45">45 min</option>
<option value="60">60 min</option>
</select>
<button type="submit" id="form-submit" class="btn btn-default btn-md pull-right ">Enviar mail</button>
</div>
<div id="msgSubmit4081" class="h4 text-center hidden">Tiempo de entrega enviado.</div>
</form>
this is the mail function
$("#contactForm4081").submit(function(event){
// cancels the form submission
event.preventDefault();
submitForm4081();
});
function submitForm4081(){
// Initiate Variables With Form Content
var name4081 = $("#name4081").val();
var email4081 = $("#email4081").val();
var message4081 = $("#message4081").val();
$.ajax({
type: "POST",
url: "php/process.php",
data: "name=" + name4081 + "&email=" + email4081 + "&message=" + message4081,
success : function(text){
if (text == "success"){
formSuccess4081();
}
}
});
}
function formSuccess4081(){
$( "#msgSubmit4081" ).removeClass( "hidden" );
$( ".fg4081" ).addClass( "hidden" );
}
and this is the function that looks for new orders
var ultimoid = 4081;
var xultimoid = "";
function nuevospedidos() {
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "cosito3.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText);
console.log(response);
var element = document.querySelector('#contenidogral');
var content = element.innerHTML;
ultimoid = response.ultimoid;
element.innerHTML = response.contenido + content;
}
};
xhttp.send("ultimoid="+encodeURIComponent(ultimoid));
}
setInterval( nuevospedidos, 30000);
Instead of -
$("#contactForm4081").submit(function(event){
// cancels the form submission
event.preventDefault();
submitForm4081();
});
Try with this -
$(document).on("submit","#contactForm4081",function(event){
event.preventDefault();
submitForm4081();
});

How to get all values in a form with Onchange attribute

I'm trying to get all the values in a form when the user selects an option in the droplist. I'm using the Onchange attribute but I don't know how to send the all values to submitForm() via this attribute.
<input type="hidden" name="var1" value="..." />
<input type="hidden" name="var2" value="..." />
<input type="hidden" name="var3" value="..." />
<select name="var4" onchange="submitForm([var1 var2 var3 var4]);return false">
<option value="1">Choice 1</option>
<option value="2">Choice 2</option>
</select>
<script>
function submitForm(var1, var2, var3, var4)
{
var OAjax;
if (window.XMLHttpRequest) OAjax = new XMLHttpRequest();
else if (window.ActiveXObject) OAjax = new ActiveXObject('Microsoft.XMLHTTP');
OAjax.open('POST',"return.php",true);
OAjax.onreadystatechange = function()
{
if (OAjax.readyState == 4 && OAjax.status==200)
{
if (document.getElementById)
{
document.getElementById('msg').innerHTML=''+OAjax.responseText+'';
}
}
}
OAjax.setRequestHeader('Content-type','application/x-www-form-urlencoded');
OAjax.send(var1='+var1+'&var2='+var2'&var3='+var3'&var4='+var4);
}
</script>
Thanks
Since there is no jQuery used in your js method, I'm assuming you are not really using jQuery.
In that case
<select name="var4" onchange="submitForm();">
then
function submitForm() {
//get the input elements by name and then read its value
var OAjax, var1 = document.getElementsByName('var1')[0].value,
var2 = document.getElementsByName('var2')[0].value,
var3 = document.getElementsByName('var3')[0].value,
var4 = document.getElementsByName('var4')[0].value;
if (window.XMLHttpRequest) OAjax = new XMLHttpRequest();
else if (window.ActiveXObject) OAjax = new ActiveXObject('Microsoft.XMLHTTP');
OAjax.open('POST', "return.php", true);
OAjax.onreadystatechange = function () {
if (OAjax.readyState == 4 && OAjax.status == 200) {
if (document.getElementById) {
document.getElementById('msg').innerHTML = '' + OAjax.responseText + '';
}
}
}
OAjax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
//create a parma string using the input values
OAjax.send('var1=' + var1 + '&var2=' + var2 '&var3=' + var3 '&var4=' + var4);
}

Javascript : How to check multiple empty values

I have four input elements in my form. I don't have submit button in my form. I want to check all the values and if all the values are not empty then I want to post that all values to php page by using ajax.
This is my form input elements.
<form method="post" action="getAllDteails.php" name="dashboard">
Manager Name<input type="text" id="managername" onchange="getDetails(this.value)" name="managername"/>
Project Name<input type="text" id="projectname" onchange="getDetails(this.value)" name="projectname"/>
Task Name<input type="text" id="taskname" onchange="getDetails(this.value)" name="taskname"/>
Completion Date<input type="date" id="date" onchange="getDetails(this.value)" name="date"/>
<div id="cool"></div>
</form>
This is my script.
function getDetails()
{
var mname = document.getElementById('managername').value;
var pname = document.getElementById('projectname').value;
var tname = document.getElementById('taskname').value;
var cdate = document.getElementById('date').value;
//alert(mname);
if(mname!==null&&pname!==null&&tname!==null&&cdate!==null)
{
alert("true");
var jsonobj = {"mname" : mname, "pname" : pname, "tname" : tname, "cdate" : cdate};
var js = JSON.stringify(jsonobj);
alert(js);
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(js);
document.getElementById("cool").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","getAllDetails.php?js="+js,true);
xmlhttp.send();
}
}
Just am getting all the values and assigning to four variables. If the four variables are not null then I want to assign all that in single object. But the problem is every time it is coming inside the condition and showing alert.
At fourth time also it is showing the alert. But the values are not going to php page. I'am a beginner Please guide me if I approached in a wrong way.
1.Change Html Code to new code
<form method="post" action="getAllDteails.php" name="dashboard">
Manager Name<input type="text" id="managername" name="managername" class="v1"/>
Project Name<input type="text" id="projectname" name="projectname" class="v1"/>
Task Name<input type="text" id="taskname" name="taskname" class="v1"/>
Completion Date<input type="date" id="date" name="date" class="v1"/>
<input id="Button1" type="button" value="button" onclick="return checkData();" />
</form>
2.Change Script Code to new script code (for checking multipe value)
function checkData() {
var _v = document.getElementsByClassName("v1"); // get all field
var _empty = false; // default has false;
var _jsParm = '';
for (var i = 0; i < _v.length; i++) {
if (_v[i].value == '') {
_empty = true; // if value of null or empty; *
break;
}
_jsParm += _v[i].id + ':\'' + _v[i].value + '\',';
}
//* if any field is null , show alert
if (_empty == true) {
alert('Error!!!!! \r\n Please enter data in all field.');
return false;
}
alert('OK! all field has data.' + '\r\n' + _jsParm)
_jsParm = _jsParm.substr(0, _jsParm.length - 1);
var jsonobj = '{' + _jsParm + '}';
var js = JSON.stringify(jsonobj);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(js);
document.getElementById("cool").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "getAllDetails.php?js=" + js, true);
xmlhttp.send();
}
3.Save
4.Enjoy Now!

Javascript/ajax is passing all form textfield values to the php but not the last textfield value

This is my html with form and javascript/ajax function. All the textfield values are passed to the test.php. When I do so, if i enter the first three textfields then test.php will successfully display the form values. But on the other hand, if I fill all the four textfield and send then nothing will happen. Since, I am new in the programming, i could not figure this issue out. I would be thankful for the solution of this issue.
#form.html
<html>
<SCRIPT language="javaScript">
function sendData(){
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXobject ('Mircosoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById('message').innerHTML = xmlhttp.responseText;
}
}
var i=0;
var arr = new Array();
while ((document.getElementById(i).value)) {
if ((document.getElementById(i).value)!=""){
var activity = document.getElementById(i).value;
arr[i] = activity;
}
i++;
}
var params = 'activity='+JSON.stringify(arr);
xmlhttp.open('POST','test.php', true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send(params);
document.getElementById("message").innerHTML = "Sending...";
}
</script>
<form action="#" method="POST">
<tr>Name1:<td> <input type="text" id="0"/> </td></tr><br>
<tr>Name2:<td> <input type="text" id="1"/> </td></tr><br>
<tr>Name3:<td> <input type="text" id="2"/> </td></tr><br>
<tr>Name4:<td> <input type="text" id="3"/> </td></tr><br>
<input type="button" value="Send" onclick="sendData()";/>
</form>
<div id="message">
</div>
</html>
This is the test.php file where the form value will be displayed.
#test.php
<?php
$activity = $_POST['activity'];
$activity = json_decode($activity);
if (is_array($activity)){
foreach ($activity as $value){
echo $value."<br>";
}
}
else {
echo "error";
}
?>
The issue is with
while ((document.getElementById(i).value)) {
It works just fine until i === 4, then getElementById returns null, and null.value is an error, so the whole thing errors out.
Using a while loop for this doesn't really seem like a good idea, but something like this should at least work
while (document.getElementById(i)) {
if ((document.getElementById(i).value) != "") {
arr[i] = document.getElementById(i).value;
}
i++;
}
Getting the elements by class, tagname or something else other than numeric ID's seems better
var arr = new Array();
var elems = document.querySelectorAll('.inputs'); // class
for ( var i=0; i<elems.length; i++ ) {
arr.push(elems[i].value)
}

Categories

Resources