Submit Values via POST to multiple PHP files - php

I have a form :
<form action="moods.php" method="post" id="geog">
Longitude: <input size="15" id="lonbox" name="lon" type="text" />
Latitude: <input size="15" id="latbox" name="lat" type="text" />
<input type="submit" />
</form>
I wish to submit the values of latitude and longitude to multiple .php files apart from moods.php at the same time using the single above form.
How can I do that?? please suggest some ways ..

why have the form submit to multiple pages, when you can have one single script include() the other scripts?
require('script1.php');
require('script2.php');
require('script3.php');

You could submit it to a file containing a cURL script that would handle multiple submissions
<form action="multi_submit.php" method="post" id="geog">
on multi_submit.php handle the form submission using cURL

If you really need to submit the values over multiple .php files, and the require option gave by dqhendricks does not solve it, why not to use several Ajax calls? One for each file.
You could have something like this:
<form onsubmit='sendSeveralPost()'>
... form fields
</form>
And the javascript function
function sendSeveralPost() {
var f1 = document.getElementById('field1');
var f2 = document.getElementById('field2');
var x = getXmlHttp();
var params = 'field1='+f1+'&field2='+f2;
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
x.setRequestHeader("Content-length", params.length);
x.setRequestHeader("Connection", "close");
var files = new Array();
files[0] = 'script1.php';
files[1] = 'script2.php';
files[2] = 'script3.php';
for (i=0;i<files.lenght;i++) {
var url = files[i];
x.open("POST", url, true);
x.onreadystatechange = function() {//Call a function when the state changes.
if(x.readyState == 4 && x.status == 200) {
alert(x.responseText);
}
}
x.send(params);
}
}
function getXmlHttp() {
var xmlHttp;
try { // Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
} catch (e) {
try { // Internet Explorer 6.0+
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e){
try { // Internet Explorer 5.5
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
alert("Your browser does not support AJAX!");
return false;
}
}
}
return xmlHttp;
}
Further explanations about the commands can be found at the article http://www.openjs.com/articles/ajax_xmlhttp_using_post.php, from where I took the inspiration for this example.
Hope this helps.
NamastĂȘ!

Related

Sending POST with javascript

