I have two fields in form and onsubmit() event I am calling function. When I click udpate button I could not get the values of "sent", all other values fetched correctly.
In case of insert button, sent is fetched correctly.
I am tracking the values using aler button. Can it be done using firebug too?
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type" />
<meta content="utf-8" http-equiv="encoding" />
<script type="text/javascript">
function showUser(form, e) {
e.preventDefault();
e.returnValue=false;
var xmlhttp;
var submit = form.getElementsByClassName('submit')[0];
var sent = document.getElementsByName('sent')[0].value || '';
var id = document.getElementsByName('id')[0].value || '';
**alert(id);
alert(sent);
alert(submit.name);
alert(submit.value);**
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(e) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open(form.method, form.action, true);
xmlhttp.send('sent=' + sent + '&id=' + id + '&' + submit.name + '=' + submit.value);
}
</script>
</head>
<body>
<form action="ajax_test.php" method="POST" onsubmit="showUser(this, event)">
<label>Enter the sentence: <input type="text" name="sent"></label><br />
<input type="submit" class="submit" name="insert" value="submit" />
</form>
<h4>UPDATE</h4>
<form action="ajax_test.php" method="POST" onsubmit="showUser(this, event)">
<pre>
<label>Enter the ID:</label><input type="text" name="id"><br>
<label>Enter the sentence:<input type="text" name="sent"></label><br />
</pre>
<input type="submit" class="submit" value="submit" name="update"/>
</form>
<br />
<div id="txtHint">
<b>Person info will be listed here.</b>
</div>
</body>
</html>
You're always getting the first sent and id elements because you're using document.getElementsByName, so you need to grab the ones within the form that is submitted. By always getting the first, you will get the values from the insert form even when the update form is submitted.
var sent = form.elements['sent'].value;
var id = form.elements['id'].value;
The above will get the sent and id values from the form that was submitted, based on the form object that was passed as an argument.
You can use console.log(...) and console.debug() with firebug.
See the documentation for more info: https://getfirebug.com/wiki/index.php/Console_API
Not sure what you're trying to accomplish, but you should at least provide us with a copy of ajax_test.php if you want us to test your code. Do you get any error messages in to firebug console?
Also, why not use the ajax features of jQuery? That would make things far easier on yourself. Piao Yishi has a good tutorial on NetTuts+ on how to do that: http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/
Doing so might just solve your problems.
Related
Completely flummoxed after going over and over this problem for hours. Have tried a large number of approaches, without success.
Intent is to send login form data to PHP and have PHP return the result of an API call.
My latest approach is to have form onSubmit in login.html call myFunction() which performs POST call to n_authorise.php for some server side processing. In future the PHP will return API secrets. For my testing I stripped back the PHP to echo back the user input extracted from the $_POST global.
No matter what combinations of form ACTION / SUBMIT or XMLHttpRequest structures I try, I can't seem to pass the $_POST from the HTML to the PHP. I repeatedly get "Undefined index" from the PHP suggesting the $_POST is not populated.
I have tried action="n_authorise.php" directly in the form (avoiding myFunction() ) but this either fails or when it does work loads the PHP file to the browser NOT just returning the result.
I am so frustrated as it has to be possible and I can see from other postings that they have had (and resolved) similar problems... I just can't crack it, so asking the experts! Thanks in advance.
My HTML in file login.html :
<html>
<head>
<script>
function myFunction() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
};
xmlhttp.open("post", "n_authorise.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
}
</script>
</head>
<body>
<form name="loginform" onsubmit="myFunction()" method="post">
<input type="text" name="t_username" id="t_username" placeholder="Username" required autofocus>
<input type="password" name="t_password" id="t_password" placeholder="Password" required>
<input name ="submit" type="submit" value="submit">
</form>
</body>
</html>
My minimal PHP in file n_authorise.php
<?php
$email = $_POST["t_username"];
$password = $_POST["t_password"];
echo $email . " " . $password;
?>
Expected result is for alert box to display entered email & password (this would be replaced in final version).
Note: I have tried with and without xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");. In fact, I think I've tried nearly every possible combination of code without success... yet.
This is a most simple answer:
you are not adding any parameters to your request, you could do it with native js like this:
var form = document.querySelector('form'); // <-- extend this to select your form, maybe add an id to select
var data = new FormData(form);
var req = new XMLHttpRequest();
req.send(data); // <----- this way the form data is appended
Based on the above - sharing working code with humble thanks. FYI only:
<html>
<head>
<script>
function myFunction() {
var form = document.querySelector('form.loginform'); // <-------- extended to select new class ID for form
var data = new FormData(form); // <-------- 'data' extracts form content
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
};
xmlhttp.open("post", "n_authorise.php", true);
xmlhttp.send(data); // <-------- 'data' sent to PHP!
}
</script>
</head>
<body>
<form name="loginform" class="loginform" onsubmit="myFunction()" method="post">. // <-------- new class added
<input type="text" name="t_username" id="t_username" placeholder="Username" required autofocus>
<input type="password" name="t_password" id="t_password" placeholder="Password" required>
<input name ="submit" type="submit" value="submit">
</form>
</body>
</html>
I want to prevent the main form to be submitted according to AJAX response.
HTML is like this...
<form action="test.php" method="POST">
<input type="text" name="email" id="email" onblur="ajax_check_email();">
<span id="email_alert"></span>
<input type="submit" name="submit">
</form>
Now I have a js file with ajax query -
function ajax_email_check () {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("email_alert").innerHTML=xmlhttp.responseText;
}
}
var email = document.getElementById("email").value;
xmlhttp.open("GET","ajax/check_email.php?email=" + email,true);
xmlhttp.send();
}
Now the php page returns Email Already Exists or Success.
All goes well but after showing the Text that the "email already exists...!" the main form is getting submitted when I hit submit. It should prevent me. But how am I gonna do that?
You can simply add a flag like var shouldSubmit = false, in your ajax response, if it's okay to submit, change shouldSubmit to true, then add a eventlistener to form
<script>
yourform.addEventListener("submit", function(e){
if(!shouldSubmit){
e.preventDefault();
return false;
}
});
</script>
Just catch the event and stop it.
<form id="myform" action="test.php" method="POST">
<script>
$('form#myform').submit(function(e){
e.preventDefault();
});
</script>
Just add this in form tag onsubmit="return false;"
Like this-
<form action="test.php" method="POST" onsubmit="return false;">
<input type="text" name="email" id="email" onblur="ajax_check_email();">
<span id="email_alert"></span>
<input type="submit" name="submit">
</form>
Have Radio Buttons to Trigger Different PHP Functions.. At the moment though, the page just flashes when the submit button is clicked!
IT SEEMS THE .PHP NEEDS TWEAKING!!
Would like the functions to perform without a page refresh, hence AJAX..
The Form field should submit a string to the PHP when the Submit Button (Return) is clicked, subject to the selected Radio button.
http://bootply.com/61461
HTML PAGE:
<div class="container">
<!-- Input Section -->
<form action="">
<fieldset>
<legend>A Form to input plain English and output Pig Latin</legend>
<label></label>
<input class="span9" type="text" id="txt1" name="yourText" placeholder="… Type Something Here …"><br><br>
<span class="help-block">Choose whether or not you want to have the English input echoed on the output as Pig Latin:</span>
<label class="radio inline">
<input type="radio" name="optionsRadios" id="english" value="english" checked>
Echo the English Input
</label>
<label class="radio inline">
<input type="radio" name="optionsRadios" id="piglatin" value="piglatin">
Output as Pig Latin
</label>
<br><br>
<button type="submit" class="btn" onClick="showTxt(this.value)">Return</button>
</fieldset>
</form>
<br><br><br>
<!-- Output Section -->
<span id="return-text">
<p>Text Will Post Here</p>
</span>
</div>
PHP PAGE:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Pig Latin PHP</title>
</head>
<body>
<?php
if( isset($_POST['yourText'])){
$text = $_POST['yourText'];
}
function engish(){
if( isset($_POST['optionsRadios']) &&
$_POST['optionsRadios'] == 'english'){
echo $text;
}
}
function piglatin(){
if( isset($_POST['optionsRadios']) &&
$_POST['optionsRadios'] == 'piglatin'){
echo '…pig latin php operation to be written…';
}
}
echo english();
echo piglatin();
?>
</body>
</html>
AJAX SCRIPT (thanks to ogc-nick's answer):
<!-- AJAX Call to piglatin.php -->
<script>
function showTxt(str)
{
var xmlhttp;
if (str.length==0)
{
document.getElementById("return-text").innerHTML="";
return;
}
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("return-text").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","piglatinajax.php", true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var dataString = $('form').serialize();
xmlhttp.send(dataString);
}
Thanks for Looking
It looks like your request is sending the data in the $_GET variable q but you php is looking for the indexes. You need to add post data in the send method like so
var optionsRadios = document.forms[formname].optionsRadios.value;
var yourText = document.forms[formname].yourText.value;
xmlhttp.send("optionsRadios=" + optionsRadios + "&yourText=" + yourText);
Reference: http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
I am trying to call a function with Javascript, HTML, AJAX, and PHP.
I am still new to Javascript, AJAX, and PHP.
Background info: I am trying to add a new customer to my database but I am now trying to get a confirmation message on the same page without the page refreshing.
This is what I have:
<script type="text/javascript">
function addCustomer(ln,fn,pn,dob)
{
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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","addCustomer.php?add_LN="+ln+"?add_FN="+fn+"?add_PN="+pn+"?add_DOB="+dob,true);
xmlhttp.send();
}
</script>
<p>Suggestions: <span id="txtHint"></span></p>
<form action="return addCustomer(this.add_LN, this.add_FN, this.add_PN, this.add_DOB);">
<input type="text" name="add_LN" id="add_LN" />
<br />
<br />
<input type="text" name="add_FN" id="add_FN" />
<br />
<br />
<input type="text" name="add_PN" id="add_PN" />
<br />
<br />
<input type="text" name="add_DOB" id="add_DOB" />
<br />
<br />
<input type="submit" name="add_Customer" id="add_Customer" value="Add Customer" />
</form>
<span id="txtHint"></span>
</p> </td>
</tr>
</table>
</div>
I get a "This link appears broken"
With:
http://127.0.0.1/cpsc471/return%20addCustomer(this.add_LN,%20this.add_FN,%20this.add_PN,%20this.add_DOB);?add_LN=ee&add_FN=123&add_PN=eee&add_DOB=eee&add_Customer=Add+Customer
in the url bar.
What am I doing wrong? :) I do not want the page to refresh. I am trying to just get the confirmation or non-confirmation to display.
Thanks again for all the help!
Your problem is here:
<form action="return addCustomer(this.add_LN, this.add_FN, this.add_PN, this.add_DOB);">
You don't want the form action to be a javascript call, you need to do this onclick or something.
The arguments above by #thiefmaster and #martin are correct: using jquery is much simpler. You are right about the framework thing, but in this case you need to go and code for a lot of troubles (responses, when is there a successfull AJAX call, different browsers etc)
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
// put your codes here like
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
// document.getElementById("show_label").innerHTML='text as you wish like updated enjoy';
}
}
And add a label with the id of show_label
I'm going to get the checked radio button value using AJAX in PHP. I have done the following code, but i can't continue.
I need your help.
ajax_radio.php
<html>
<head>
<script type="text/javascript" src="ajax.js" ></script>
</head>
<body>
<input type="radio" name="radio1">Blue</input>
<input type="radio" name="radio2">White</input>
<input type="radio" name="radio3">Red</input>
<input type="button" name="btn" value="Click" onClick="hello('a')"></input><br />
<input type="text" id="btn_get" name="get_btn_value"></input>
</body>
</html>
ajax.js
var xmlHttp;
function GetXmlHttpObject(){
try{
xmlHttp = new XMLHttpRequest();
}
catch(e){
try{
xmlHttp = new ActiveXObject(Msxml2.XMLHTTP);
}
catch(e){
try{
xmlHttp = new ActiveXObject(Microsoft.XMLHTTP);
}
catch(e){
alert("doesn't support AJAX");
return false;
}
}
}
}
function hello(a){
GetXmlHttpObject();
xmlHttp.open("GET","ajax_radio.html?",true);
xmlHttp.onreadystatechange = response;
xmlHttp.send(null);
}
function response(){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
var radio_text = xmlHttp.responseText;
document.getElementById('btn_get').innerHTML = radio_text;
}
}
}
Do you know how to complete this? Thanks in advance. :)
Edit:
I can't post the code here right now, because of the low speed of network. I'm sorry.
I have shared it in rapidshare. Can you download it firstly, and help then? Thanks a lot.
I have to update it when i go back home. Too bad.
because I mostly use Jquery I wrote here a jquery snipped that checks radio button values because it is much easier and cleaner:
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1.4.0");
</script>
<script type="text/javascript">
$(function() {
$('#buttoncheck').click(function () {
var var_name = $("input[name='radio1']:checked").val();
$('#btn_get').val(var_name);
});
});
</script>
<html>
<head>
<script type="text/javascript" src="ajax.js" ></script>
</head>
<body>
<input type="radio" value="Blue" name="radio1">Blue</input>
<input type="radio" value="White" name="radio1">White</input>
<input type="radio" value="Red" name="radio1">Red</input>
<input id="buttoncheck" type="button" name="btn" value="Click"></input>
<br />
<input type="text" id="btn_get" name="get_btn_value"></input>
</body>
</html>
Take a look for jquery here: Jquery
Explanation:
This part selects the item with the ID #buttoncheck and checks if its ran: $('#buttoncheck').click(function () {
Then it will run the code in the function. This code gets the value of a input box with the name radio1. the ':checked' makes sure that it only selects the value of the checked radio button:
var var_name = $("input[name='radio1']:checked").val();
And last. This puts the value of the variable into the item with #btn_get as id:
$('#btn_get').val(var_name);