Need to post form values to a remote script using Javascript

Hi,

I need to post form values to a PHP file located at other server. I want to use Javascript. I have done it with PHP CURL. I need to insert form values to mysql server located at myserver. I will ask client to include javascript in contact us file. If I use PHP for it then I can only install it to PHP based websites.

  1. Post form variables to a php file using javascript
  2. The original form should not be redirected to new PHP file but it should be like CURL call.

Here is the PHP function. I need same with Javascript.


function fetch_remote_file($url, $post_data=array())
{
    $post_body = '';
    if(!empty($post_data))
    {
        foreach($post_data as $key => $val)
        {
            $post_body .= '&'.urlencode($key).'='.urlencode($val);
        }
        $post_body = ltrim($post_body, '&');
    }
	//echo $post_data['fn'];
    //echo $post_body;
    if(function_exists("curl_init"))
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
        if(!empty($post_body))
        {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_body);
        }
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
     else if(function_exists("fsockopen"))
    {
        $url = @parse_url($url);
        if(!$url['host'])
        {
            return false;
        }
        if(!$url['port'])
        {
            $url['port'] = 80;
        }
        if(!$url['path'])
        {
            $url['path'] = "/";
        }
        if($url['query'])
        {
            $url['path'] .= "?{$url['query']}";
        }
        $fp = @fsockopen($url['host'], $url['port'], $error_no, $error, 10);
        @stream_set_timeout($fp, 10);
        if(!$fp)
        {
            return false;
        }
        $headers = array();
        if(!empty($post_body))
        {
            $headers[] = "POST {$url['path']} HTTP/1.0";
            $headers[] = "Content-Length: ".strlen($post_body);
            $headers[] = "Content-Type: application/x-www-form-urlencoded";
        }
        else
        {
            $headers[] = "GET {$url['path']} HTTP/1.0";
        }
        
        $headers[] = "Host: {$url['host']}";
        $headers[] = "Connection: Close";
        $headers[] = "\\r\
";
        
        if(!empty($post_body))
        {
            $headers[] = $post_body;
        }
        
        $headers = implode("\\r\
", $headers);    
        if(!@fwrite($fp, $headers))
        {
            return false;
        }
        while(!feof($fp))
        {
            $data .= fgets($fp, 12800);
        }
        fclose($fp);
        $data = explode("\\r\
\\r\
", $data, 2);
        return $data[1];
    }
    else if(empty($post_data))
    {
        return @implode("", @file($url));
    }
    else
    {
        return false;
    }
}  
echo fetch_remote_file('http://myserver.com/psi/ipinfo.php?ip='.$_SERVER['REMOTE_ADDR'], $_REQUEST);

ipinfo.php will get the posted variables and insert into mysql db. The form should not be submitted to ipinfo.php. The control should be there in the same javascript calling file.

If someone please help me.

Javascript is subject to “same domain” restrictions.

So you could have the javascript submit to a PHP file on the same server and have that file submit to the remote site.

I think using AJAX (which is still JS) it can be possible. Call your own PHP script file from AJAX which file calls the REMOTE server using cURL or fsockopen or whatever to send the POST.

I tried ajax but it is not showing anything when I specify complete URL


xmlhttp.open("GET","http://www.people-sourceinc.com/psi/a.php?fname=a&lname=a",true);

I need this to be successful. The following code is successful


xmlhttp.open("GET","a.php?fname=Henry&lname=Ford",true);

I want to specify URL of the file located on other server. Google Adsense uses javascript and sends values to remote server.

I had the same issue a while back. I needed to use JS to submit data using GET to another url, because I did not have sufficient time to properly come up with an AJAX to do this I did it using an <img> like so.

Let say you need to submit data to www.example.com

you could do something like this:

<img src=“http://www.example.com?fname=john&lname=smith” width=“1” height=“1” />

you could also dynamically populate the query string fname and lname using JS like so:

let’s say a <form> is submitted, you then use js to grab the values append to the img query string like so:


if (document.getElementById("submit").value=="Y")
        {
var fname=document.getElementById("fname").value;
var lname=document.getElementById("lname").value;

document.write('<img src="http://www.example.com?fname='+fname+'&lname='+lname+'" />')

}

HTH

Thanks. It is redirecting but in Fire Fox I am getting the status “Transferring Data” and it never ends like an infinite loop. I am posting the values to a file located at remote server and I am just printing the fname and lname but it never ends and does not show the values.

Here is the code: -


<html>
<head>
<script type="text/javascript">
function send_values(){	
	var fname=document.getElementById("fname").value;
	var lname=document.getElementById("lname").value;
			//document.write('<img src="http://www.example.com?fname='+fname+'&lname='+lname+'" />');
			document.write('<img src="http://people-sourceinc.com/psi/fetch.php?fname='+fname+'&lname='+lname+'" />');
	return true;
}
</script>
</head>
<body>
<form action="" method="post" name='frm' onsubmit="send_values()">
<input type="text" name="fname" id='fname' value="">
<input type="text" name="lname"  id='lname'  value="">
<input type="button" value="Submit" onclick="send_values();"/>
</form>
</body>
</html>