What is wrong with this code? Trying to send data over POST w/ javascript to a PHP page but it isn't sending anything, nothing comes across in the headers $_POST contains nothing.
HTML:
<form method="POST" id="userSub" class="userSub">
<table>
<tr><td colspan="2">Sign In Here </td></tr>
<tr><td>Username:</td><td><input name="username" type="text" id="username" /></td></tr>
<tr><td>Password:</td><td><input name="pwd" type="text" id="pwd" /></td></tr>
<tr><td><input name="submit" type="submit" value="submit" id="submit" onclick="loginSub()" /></td></tr>
<tr><td colspan="2">Need a Username? Sign Up</td></tr>
</table>
</form>
Javascript:
function loginSub(){
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("rssnav2").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","PHP/login.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
}
PHP doesn't do anything special right now, just seeing if I can pass the post information to it:
<?php
echo "test";
$username=$_POST['username'];
echo $username;
?>
It is IS echoing that 'test' line to the correct so it is communicating w/ the PHP page. Also, I know that I still have the pwd input in "text" type and I know its probably a good idea to hash a password before sending it to the server.
Thanks for your help, everyone!
The xmlhttp doesn't actually have any knowledge of the <form>, so it won't send any data automatically.
You'll instead have to gather the <form>'s data yourself, format it as URL-encoded, and .send() it along with the request.
function loginSub(){
var user = document.getElementById('username');
var pass = document.getElementById('pwd');
var postData = [
encodeURIComponent(user.name) + '=' + encodeURIComponent(user.value),
encodeURIComponent(pass.name) + '=' + encodeURIComponent(pass.value)
].join('&');
// ...
xmlhttp.send(postData);
}
For more details, you may want to read through MDN's Using XMLHttpRequest, especially the sections on Using nothing but pure AJAX.
It includes a generalized solution for gathering <form> data in A little vanilla framework, which you could use with:
<form method="POST" action="PHP/login.php" onsubmit="AJAXSubmit(this); return false;">
Side note:
Your <form> is likely still submitting as well and may interrupt the Ajax request. You can prevent this by cancelling its onsubmit event:
<form method="POST" id="userSub" class="userSub" onsubmit="return false">
Also, there are more ways to submit a <form> than clicking the type="submit". For example, most browsers allow submitting by simply tapping Enter while typing in a type="text" or type="password". And, doing so won't typically imitate a click of the type="submit".
So, you'll want to at least consider moving the call out of the onclick and into the onsubmit:
<form method="POST" id="userSub" class="userSub" onsubmit="loginSub(); return false;">
You are not sending parameters in your XMLHttpRequest. Something like:
var params = "username=user&password=something";
xmlhttp.open("POST", "PHP/login.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
document.getElementById("rssnav2").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(params);
Try changing
xmlhttp.send();
to
xmlhttp.send('username='+document.getElementById('username').value);
Of course you will need to put in validation logic.
function loginSub()
{
var xmlhttp = false;
if(window.XMLHttpRequest)
{
if(typeof XMLHttpRequest != 'undefined')
{
try
{
return xmlhttp= new XMLHttpRequest();
}
catch(e)
{
return xmlhttp= false;
}
}
else if( window.ActiveXObject)
{
try
{
return xmlhttp= new ActiveXObject('Msxml2.XMLHTTP');
}
catch(e)
{
try
{
return xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
catch(e)
{
return xmlhttp = false;
}
}
}
}
var xmlhttp=false;
xmlhttp=createobject();
if(xmlhttp)
{
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById('rssnav2').innerHTML = xmlhttp.responseText;
}
}
parameter=username+'='+document.getElementById('usernname').value;
xmlhttp.open('POST','PHP/login.php',true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send(parameter);
}
}
this will solve your problem

Ajax / PHP updating DIV

I'm using the following to update a DIV called 'output'. This works fine with one exception, I would like echo entries to update the parent page.
<script type="text/javascript">
<!--
var divid = 'output';
var loadingmessage = '<img src="working.gif">';
function AJAX(){
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
return xmlHttp;
}
catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
return xmlHttp;
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
return xmlHttp;
}
catch (e){
alert("Your browser does not support AJAX!");
return false;
}
}
}
}
function formget(f, url) {
var poststr = getFormValues(f);
postData(url, poststr);
}
function postData(url, parameters){
var xmlHttp = AJAX();
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState > 0 && xmlHttp.readyState < 4){
document.getElementById(divid).innerHTML=loadingmessage;
}
if (xmlHttp.readyState == 4) {
document.getElementById(divid).innerHTML=xmlHttp.responseText;
}
}
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", parameters.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(parameters);
}
function getFormValues(fobj)
{
var str = "";
var valueArr = null;
var val = "";
var cmd = "";
for(var i = 0;i < fobj.elements.length;i++)
{
switch(fobj.elements[i].type)
{
case "select-one":
str += fobj.elements[i].name +
"=" + fobj.elements[i].options[fobj.elements[i].selectedIndex].value + "&amp;";
break;
}
}
str = str.substr(0,(str.length - 1));
return str;
}
//--></script>
This is called using :
<input type='button' name='Send' value='submit' onclick="javascript: formget(this.form, 'foo.php');">
The issue I have is foo.php runs a series of exec() commands, between each command is an echo statement that I would like to be displayed in the output div.
So it will do something like:
echo "archive files";
exec ("tar -cvf bar.tar bar.txt foo.txt");
echo "backing up /user";
exec ("tar -cvf /user.tar /user/*");
I would like the user to see the working.gif, but under it each echo statement from foo.php
Can that be done and how ?
Thanks
I can't say I've ever tried sending back chunks of data at separate times with a single AJAX request, so I'm not sure it's possible. What happens currently? Do you only get first echoed message, or do only get the entire response at the end?
Two things that I know will work:
Break your PHP script into multiple scripts and execute them in order with separate AJAX requests. This will only work if the separated scripts don't depend on each other or you find some other way to persist the state across the separated scripts.
Create an iframe and load the PHP script into it instead of using an AJAX request. Flushing the output of the PHP script should then work. (If you have ever used Wordpress, I believe they use this technique to show the progress of plugin updates.)

MySQL/PHP: Update MySQL with Ajax

