AJAX request to a php file - php

I am having problems with a really basic request to a php file from AJAX. I am running all this stuff through XAMPP. What I'm trying to do with this code is to echo the name typed into the textbox once the submit button is clicked and the results to be posted in the div "results". I am doing this to try and weed out errors in another script and so far it hasn't gone too well.
<html>
<head>
<script type="text/javascript">
function go() {
var request;
if(window.XMLHttpRequest) {
request = new XMLHttpRequest();
}
else {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
var uname = document.getElementById("name").value;
request.onreadystatechange= function() {
if(request.readyState == 4) {
document.getElementById("result").innerHTML = response.Text;
}
}
url = "win.php?name="+uname;
request.open("GET", url, true);
request.send();
}
</script>
</head>
<body>
Name:<input type="textbox" name="jesus" id="name" />
<input type="button" value="Submit" onlick="go()" />
<div id ="result"> Result:</div>
</body>
</html>
<?php
$name = $_GET['name'];
echo $name;
?>

You don't have an object called response, you are looking for the responseText property on the request object.
document.getElementById("result").innerHTML = request.responseText;
Also:
avoid using globals
don't send your HTTP request before the target div exists, you run the risk of it still not existing when the response comes back
you probably should check that the HTTP status of the response is 200 (OK) as well as being finished (readyState 4).
Don't put raw user input in URLs, escape it with encodeURIComponent first

Use that
document.getElementById("result").innerHTML = response.responseText;

Related

I'm trying to learn the basic of ajax. I want to send a form data using post method to the server and get back a response text that's all

I know how to use the GET method but is hard to understand the POST method with a form.
I'm sure there is something wrong with the line request.send(); but I'm sorry I couldn't get it.
Also what If there is more than one field like I want to send name + email
My HTML code
<!DOCTYPE html>
<html>
<head>
<title>AJAX Demo 2</title>
</head>
<body>
<form action="demo2.php" method="post">
Email: <input type="email" name="email" required >
</form>
<button onclick="loadContent()">Load</button>
<div id="ServerContent">
<p></p>
</div>
<script>
function loadContent(email){
//Create request object
let request = new XMLHttpRequest();
let email = document.getElementsByName("eamil").values;
//Create event handler that specifies what should happen when server responds
request.onload = function(){
//Check HTTP status code
if(request.status == 200){
//Get data from server
let responseData = request.responseText;
//Add data to page
document.getElementById("ServerContent").innerHTML = responseData;
}
else
alert("Error communicating with server");
}
//Set up request with HTTP method and URL
request.open("POST", "demo2.php", true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//Send request
request.send();
}
</script>
</body>
</html>
My PHP code
<?php
//Get email string - need to filter input to reduce chances of SQL injection etc.
$emailString = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_URL);
if($emailString != ""){//email string exists
echo 'Hello ' . $emailString;//Output message with contents of query string
}
else{//Query string parameter 'email' cannot be found
echo 'Hello stranger';
}
var url = "url to your php file";
var xhr = new XMLHttpRequest();
xhr.open("POST", url);
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
console.log(xhr.responseText);
}};
var data = `{
"email": "youremailvariable",
"name": "yournamevariable"
}`;
xhr.send(data);
Try this way

How to create a button that clears my form

