0

Before I satart, allow me to explain a situation.

  1. I have an html(say A.html) page where I get information from a form. I send the data to a php page (say B.php).

  2. B.php processes the form and echo a string on screen.

  3. A javascript page (Say C.js) needs to send an HTTP request to B.php and read what has been echoed.

Is such a thing even possible? I searched a lot and no explanation.

3
  • Please read up about AJAX Commented Jan 18, 2015 at 6:43
  • 1
    What you want is probably possible, but it sounds like an x/y problem, one page accessing the result of user action on another page etc. Are you sure you're not just looking for ajax to submit the form and return the result in the background. Commented Jan 18, 2015 at 6:43
  • Sounds like you want to make an ajax request? Commented Jan 18, 2015 at 6:43

1 Answer 1

1

You should use AJAX.

It concludes 3 steps :

  1. Create XMLHttpRequest Object
  2. Set onreadystatechange function
  3. Post data via JS

File A.html:

<html>
	<input id="text" type="text" value="Hello"/>
	<input type="button" value="getResponse" onclick="getResponse();"/>
	<script>
	var xmlhttp;
	//Create XMLHttpRequest Object
	if (window.XMLHttpRequest)
	{// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	}
	else
	{// code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	//this function will be triggered after "xmlhttp.send" finished
	xmlhttp.onreadystatechange=function()
	{
		//readyState==4 means success, and status==200 means 'OK'
		if (xmlhttp.readyState==4 && xmlhttp.status==200)
		{
			alert(xmlhttp.responseText);
		}
	}
	// send post data via your web element
	function getResponse(){
		var text = document.getElementById("text").value;
		//send data and get response
		xmlhttp.open("POST","b.php",true);
		xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
		xmlhttp.send("text="+text);
	}
	</script>
</html>

And the file b.php:

<?php 
$text = $_POST['text'];
echo "The length of your text $text is ".strlen($text);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot, brilliant ! . However if I change 'b.php' to a www URL , no response is generated ! Why?
new url should be at the same domain(or IP) with your current page(a.html), because cross-domain visiting is not allowed and unsafety. Just use relative address in the page path parameter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.