I am a beginner and I am trying to learn how to add, delete, retrieve and update a database using PHP and Ajax.
At this time I have accomplished how to retrieve and delete so I am trying to update some values. For retrieving data, I just pass the selected ID I want, so I can retrieve the data. Same goes for delete, I just assign which ID I want to delete. Now to update there are more things going on, its where I cant find the solution.
This is my Form:
<form onsubmit="updateuser()">
ID Number: <input name="ud_id"><br>
First Name: <input type="text" name="ud_first"><br>
Last Name: <input type="text" name="ud_last"><br>
<input type="Submit" value="Update">
</form>
and this is my javascript:
function updateuser() {
var str = $('.ud_id').attr('value');
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtuser").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "ajaxupdate.php?q=" + str, true);
xmlhttp.send();
}
I think the problem comes because my form ajaxupdate.php file doesn't retrieve the First and Last name values from the form. It's like I am not passing them (?).
Here is my ajaxupdate.php file:
<?php include("connection.php");
$id=$_GET['ud_id'];
$first=$_GET['ud_first'];
$last=$_GET['ud_last'];
$query="UPDATE contacts SET first='$first', last='$last' WHERE id='$id'";
mysql_query($query);
mysql_close();
?>
What I'm I doing wrong so that I can update the value first and last of database for a specific ID ?
Try this code
<script type="text/javascript">
function updateuser() {
var ud_id = document.getElementById('ud_id').value;
var ud_first = document.getElementById('ud_first').value;
var ud_last = document.getElementById('ud_last').value;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtuser").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "ajaxupdate.php?ud_id=" + ud_id + "&ud_first="+ud_first+"&ud_last="+ud_last, true);
xmlhttp.send();
}
</script>
HTML
<form name="test">
ID Number: <input name="ud_id"><br>
First Name: <input type="text" name="ud_first"><br>
Last Name: <input type="text" name="ud_last"><br>
<input type="button" onClick="updateuser()" value="Update">
</form>
In your javascript, do this
function updateuser() {
var ud_id = $('input[name="ud_id"]').val();
var ud_first = $('input[name="ud_first"]').val();
var ud_last = $('input[name="ud_last"]').val();
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtuser").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "ajaxupdate.php?ud_id=" + ud_id + "&ud_first="+ud_first+"&ud_last="+ud_last, true);
xmlhttp.send();
}
If you want to use the updateuser() function on submit, then it must prevent the form from actually submitting. Make it return false, otherwise the form gets submitted by the browser before the function has time to execute.
The browser runs the function before submitting the form (that's how on submit works). If the function doesn't return false, then it interprets that as "everything is OK, you can safely submit the form". The form then gets submitted as usual.
In the mean time, the function initiates the asynchronous request. But since the browser has already submitted the form, now you're on a totally different page, thus the connection and the asynchronous request get disconnected and most likely ignored (unless of course the request made it before the page was changed, in which case both requests are processed).
As an alternative, you could execute the function without placing it in the on submit event. See sam_13's answer.
Check this it will work as expected
ud_id = document.getElementById('ud_id').value;
ud_first = document.getElementById('ud_first').value;
ud_last = document.getElementById('ud_last').value;
xmlhttp.open("GET", "ajaxupdate.php?ud_id=" + ud_id +"&ud_first=" +ud_first+ "ud_last="+ud_last, true);
<form onsubmit="updateuser()">
ID Number: <input name="ud_id" id="ud_id"><br>
First Name: <input type="text" name="ud_first" id="ud_first"><br>
Last Name: <input type="text" name="ud_last" id="ud_last"><br>
<input type="Submit" value="Update">
</form>
I came accross this example because i am also running into a similar issue. however I couldnt help but notice that you do not specify a method for your form and your AJAX is assuming it should use the GET method. just food for thought... cheers
This code is tested and works. I needed to do the same thing, update MySql with ajax and combining the above with a wider research I got this to work.
The php file is called ajaxupdate.php:
<?php
$id= $_GET['ud_id'];
$first= $_GET['ud_first'];
$last= $_GET['ud_last'];
require_once ('mysqli_connect.php'); //connection to the database
$sql = "UPDATE contacts SET FirstName ='$first', LastName='$last' WHERE id='$id'";
$result = mysqli_query($dbc,$sql);
mysqli_close($dbc);
?>
The Html file called anyNameYouWish.html:
<html>
<head>
</SCRIPT>
<script language="javascript" type="text/javascript">
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
function MsgBox (textstring) {
alert (textstring) }
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var ud_id = document.getElementById('ud_id').value;
var ud_first = document.getElementById('ud_first').value;
var ud_last = document.getElementById('ud_last').value;
var queryString = "?ud_id=" + ud_id + "&ud_first="+ud_first+"&ud_last="+ud_last;
ajaxRequest.open("GET", "ajaxupdate.php" + queryString + "&random=" + Math.random(), true);
ajaxRequest.send(null);
}
</script>
</head>
<body>
<form method="post" name="test" onsubmit="ajaxFunction()">
ID Number: <input id="ud_id" name="ud_id"><br>
First Name: <input id="ud_first" type="text" name="ud_first"><br>
Last Name: <input id="ud_last" type="text" name="ud_last"><br>
<input type="submit" value="Update">
</form>
</body>
</html>