I am writing a program that gets information from forms using AJAX, and I was wondering if there was a way to make a button that clears the form and sort of resets the form. Right now if you press a button, the text won't disappear, but Im hoping to make a home button that would make the text disappear. I am just going to post my .html file because I think thats all we need. Let me know if there is more code you need. I tried making a reset button but it didn't seem to work.
<!DOCTYPE html>
<html>
<head>
<title>Assignment8</title>
<script src="ajax.js"></script>
<script>
function getXML() {
var xmlHttp = xmlHttpObjCreate();
if (!xmlHttp) {
alert("The browser doesn't support this action.");
return;
}
xmlHttp.onload = function() {
if (xmlHttp.status == 200) {
// Get XML Document
var xmlDoc = xmlHttp.responseXML;
// Variable for our output
var output = '';
// Build output by parsing XML
dinos = xmlDoc.getElementsByTagName('title');
for (i = 0; i < dinos.length; i++) {
output += dinos[i].childNodes[0].nodeValue + "<br>";
}
// Get div object
var divObj = document.getElementById('dinoXML');
// Set the div's innerHTML
divObj.innerHTML = output;
}
}
xmlHttp.open("GET", "dino.xml", true);
xmlHttp.overrideMimeType("text/xml")
xmlHttp.send();
}
function getJSON() {
var xmlHttp = xmlHttpObjCreate();
if (!xmlHttp) {
alert("The browser doesn't support this action.");
return;
}
xmlHttp.onload = function() {
if (xmlHttp.status == 200) {
// Get Response Text
var response = xmlHttp.responseText;
// Prints the JSON string
console.dir(response);
// Get div object
var divObj = document.getElementById('dinoJSON');
// We used JSON.parse to turn the JSON string into an object
var responseObject = JSON.parse(response);
// This is our object
console.dir(responseObject)
// We can use that object like so:
for (i in responseObject) {
divObj.innerHTML += "<p>"+responseObject[i].name + " lived during the " + responseObject[i].pet + "period.</p>";
}
}
}
xmlHttp.open("GET", "json.php", true);
xmlHttp.send();
}
</script>
</head>
<body>
<form>
<h3> Dinosaur Web Services </h3>
<div id="home"></div>
<button type="reset" value="Reset"> Home</button>
<div id="dinoJSON"></div>
<button type="button" onclick="getJSON();"> JSON Dinos</button>
<div id="dinoXML"></div>
<button type="button" onclick="getXML();"> XML Dinos</button>
</form>
</body>
</html>
Your reset-button should already do this, if its within the <form></form> or has the "form"-attribute, see here
You can either use the default reset button, if it is in between the form tag or you can use jquery to do this for you.
You just have to add an event on the click event of the home button and u can achieve what you want.
this is a reference which u can take
$(".reset").click(function() {
$(this).closest('form').find("input[type=text], input[type="password"], textarea").val("");
});
Add all other fields which u want to clear on click of the home button

show the JW player

