This is the fragment of code inserted with ajax:
<form>
<label for = "task-name">Name</label>
<input type = "text" id = "task-name" />
<label for = "task-description">Description</label>
<input type = "text" id = "task-description" />
<input type = "hidden" id = "task-col" />
<input type = "hidden" id = "task-row" />
<input type = "submit" id = "add-task" onclick="return false" value="Add" />
</form>
This is the JS code which insert the previous element in the DOM:
$('html').on('click', '.task-pop', function(){
var pos = $(this).parent().parent().attr('class').split("-");
ajaxObj = getXmlHttpObject();
ajaxObj.onreadystatechange = function(){
if(ajaxObj.readyState == 4 && ajaxObj.status == 200){
$('#pop-hold').html(ajaxObj.responseText);
$('#task-col').val(pos[0]);
$('#task-row').val(pos[1]);
}
};
ajaxObj.open("GET","resources/component/newTask.jsp");
ajaxObj.send(null);
$('#pop-blk').css('display','block');
$('#pop').show("fast");
});
As you can see I'm trying to add some values to the hidden inputs #task-row and #task-col from the content added dynamically.
The page is properly displayed and no error is thrown but those two fields are never accessed. How can I solve this?
change
$('#pop-hold').html(ajaxObj.responseText);
$('#task-col').val(pos[0]);
$('#task-row').val(pos[1]);
with
var html = $(ajaxObj.responseText);
html.find('#task-col').val(pos[0]);
html.find('#task-row').val(pos[1]);
$('#pop-hold').html('').append(html);
You should use jQuery ajax(), would be much easier for you to handle the whole Ajax thing :
$('html').on('click', '.task-pop', function(){
var pos = $(this).parent().parent().attr('class').split("-");
$.ajax({
url: 'resources/component/newTask.jsp',
type: 'GET', // Default value is GET but I included it for you
success: function(data) {
$('#pop-hold').empty().append(data);
$('#task-col').val(pos[0]);
$('#task-row').val(pos[1]);
}
});
$('#pop-blk').css('display','block');
$('#pop').show("fast");
});
Just a part of the solution, hope it will help ^^
The fact that the inputs are hidden don't prevent you from setting their value with val().
When you call the val function like this $('#task-col').val(pos[0]);, make sure that:
The #task-col element exists
pos[0] is not undefined (you can test by replacing pos[0] with "test")
you are actually executing this line (you can test by putting an altet("test") the line before)
And when you use jQuery, don't mess around with the getXmlHttpObject as #Ethenyl said. Use $.ajax instead.
Related
I have a textfield:
Voornaam: <h3 class="title1">Kevin</h3>
<input type="text" id="myTextField1" />
<input type="submit" id="byBtn" value="Change" onclick="change1()"/><br/>
I can set a value of this using this function:
function change1(){
var myNewTitle = document.getElementById('myTextField1').value;
if( myNewTitle.length==0 ){
alert('Write Some real Text please.');
return;
}
var titles = document.getElementsByClassName('title1');
Array.prototype.forEach.call(titles,title => {
title.innerHTML = myNewTitle;
});
}
Now in my other page, I want to use the value. I know I can for example pass a value from one page to another like this:
<a href='convert.php?var=data'>converteren.</a>
And then for example show it by doing this in the other page:
echo $_GET['var'];
But I cant really seem to figure out how to use the value which I've set using my textfield.
So my goal for now is to display the value I've set using my textfield in the other page using the method I just described.
Basically all I want to happen is for my textfield to change the value inside here aswell:
<a href='convert.php?var=data'>converteren.</a>
So where data is the value, I want it to become what I've put in the textfield.
Could anybody provide me with an example?
I've altered a bit your javascript code to make the link as you want.
To explain the answer, i've added document.getElementById("myLink").href="convert.php?var=" + myNewTitle ; which updates your a href while your function runs and is not empty.
function change1(){
var myNewTitle = document.getElementById('myTextField1').value;
if( myNewTitle.length==0 ){
alert('Write Some real Text please.');
return;
}
document.getElementById("myLink").href="convert.php?var=" + myNewTitle ;
var titles = document.getElementsByClassName('title1');
Array.prototype.forEach.call(titles,title => {
title.innerHTML = myNewTitle;
});
}
<a id="myLink" href='#'>converteren.</a>
Wrap your inputs inside a form element.
In the action attribute, specify the destination url.
In the method attribute, choose between GET and POST.
For example:
<form method="GET" action="convert.php">
<input type="text" id="myTextField1" />
<input type="submit" id="byBtn" value="Change" onclick="change1()"/>
</form>
Clicking the submit button will call "convert.php?myTextField1={value}".
I am trying to change the value of a hidden field on submission by JavaScript. In my page there are two buttons, one for going back to homepage (index.php) and another for returning to the first page for data entry (addData.php). I am trying to use a hidden field with id "goHome" to control the routeing. My codes are like this:
HTML (Form only)
<form name = "addDataReal" id = "addDataReal" method = "POST" action = "addDataProc.php" onsubmit="return checkNSub()">
<!-- Other items -->
<input type = "submit" name = "submitBtnF" id = "submitBtnF" class="shortText" style = "width: 120px;" value = "Submit + Home" onclick = "return getGoValue(true)"/>
<input type = "submit" name = "submitBtnR" id = "submitBtnT" class="shortText" style = "width: 120px;" value = "Submit + Next" onclick = "return getGoValue(false)"/>
<input type = "hidden" name = "goHome" id = "goHome" value = "" />
</div>
</form>
Javascript
function checkNSub() {
//form validation functions
//OK then return true
//Not then return false
}
function getGoValue(goHome) {
if (goHome) {
document.getElementById("goHome").value = "true";
} else {
document.getElementById("goHome").value = "false";
}
return true;
}
Before this I have tried many other versions and I refered to these few questions:
Set form hidden value on submit
Setting a form variable value before submitting
How to change the value of hidden input field before submitting
But none of the methods were working for me.
For practical purposes there is a workaround for this, but I want to know if I would like to keep these two buttons, how should my code be modified so that the value of "goHome" can be changed before the form is submitted? After many attempts I am still getting $_POST["goHome"] = "".
Also, why is the form submitted before the value is actually changed when the code is placed before that?
Thanks!
It's old question But I thought If any one still looking for the answer , here it is
You can try jquery $('input[name="goHome"]').val('true');
or JS - document.getElementByName("goHome").value = "true";
This will work for sure.
While updating any value at the time of submitting for use name selector instead of ID, that will save you some time :)
When we try to change value of Hidden field at the time of submitting form it didn't update value because DOM has already detached the ID from the input parameter but name is still there because name is going to be passed in form.
If anyone find this useful and they do not have to work for lot hours for a simple solution :)
Happy Coding :)
Various ways to achieve this. Firstly though keep in mind that you are using type="submit" <input> inside a <form> , and that means that they will automatically submit the form regardless of an onclick event or not.
One as much as less intrusive (to your code) way is the following:
Take out the submit inputs from your form like this:
Example :
<form name = "addDataReal" id = "addDataReal" method = "POST" action = "whatever.php">
<!-- Other items -->
<input type = "hidden" name = "goHome" id = "goHome" value = "" />
</div>
</form>
<input type = "submit" name = "submitBtnF" id = "submitBtnF" class="shortText" style = "width: 120px;" value = "Submit + Home" onclick = "return getGoValue(true)"/>
<input type = "submit" name = "submitBtnR" id = "submitBtnT" class="shortText" style = "width: 120px;" value = "Submit + Next" onclick = "return getGoValue(false)"/>
Change your getGoValue() and checkNSub() functions like this :
function checkNSub() {
//form validation functions
//OK then return true
//Not then return false
var myForm = document.getElementById('addDataReal');
myForm.submit();
}
function getGoValue(goHome) {
if (goHome) {
document.getElementById("goHome").value = "true";
console.log(document.getElementById("goHome").value);
checkNSub();
} else {
document.getElementById("goHome").value = "false";
console.log(document.getElementById("goHome").value);
checkNSub();
}
return true;
}
Try it out.
P.S : A couple of console.logs so you can check out the value changing. Comment out checkNSub(); to see them in your console. Nevertheless keep in mind that you are posting a Form which means you are going to load a new page from the server , this new page will be agnostic regarding your "goHome" value. The "goHome" value exists only while you are on the same page. The moment your DOM is "recreated" you will lose it.
P.S.2 :
Your return true; inside the getGoValue(); is not needed in my
example. You can remove it.
the return in your onclick = "return getGoValue(true)" is also
not needed and you can remove it
P.S.3 :
This reply is focused on keeping most of your code intact. In reality now that you have your inputs outside the form there is no need for them to be of type="submit" you should change them to <button> with onClick events (or Listeners).
I have my AJAX form it works great.
Every time I submit the form It returns the result inside the <div id="message"></div>, but it gets complicated when I have multiple forms. So I was wondering if their is a way to indicate inside the form what <div> to return the message to.
Here is my AJAX.js
$("form#ajaxForm").on("submit", function() {
var form = $(this),
url = form.attr("action"),
type = form.attr("method");
data = {};
form.find("[name]").each(function(index, value){
var input = $(this),
name = input.attr("name"),
value = input.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
$("#message").html(response); //I would like to interactively switch the return div, from #message to like #message2
$("body, html").animate({
scrollTop: $( $("#message") ).offset().top - 5000
}, 600);
}
});
return false;
});
In the form I would like to indicate where the return div is, like
<form action="../forms/add_event_form.php" method="post" id="ajaxForm">
//Can I add an input somewhere here? To indicate where I want the return to go too? Like <input type="hidden" value="message2" name="return">
<input type="text" class="formI" name="date" id="dateI" placeholder="Date">
<input type="submit" name="submit" class="btn btn-primary" value="Add">
</form>
Thank you for reading this. Have a good day! And Thank you in advance for your responses.
Yes, it will not work automatically, but you can add some information to the form and then use it to decide where to put returned HTML. Doing that with additional inputs may not be the best way though, as it can be achieved with far less impact on the DOM: with an attribute on the form itself.
Here's an example of how you may do that.
$(".ajaxForm").on("submit", function(e) {
e.preventDefault();
var form = $(this);
// using jQuery's `data()` to get an ID of response element from the 'data-response' attribute
var responseElementId = form.data("response");
var response = $(responseElementId);
response.html(produceResponse(form));
// function that produces some html response
// you'll use AJAX request to the server for that
// so don't mind its complexity or bugs
function produceResponse(form) {
var data = form.find("input").map(function(i, el) {
return "'" + el.name + "': " + el.value;
});
return "<p>You've submitted:\n<pre>" + Array.prototype.join.call(data, ",\n") + "</pre></p>";
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Form #1</h2>
<form action="#" class="ajaxForm" data-response="#response1">
<input name="first-name" type="text">
<button>Submit</button>
</form>
<div id="response1"></div>
<h2>Form #2</h2>
<form action="#" class="ajaxForm" data-response="#response2">
<input name="last-name" type="text">
<button>Submit</button>
</form>
<div id="response2"></div>
Here I use a data attribute because it was designed for cases like this: to store arbitrary data related to the element, but which doesn't have any defined meaning for the browser. Accessing data stored in such way is really convenient with its HTML5 API, but because of pretty low support from IE (it has it only starting from the version 11), one may use jQuery's method data() to do the same.
Model # : <input type="text" name="model" id="newmodel" value="" >
Serial # : <input type="text" name="fserial" value="" class="serialClass" id="myserial">
in script I have: enter code here
<script>
//Here I can't get the value of serial# with the id="myserial"
var newserial = $("#myserial").val();
$(document).ready(function(){
$('#myserial').change(function(){
//this is a test alert, (OUTPUT = "seial number: undefined variable"), which means that
alert("serial number: "+ newserial);
$.ajax({
type: 'GET',
url: 'toshGet.php',
//upon success, pass newserial
data: {keyword: newserial},
success: function(msg){
$('#txtHint').html(msg);
}
});//ajax()
});//change()
});//document.ready()
</script>
I know this is really strange but can't get assigned the text input's value to the variable "newserial". Here is so far a piece of the code:
The problem in your case is that you are assigning element with id 'myserial' to a variable when it is not rendered properly inside DOM.
Instead of assigning var newserial = $("#myserial").val(); outside document.ready() try this:
var newserial;
$(document).ready(function(){
newserial = $("#myserial").val();
....
});
Or (if you want updated value of '#myserial' then)
Use var newserial = $("#myserial").val(); or var newserial = $(this).val(); inside change event handler itself.
Or
Just assign value directly without taking any extra variable in ajax call as shown :
data: { keyword: $("#myserial").val() }, //or $(this).val()
Side Note :- Your alert("serial number: "+model); is absolutely wrong because there is no variable with name model in your code.
In the form below, I change the action attribute and submit the form. That works fine. What goes on is: if the current location is http://localhost/search/?mod=all and the search term is 14, the action will be changed to http://localhost/search/?mod=all&handle=14 and so will the url in the browser.
But the next time I try to search, since the url now is http://localhost/search/?mod=all&handle=14, I get http://localhost/search/?mod=all&handle=14&handle=15. It'll keep going on and on with each search term.
Any idea how I can retain the orginal url http://localhost/search/?mod=all through this all.
Here's the form:
<form method="GET" class="modForm" action="">
<input type="text" placeholder="Search" class="modSearchValue">
<input type="radio" name="text" value="text" class="text" title="Search">
</form>
Here's the jquery:
$('.modForm').submit(function(event) {
var $this = $(this);
var query = $this.find('.modSearchValue').val(); // Use val() instead of attr('value').
var locale = window.location;
if ($('.text').is(':checked')) {
query = '&text=' + query;
} else {
query = '&handle=' + query;
}
route = locale + query;
console.log(route);
if (query.length >= 1) {
// Use URI encoding
var newAction = (route);
console.log(newAction); // DEBUG
// Change action attribute
$this.attr('action', newAction);
//event.preventDefault();
} else {
console.log('Invalid search terms'); // DEBUG
// Do not submit the form
event.preventDefault();
}
});
There are few ways to do it. I would rather not mess with window.location and do something simpler:
<form method="GET" class="modForm" action="">
<input type="hidden" name="mod" value="all"> <!-- mod is a hidden variable -->
<input type="text" id="modSearchValue"> <!-- name not defined yet -->
<input type="checkbox" id="textOrHandle"> <!-- name not required -->
</form>
$(".modForm").submit(function() {
$("#modSearchValue").attr("name", $("#textOrHandle").is(":checked") ? "text" : "handle");
// let the form submit!
});
You have multiple ways to do it. Why can't you store original URL in a global variable (kept outside your functions like form submit etc.)
If you do not want that you can use window.location.hash which will return all the GET params you are sending. Using split you will be able to get exact parameter that you want. If you still need help, I will post the code.
Quickest solution: If, for this code, window.location should always be http://localhost/search/?mod=all, then you don't even need to say var locale = window.location. Just say var locale = "http://localhost/search/?mod=all" and you avoid the problem.
var s = window.location.hostname; // gets the hostname
var d = window.location.protocol; // gets the protocol
var g = window.location.search; // gets all the params
var x = g.split("&"); // split each parameter
var url = d+"//"+s+x[0]; // makes url you want
alert(url); // just for chill