Ajax PHP MYSQL on enter

I am using the below code to search a mysql database but cannot get the form to submit when the return key is pressed.
Does anybody have any ideas?
function ajaxFunction(){
var ajaxRequest;
{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var kw = document.getElementById('kw').value;
var division = document.getElementById('division').value;
var queryString = "?kw=" + kw + "&division=" + division;
ajaxRequest.open("GET", "search/jsearch.php" + queryString, true);
ajaxRequest.send(null);
}
Form code is:
<form name='myForm'>
Keywords<input type='text' id='kw' /> <br />
<br />
<select id='division'>
<option value='0' selected="selected">window & door</option>
<option value="1">window</option>
<option value="2">door</option>
</select>
<input type='button' onclick='ajaxFunction()' value='Query MySQL' />
</form>
Where is your event code for the form? Are you using an onclick instead of onsubmit? I don't think we have enough code/information to answer this, but from what you describe your first step to make sure you are using an onsubmit event for the form so you can fire off the xhr.
EDIT:
Then the answer to this problem: "...cannot get the form to submit when the return key is pressed", is use onsubmit instead of onclick. You also need to attach the event to the form instead of the button, and if possible refrain from using inline js.
http://en.wikipedia.org/wiki/Unobtrusive_JavaScript
onclick fires when you click the button. You are pressing return, not clicking the button.
As mentioned earlier, you should use onsubmit which fires when the form is submitted. You will need to return false, ie use onsubmit="ajaxFunction();return false;", to prevent the normal submission from occurring.

Ajax responds with empty string when triggered via form onsubmit in Firefox, but working fine in Internet Explorer

Ajax responds with an empty string when triggered via form onsubmit in Firefox, but it is working fine in Internet Explorer and Opera (works in Firefox if sent by a submit button instead of form onsubmit).
I am simply calling a php file with the ajax GET and the php file response with - echo $response = "something";. Then the response value is alerted. I am getting it work in IE but in Firefox the response is an empty string (checked by typeof()).
code is 4 files: index.php, ajax-connect.js, cbb.js, cbb.php
index.php
<html> <head> <script src="ajax-connect.js"></script> <script src="cbb.js"></script>
</head> <body>
<form name="condtactform1" method="get" action="" onSubmit="contactfunction()">
<input type="submit" name="hissubmit" id="hissubmit" value="submit"> </form>
</body> </html>
ajax-connect.php
/* Create a new XMLHttpRequest object to talk to the Web server */
var xmlHttp = false;
/*#cc_on #*/
/*#
if (#_jscript_version >= 5)
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
xmlHttp = false;
}
}
#end
#*/
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();
}
cbb.js
function contactfunction() {
var url = "cbb.php";
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = updatecontact1;
xmlHttp.send(null);
}
function updatecontact1() {
if (xmlHttp.readyState == 4) {
var responsae = xmlHttp.responseText;
alert(responsae);
}
}
cbb.php
<?php $response = "something"; echo $response; ?>
If i trigger ajax by submit button instead of the form submit then it works fine in firefox like:
<form name="condtactform1" method="get" action="">
<input type="submit" name="hissubmit" id="hissubmit" value="submit" onFocus="contactfunction()"> </form>
Any idea why it is doing this?
Thanks.
I think part of the problem is that you aren't stopping the normal action of the submit. That it is working at all is probably based on how the return values of the last function executed is handled, though its hard to tell. Try adding a "return false" to your contactFunction();
If that doesn't work, I'd invest some time in retrofitting it to use a javascript framework for the AJAX (jQuery, MooTools, Prototype, etc.) rather than going down the route of debugging the cross browser differences. A jQuery solution would look like:
<form name="condtactform1" method="get" action="cbb-full.php">
<input type="submit" name="hissubmit" id="hissubmit" value="submit">
</form>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
<script>
<script type="text/javascript">
$(function() {
$('#hissubmit').click( function() {
$.get( 'cbb.php', function(response) {
alert(response);
});
return false;
});
});
</script>
Note that the form ought to post to a url that will generate a full response if javascript isn't enabled.

Categories