I have page that has a text input and a button
the user must fill a URL which is referring to a playable media file(mp4) in the text field and click the button
when the button is clicked the a script is running and ajax is passing the url value to PHP file which do some verifications and send the response back
if every thing is ok it should replace the DIV tag with JW player and the user can play the media
I test the whole process by replacing the DIV tag with a plain text or image and it worked smoothly
and when I tried to replace it with the jw player component it is not showing any thing
I tested the jw by inserting it directly in the HTML code and it worked smoothly
here is the full index.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="/ajax4/jwplayer.js"></script>
<script type="text/javascript">jwplayer.key="RXVe0CXFsIS8pAar5ezgSLJqb9jfx7rDOBxkVw==";</script>
<script type="text/javascript"><!--
function get_XmlHttp() {
var xmlHttp = null;
if(window.XMLHttpRequest) { // for Forefox, IE7+, Opera, Safari, ...
xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject) { // for Internet Explorer 5 or 6
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(); // call the function for the XMLHttpRequest instance
// create pairs index=value with data that must be sent to server
var hiturl = document.getElementById('hit').value;
var the_data = 'hiturl='+hiturl;
request.open("POST", php_file, true); // set the request
// adds a header to tell the PHP script to recognize the data as is sent via POST
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(the_data); // calls the send() method with datas as parameter
// Check request status
// If the response is received completely, will be transferred to the HTML tag with tagID
request.onreadystatechange = function() {
if (request.readyState == 4) {
document.getElementById(tagID).innerHTML = request.responseText;
}
}
}
--></script>
</head>
<body>
<form action="test_form.php" method="post" name="form1" onsubmit="ajaxrequest('hitphp.php', 'myDiv'); return false;">
<label for="name" id="name_label">hit URL: </label>
<input type="text" name="hit" id="hit" size="100" />
<input type="submit" value="Enter hit UrL" />
</form>
<div id="myDiv"></div>
</body>
</html>
and the hitphp.php file
<?php
// if data are received via POST
if (isset($_POST['hiturl'])) {
// get data into variables, deleting the html tags
$hiturl = strip_tags($_POST['hiturl']);
// if the form fields are completed
if (true) {
if (true) {
echo'<div id="myElement">nnnnn.....</div><script type="text/javascript">
jwplayer("myElement").setup({
type:"mp4",
bufferlength: "60",
file: "mediaurl",
});
</script>';
}else{
echo 'sorry not a valid url';
}
}
else {
echo 'Fill in all form fields';
}
}
?>

Send POST data to PHP without using an HTML form?

Is there anyway to send post data to a php script other than having a form? (Not using GET of course).
I want javascript to reload the page after X seconds and post some data to the page at the same time. I could do it with GET but I would rather use POST, as it looks cleaner.
Thanks a lot.
EDIT: Would it be possible to do with PHP header? I'm sure it is better to use JQuery but for my current situation I could implement that a lot easier/faster : )
Cheers
I ended up doing it like so:
<script>
function mySubmit() {
var form = document.forms.myForm;
form.submit();
}
</script>
...
<body onLoad="mySubmit()";>
<form action="script.php?GET_Value=<?php echo $GET_var ?>" name="myForm" method="post">
<input type="hidden" name="POST_Value" value="<?php echo $POST_Var ?>">
</form>
</body>
Seems to work fine for me, but please say if there is anything wrong with it!
Thanks everyone.
As requested above, here is how you could dynamically add a hidden form and submit it when you want to refresh the page.
Somewhere in your HTML:
<div id="hidden_form_container" style="display:none;"></div>
And some Javascript:
function postRefreshPage () {
var theForm, newInput1, newInput2;
// Start by creating a <form>
theForm = document.createElement('form');
theForm.action = 'somepage.php';
theForm.method = 'post';
// Next create the <input>s in the form and give them names and values
newInput1 = document.createElement('input');
newInput1.type = 'hidden';
newInput1.name = 'input_1';
newInput1.value = 'value 1';
newInput2 = document.createElement('input');
newInput2.type = 'hidden';
newInput2.name = 'input_2';
newInput2.value = 'value 2';
// Now put everything together...
theForm.appendChild(newInput1);
theForm.appendChild(newInput2);
// ...and it to the DOM...
document.getElementById('hidden_form_container').appendChild(theForm);
// ...and submit it
theForm.submit();
}
This is equivalent to submitting this HTML form:
<form action="somepage.php" method="post">
<input type="hidden" name="input_1" value="value 1" />
<input type="hidden" name="input_2" value="value 2" />
</form>
You can use JQuery to post to a php page:
http://api.jquery.com/jQuery.post/
By jQuery:
$.ajax({
url: "yourphpscript.php",
type: "post",
data: json/array/whatever,
success: function(){ // trigger when request was successfull
window.location.href = 'somewhere'
},
error: anyFunction // when error happened
complete: otherFunction // when request is completed -no matter if the error or not
// callbacks are of course not mandatory
})
or simplest:
$.post( "yourphpscript.php", data, success_callback_as_above );
more on http://api.jquery.com/jQuery.ajax
Use the FormData API.
From the example there:
var formData = new FormData();
formData.append("username", "Groucho");
formData.append("accountnum", 123456);
var request = new XMLHttpRequest();
request.open("POST", "http://foo.com/submitform.php");
request.send(formData);
Form your own header, as such:
POST /submit.php HTTP/1.1
Host: localhost
User-Agent: Mozilla/4.0
Content-Length: 27
Content-Type: application/x-www-form-urlencoded
userId=admin&password=letmein
How about this:
function redirectWithPostData(strLocation, objData, strTarget)
{
var objForm = document.createElement('FORM');
objForm.method = 'post';
objForm.action = strLocation;
if (strTarget)
objForm.target = strTarget;
var strKey;
for (strKey in objData)
{
var objInput = document.createElement('INPUT');
objInput.type = 'hidden';
objInput.name = strKey;
objInput.value = objData[strKey];
objForm.appendChild(objInput);
}
document.body.appendChild(objForm);
objForm.submit();
if (strTarget)
document.body.removeChild(objForm);
}
use like this:
redirectWithPostData('page.aspx', {UserIDs: getMultiUserSelectedItems()},'_top');
You can send an xhr request with the data you want to post before reloading the page.
And reload the page only if the xhr request is finished.
So basically you would want to do a synchronous request.

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