I am having trouble in submitting radio input values using PHP and AJAX. I've constructed the code below, but I can't seem to get it to work. Any ideas? The values of the radio fields need to pass only when the button is pressed
<script>
function showUser(str) {
if (str == "myvalue") {
document.getElementById("txtHint").innerHTML = "";
/// location of new code -start
document.querySelector('input[name="users"]:checked').value;
/// location of new code -end
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "ajax-php.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
<form>
<input type="radio" name="users" value="1">
<input type="radio" name="users" value="2">
<!-------unable to pass value----------->
<input type="button" value="myvalue" onclick="showUser(this.value)">
<!-------unable to pass value----------->
</form>
<div id="txtHint">echo results here</div>
ajax-php.php
<?php
$q = intval($_GET['q']);
echo $q;
?>
Thank you.
Your 'this.value' parameter being passed to your showUser function is scoped to the element with the onclick function.
So it is trying to send the value of the button element which has no value.
What you are doing is fine.
<input type="button" onclick="showUser(this.value)">
The function showUser is called by the button type input field. And the field has no value.
If you want to send any value then use value attribute. For example:
<input type="button" value="mayValue" onclick="showUser(this.value)">
To access the radio button value you can use this code.
document.querySelector('input[name="users"]:checked').value;
To send the radio button value follow the code bellow
//xmlhttp.open("GET", "ajax-php.php?q=" + str, true);
xmlhttp.open("GET", "ajax-php.php?q=" + document.querySelector('input[name="users"]:checked').value, true);
Related
In my HTML I have an article containing clickable lists. I also have a form that adds data to my database. Once it's done adding the data I want my PHP to send a new list based off the data given in the form to the article in my HTML with my other lists.
How can I do this? I know how to display data from PHP in HTML but I don't know how to display that data in existing articles in HTML.
My function that updates and refreshes my page after every click on a link is called MyFnc and this is the JavaScript for it:
function myFnc(x) {
if (x == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else { //if a link is clicked
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
//readyState = 4: request finished and response is ready
//status = 200: "OK"
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", "get_data.php?q=" + x, true);
xmlhttp.send();
}
}
And get_data.php is where I display the data from the database to the webpage. I know that displaying the link must be done in get_data since that is where I display everything to the page. But for now I just want to know how to send the data retrieved from add_records and make a list out of it.
This is my article in my HTML:
<article>
<ul class="lists" style="list-style-type:none">
<li>Tiger</li>
<li>Hammerhead</li>
<li>Bull</li>
<li>Great White</li>
<li>Mako</li>
<li>Greenland</li>
<li>Whale</li>
<li>Thresher</li>
<li>Oceanic WhiteTip</li>
<li>Goblin</li>
</ul>
</article>
Here is my form in my HTML:
<form method="post" action="add_to_records.php">
<input type="hidden" name="addshark" value="true" />
<fieldset>
<label>Name:<input type="text" name="Name" /></label>
<label>SpeciesID:<input type="text" name="speciesID" /></label>
<label>Genus:<input type="text" name="genss" /></label>
<label>Family:<input type="text" name="famly" /></label>
<label>Order:<input type="text" name="ordr" /></label>
<label>Class:<input type="text" name="clss" /></label>
<label>Create New Shark</label>
<input type="submit" value="add shark" />
</fieldset>
<br />
</form>
Here is my add_to_records.php:
<?php
include 'connect.php';
if (isset($_POST['addshark']))
{
include 'connect.php';
$Namee = mysqli_real_escape_string($connect,trim($_POST['Name']));
$specID = mysqli_real_escape_string($connect,trim($_POST['speciesID']));
$gens = mysqli_real_escape_string($connect,trim($_POST['genss']));
$fam = mysqli_real_escape_string($connect,trim($_POST['famly']));
$ord = mysqli_real_escape_string($connect,trim($_POST['ordr']));
$cls = mysqli_real_escape_string($connect,trim($_POST['clss']));
if (!mysqli_query($connect, "INSERT INTO Species
(SpeciesID,Genus,Family,Order_,Class)
VALUES ('$specID','$gens','$fam','$ord','$cls')"))
{
die('error inserting new record');
}
//I would like the list it returns to look like this if the Name entered was Hello
//and the speciesID entered was Something
//<li>Hello</li>
//echo "shark was added";
header('Location: ProjectMainAdmin.html'); exit;
}
mysqli_close($connect);
?>
Just use jQuery's AJAX, it's a lot simpler and easier to implement. Data will be passed to server, then once completed you need to append the data into your list.
something like this:
$("form").submit( function(){
$.ajax({
url: "add_to_records.php",
success: function(result){
$(".lists").append("<li><a href=''>" + result.name + "</li>");
}
});
return false;
});
I'm trying to add an auto-complete function to a text field.
This used to work, but then I switched to an MVC structure and now I can't get it back to work.
PHP/HTML:
echo '<br><br>Add member:<br>'
. '<form method="post"><input type="text" name="username" oninput="findUsers(this.value)" list="livesearch">'
. '<datalist id="livesearch"></datalist>'
. '<input type="submit" value="Add">'
. '</form>';
JavaScript:
<script>
function findUsers(str) {
if (str == "") {
document.getElementById("livesearch").innerHTML = "no suggestions";
xmlhttp.send();
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("livesearch").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","/user/search/?q="+str,true);
xmlhttp.send();
}
}
</script>
/user/search opens a function called search in the class User in the UserController.php file
class UserController extends Controller
{
public function search()
{
$response = "hello";
echo $response;
}
}
So this should put the "hello" message in the livesearch datalist.
But for some reason just nothing is happening.
If I replace the xmlhttp.open by window.open, the page does load normally and shows the hello message. But that is obviously not what I want.
Figured out the exact problem:
My xmlhttp.responseText is also returning the header of my website, which is already loaded in the MVC structure.
How would I work around this?
Is it an option to just edit the string and get the last part in javascript?
Or are there better solutions?
Used JavaScript to grab the last part of the string (so without the header)
It does what it's supposed to do now, but feels like a pretty "dirty" solution.
Also had to add the <option value=""> tag, which was in my code, but not in my testcode.
I am getting response without a refresh! When the user clicks on the button, I want it to reload and then display the response!How can I do that?
And What should I do to uncheck the radio box after the response?
<script>
function sendid(attack) {
var att;
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("result").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "battleuser2.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("att=" + attack);
}
</script>
This is my radio form:
<input type="radio" value="10" id="radioButtonId" onClick="sendid(this.value)"/> Attack 1
<input type="radio" value="20" id="radioButtonId" onClick="sendid(this.value)"/> Attack 2
No, you can't reload and display the response unless you are making the ajax call on page load again.
else you need to store the previous response in localstorage and access it from it when the page reloads again.
Regarding unchecking the radio button after the response, Insert the following code inside the if condition:
document.getElementById("radioButtonId").checked = false;
example:
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("result").innerHTML = xmlhttp.responseText;
document.getElementById("radioButtonId").checked = false;
}
I've a JSP page which includes a checkbox, so when i try to submit the form using the conventional javascript way of document.forms[0].submit(); the form gets refreshed and the checkbox values are not getting retained.
Can anybody help me on how to send the form value using only AJAX. I don't need the way to send using JQuery.
This is the code I had used for sending using form submit:
function relatedAER(){
......
document.forms[0].literatureSelected.value = litNO + "&";
document.forms[0].opCode.value = "relatedAER";
document.forms[0].target='_self';
document.forms[0].action="<%=request.getContextPath()%>/litaer.do?selected="+selected;
document.forms[0].submit();
}
I hope next time, you'll put some effort, into creating even a simple code, and showing us instead of asking for a script.
Now, that bieng said: This will submit a username to a php file, called fetch.php
HTML
<input type='text' name='user' id='user' /><br/>
<input type='submit' name='submit' onclick='check()' />
<div id='output'></div>
Ajax:
function check(){
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState === 4 && xmlhttp.status === 200){
document.getElementById('output').innerHTML = xmlhttp.responseText;
}
}
get_user = document.getElementById('user').value;
param = "name="+get_user;
xmlhttp.open('POST','fetch.php', true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(param);
}
</script>
i am trying to auto submit form when the input reaches 7 characters. i have tried few java script codes, but it is spoiling my script functioning.
can any one please help me in this.....
<script type="text/javascript">
var url = "GetCustomerData.php?id="; // The server-side script
function handleHttpResponse() {
if (http.readyState == 4) {
if(http.status==200) {
var results=http.responseText;
document.getElementById('divCustomerInfo').innerHTML = results;
}
}
}
function requestCustomerInfo() {
var sId = document.getElementById("txtCustomerId").value;
http.open("GET", url + escape(sId), true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
}
function getHTTPObject() {
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject){
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
if (!xmlhttp){
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
}
return xmlhttp;
}
var http = getHTTPObject(); // We create the HTTP Object
</script>
<form id="form_home">
<p>Enter customer ID number to retrieve information:</p>
<p>Customer ID: <input type="text" maxlength="7" id="txtCustomerId" value="" /></p>
<p><input type="submit" value="Submit" onclick="requestCustomerInfo()" /></p>
</form>
<div id="divCustomerInfo"></div>
Here is the code that will submit the form when the text box reaches 7 chars:
document.getElementById('txtCustomerId').addEventListener('keyup', function(e) {
if(this.value.length === 7) {
document.getElementById('form_home').submit();
}
});
Here is a demo of it working:
http://jsfiddle.net/TuVN2/1/
Looking at your markup, I guess you want to run requestCustomerInfo() and not submit. If you submit the response will never be handled. To do this you would move the function call into the keyup handler:
document.getElementById('txtCustomerId').addEventListener('keyup', function(e) {
if(this.value.length === 7) {
requestCustomerInfo();
}
});
I would also not recommend hand rolling your ajax handler. Consider using a library like jQuery.