Multi-submit buttons on one form with ajax - php

I have a form which has 5 submit buttons like
<form action="pages/test.php" method="post" name="form1 "onsubmit="ajaxrequest('pages/test.php', 'resp'); return false;">
<input type="hidden" name="Id" id ="Id" value=<?php echo "{$Id}"; ?> />
<input type="submit" name="Value" value="0.01" />
<input type="submit" name="Value" value="0.02" />
<input type="submit" name="Value" value="0.03" />
<input type="submit" name="Value" value="0.04" />
<input type="submit" name="Value" value="0.05" />
</form>
<div id="resp">Here will be displayed the server response.</div><br />
The ajax processing for this is:
function get_XmlHttp() {
var xmlHttp = null;
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
// sends data to a php file, via POST, and displays the received answer
function ajaxrequest(php_file, tagID) {
var request = get_XmlHttp();
var Id = document.getElementById('Id').value;
var Value = document.getElementById('Value').value;
// create pairs index=value with data that must be sent to server
var the_data = 'Id='+Id+'&Value='+Value;
request.open("POST", php_file, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(the_data);
request.onreadystatechange = function() {
if (request.readyState == 4) {
document.getElementById(tagID).innerHTML = request.responseText;
}
}
}
The test.php is:
$Id = strip_tags($_POST['Id']); $Value = strip_tags($_POST['Value']); echo "{$Id}, {$Value}";
The problem is that when clicking on any value in the form only the first value is ever displayed. How do I get it to recognise all the different submit values?

When posting, only the last value of the same name will be changed.
See this post on using multiple name elements
What you are looking for is something like this where you have multiple button names.
If you need to loop through them, give them predictable names then loop through the names like:
Submit1
Submit2
Submit3
EDIT:
You are getting the element by getElementByID('Value')
This will get the first element with the ID value.
This may be a good way to go here

Related

FormData Ajax not posting data in PHP

Hope you can help me with my problem.
The problem is that i put my data in FormData but when i'm calling them in php file using echo there is no values and data existing and gives me error
an undefined variable
But when im using var_dump() or print_r() it show all the values. and also if i var_dump the files for the images it throws me also an error.
Here in html:
<form id="form" action="myurl.php" method="post" enctype="multipart/form-data" onsubmit="return false">
<input type="file" name="image" accept="image/*"/>
<input type="text" name="description"/>
<input type="submit" />
</form>
Here is my code in ajax:
function getName(key)
{
key = document.getElementsByName(key)[0];
return key;
}
function getId(key)
{
key = document.getElementById(key);
return key;
}
var url = getId('form').getAttribute('action');
var datas = new FormData();
var xhr = new XMLHttpRequest();
var image = getName('image').value.trim();
var description = getName('description').value.trim();
datas.append('file_image', image.files[0]);
datas.append('description', description);
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(datas);
xhr.onreadystatechange = function()
{
var OK = 4;
var DONE = 200;
if(xhr.readyState == 4 && xhr.status == DONE)
{
alert(xhr.responseText);
}
}
now in my myurl.php php file
var_dump($_POST);
var_dump($_FILES);
We don't actually using third party script like jQuery. We practice native javascript language.
Thank you.
You don't have to append the element manually to form data, create FormData from the form itself.
Give your form a name name="upload-image
<form id="form" action="myurl.php" name="upload-image" method="post" enctype="multipart/form-data">
<input type="file" name="image" accept="image/*"/>
<input type="text" name="description"/>
<input type="submit" />
</form>
In your Javascript
var form = document.forms.namedItem("upload-image");
var url = form['action'];
form.addEventListener('submit', function(ev) {
var oData = new FormData(form);
var oReq = new XMLHttpRequest();
oReq.open("POST", url, true);
oReq.onload = function(oEvent) {
if (oReq.status == 200) {
alert(oReq.responseText);
} else {
alert(oReq.status + " occurred when trying to upload your file.");
}
};
oReq.send(oData);
ev.preventDefault();
}, false);

Unable to fetch data from form to function

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.

how to check which button is clicked in php file with ajax call

I have a form post.php where the user inputs data and receivepost.php where the data entered is transferred through Ajax post. I want to achieve the following in the receivepost.php:
if (button save is pressed) {
save to database
} else if (button retrieve is pressed) {
retrieve from database
}
I tried using isset($_POST['submit']) on the reveivepost.php but it does not detect the button which is pressed. The Ajax post is working and all the data is available on the receivepost page. I have another solution that is to create 2 different PHP files and run them according to the button pressed but I think there is a better solution to it.
Here is my ajax call :
$("document").ready(function () {
$("#submit").click(function () {
var xmlhttp;
// test browsers
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// get the values of textboxes
var desc_text = $("#desc").val();
var speed_text = $("#speed").val();
var tarea_text = $("#tarea").val();
// variable to hold value of textboxes
var content = "desc=" + desc_text + "&speed=" + speed_text + "&tarea=" + tarea_text;
// open the request
xmlhttp.open("POST", "receivepost.php", true);
// set header
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// check xmlhttp state and status and display text in div
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('para').innerHTML = xmlhttp.responseText;
}
}
// send the content of the textboxes
xmlhttp.send(content);
});
});
Here is my post.php form:
<form id="myform">
<label for="description">Description:</label>
<input type="text" id="desc" name="desc" /><br/>
<label for="speed">Speed: </label>
<input type="text" id="speed" name="speed" /><br/>
<textarea id="tarea" cols="10" rows="10" name="tarea"></textarea><br/>
<input type="button" id="submit" name = "submit" value="Save">
<input type="button" id="retrieve" name="retrieve" value="Retrieve">
</form>
<div id="para"></div>
Try to add to the content an extra parameter called button-pressed which you can later use in receivepost.php as below:
if($_POST['button-pressed']=="save"){
//savetodb code
}
else if($_POST['button-pressed']=="retrieve"){
//retreivefromdb code
}
Perhaps you have two JavaScript functions, one on each button:
$("#submit").click(function () {
var content = "button-pressed=save" + "&desc=" + desc_text + "&speed=" + speed_text + "&tarea=" + tarea_text;
$("#retrieve").click(function () {
var content = "button-pressed=retrieve" + "&desc=" + desc_text + "&speed=" + speed_text + "&tarea=" + tarea_text;
Hope this helps?
<input type="button" id="submit" name ="submit" value="save" onClick="fnc(this.id)">
<input type="button" id="retrieve" name="retrieve" value="retrieve" onClick="fnc(this.id)">
<script type="text/javascript">
function fnc(myid) {
var val=document.getElementById(myid).value;
alert(val);
}
</script>

How do i pass a variable from a form through to a php page in an ajax script?

I have this form:
<form onsubmit="serverconnect('Div1', 'query.php'); return
false;"
Minimum Discount: <br />
<input type="radio" value="20%" name="discount" /> 20% <br />
<input type="radio" value="15%" name="discount" /> 15% <br />
<input type="radio" value="10%" name="discount" /> 10% <br />
<input type="radio" value="5%" name="discount" /> 5% <br />
<input type="submit" value="Refine Search" />
</form>
On submit, the form calls the following ajax script
<script language="javascript" type="text/javascript">
var xmlhttp = false;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
function serverconnect(divID, datalocation)
{
var1=$clickvalue;
if(xmlhttp)
{
var obj = document.getElementById(divID);
xmlhttp.open("GET", datalocation);
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 &&
xmlhttp.status == 200)
{
obj.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(null);
}
}
</script>
I need to get the form data through to my query.php page (which is what the ajax is outputtng) to modify its output, without using the jquery library.
So is there a way to pass the form data through the ajax function to the page that the function calls?
Yes you can pass form data using ajax. As you are using GET method only you have to embed your data with the page like this
<input type="radio" value="20%" name="discount" id="discount" /> 20% <br />
var obj = document.getElementById(divID);
var disc = document.getElementById("discount");
xmlhttp.open("GET", datalocation + "?disc="+disc);
and in query.php use $_GET['disc'] for getting get data.

radio button data to ajax

Hi i'm printing out a radio button list dynamically with php using the following code:
<form method="post">
<p>Name of list:
<label for="name"></label>
<input type="text" name="name" id="name">
</p>
<p>Name of item:
<input id="first_name" name="first_name" type="text" />
<br />
<?php echo $form;?>
<input name="myBtn" type="submit" value="Submit Data" onClick="javascript:ajax_post();"></form>
where $form is the variable in which the radio button list is saved.Now i need to pass the selected radio button to an another php file using an ajax function ajax_post().But since my form method is POST my ajax function gets overridden and doesnt get called.
heres my ajax function
function ajax_post(){
var hr = new XMLHttpRequest();
var id = '<?php echo $id; ?>';
var rd = '<?php echo $_POST['radio'];?>';
var url = "my_parse_file.php";
var fn = document.getElementById("first_name").value;
var nm = document.getElementById("name").value;
var vars = "todo="+fn+"&name="+nm+"&id="+id+"&rd="+rd;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(vars); // Actually execute the request
}
I need it to be POST because i want to extract what radio button i press and i also need the ajax function to work...any way around this?
You need to return false; from your function to avoid the form getting submitted the regular way.

Categories