Please visit http://www.people-sourceinc.com/psi/1.php Enter some data and hit submit button.

In fetch.php I have two lines


echo $_REQUEST['fname'];
echo $_REQUEST['lname'];

What kind of image (i.e. MIME type) is fetch.php returning?

Its type is text/html.

If you still want to go for the way of using image (IMG tag) then you should have some image output in your remote script with the image headers (image/png) otherwise you will have that loading issue. But I would still suggest you to go for the way what I have proposed earlier thread.

  • When the form submit button is pressed then call your own file (the file located in your own server/domain i.e. callremote.php) via AJAX.
  • Write the script in that file (callremote.php) to call the page of another remove server using cURL.

In this way you can grab the output returned from the remote server and use it for whatever purpose in your calling script.

Thanks.

Actually, I have a script and I want to install it on client websites. If I use PHP then I could only install on clients having PHP websites But I want to install it on any website so Javascript is a way. It should be browser dependent not server dependent script.

Here is what I want to accomplish: -

  1. Client installs this script on contact us page
  2. Visitor enters the information and that information is saved into the database on a remote server we have.
  3. Then visitor form values will be saved to client database thats not related with us.

What I need is that (a) Client side script should call a middle file(located on remote server, my server) (b) Middle file is PHP based and it CURLs another file to save and that file has the code to insert data into the DB. Middle file and database insertion files are working properly and If I use PHP on client website then it is working fine. But it is only for PHP based websites. To go for all websites I need javascript. Javascript should call the middle file.

IMPORTANT!
Visitor should NOT know that his values are saved to some other website. He should be remain on the same contact us page and the values should be saved into our remote database.

Hope you understand my point.

Now what should I write into the middle file to avoid this infinite loading. I have used

header(“Content-Type: image/png”);

in the first line but it is still in the loading state and never comes back.

Hello Khan, if you want it to come back just do this:



//here we submitting the data using $_GET via img 
document.write('<img src="http://people-sourceinc.com/psi/fetch.php?fname='+fname+'&lname='+lname+'" />');

//lets set 700 secons for above to execute, then redirect back to http://www.sitetocomebackto.com

setTimeout("location.href = 'http://www.sitetocomebackto.com';",700);



Rajung and other folks are right that the best way is AJAX and JS. There sure is an AJAX/JS one can write to submit data to another url Independent of server side and I’m sure folks here have done it before, but these dogs :slight_smile: just too lazy to write something :slight_smile: So I hope somone can show the proper way, but mean time do the above.

PS: the above will work on IE, CROME and Mozz (from v 4.0).

HTH

One more thing Khan, in fetch.php you ought to have this:


echo $_GET['fname'];
echo $_GET['lname']; 

$_REQUEST is the old way of doing things. As of php v5 it’s recommended u use $_GET or $_POST.

Thank you very much HTH.

My main problem has been solved. Now the I can post values to fetch.php, insert the data to remote DB and then comes back to original file and save the data in original file to local database.


setTimeout("location.href='http://people-sourceinc.com/psi/1.php?fname="+fname+"&lname="+lname+"'",3000);

You see values of fname and lname in the Querystring. The visitor now can see the values. And if the data in the querystring is above 2084 bytes(GET) then it will not be saved. I want to hide these values and want to use document.form.submit(); like


setTimeout("document.form.submit()",3000);//This is not working, I have called function but that also does not work

So that user could not see the values in querystring. Is there a way to do it?

thank you for helping me.

Now I can post fname and email using javascript and fetch.php calls actaul file and data is input in the DB at remote server. Here is the javascript test code

I will put this script on customers contact us page just before the </body>


<script language="javascript">
function abc(){
			
		fname=document.getElementById('fname').value;//single quotes are must to  work in FF, I have tried double quotes but its not working in FF
		lname=document.getElementById('lname').value;
		
		if(fname !="" && lname !=""){		
		document.write("<img src='http://people-sourceinc.com/psi/fetch.php?fname=fname&lname=lname'/>");					
		setTimeout("location.href='http://www.people-sourceinc.com/psi/1.php?auth=1&fname="+fname+"'",4000); 			
		}
}
window.onload = function(){
           var subButton = document.getElementById("submit");
            subButton.onclick = function(){abc();}
        };
</script>
 

Here is the form: -


<form method="post" name="frm" id='frm1'>
	<input type="text" name="fname" id='fname' value="">
	<input type="text" name="lname"  id='lname'  value="">
	<input type="submit" value="Submit" id="submit"/>
</form>

Middle file is Curl file and third file is my database file where I insert values in DB. Customer does not know about the insertion at remote server.
I have set 4 sec is this correct or I should reduce this?

Thank you all for helping me.