I am trying to send two pieces of info to a php.
1-) tent = zuzu
2-) zart = gagi
target php simply echoes what I send so that I can check if it's working. This is the javascript:
function boka ()
{
var mesparam = "tent=zuzu&zart=gagi";
if (window.XMLHttpRequest){xmlhttp=new XMLHttpRequest();}
else {xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) {document.getElementById("response").innerHTML=xmlhttp.responseText;} }
xmlhttp.open("POST","/mysite/oxifa/oxifat.php?tent=zuzu&zart=gagi",true);
//xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//xmlhttp.setRequestHeader("Content-length", mesparam.length);
//xmlHttp.setRequestHeader("Connection", "close");
xmlhttp.send(mesparam);
}
This is oxifat.php that recieves the request:
<?php
echo " sign1 <br>";
echo next($_POST);
echo next($_POST);
echo next($_POST);
echo next($_POST);
echo next($_POST);
echo $_POST['tent'];
echo $_POST['zart'];
echo $_REQUEST['tent'];
echo $_REQUEST['zart'];
echo "<br> sign2";
?>
As you can see I've included all sorts of things to echo out whatever is in $_POST but apparently there is nothing there and this is the response I get:
sign1
Notice: Undefined index: tent in C:\wamp\www\mysite\oxifa/oxifat.php on line 16
Notice: Undefined index: zart in C:\wamp\www\mysite\oxifa/oxifat.php on line 17
Notice: Undefined index: tent in C:\wamp\www\mysite\oxifa/oxifat.php on line 18
Notice: Undefined index: zart in C:\wamp\www\mysite\oxifa/oxifat.php on line 19
sign2
three lines about the "setRequestHeader" are in comment status. If I include them, I don't even get sign1. No response. What I figure out from this is everything is OK but I don't seem to understand how to use the post method to pass data to php. How do I do this? I have read everything on the net. I only do not know what "setRequestHeader" is for. One more thing: If I put ?tent=zuzu&zart=gagi at the end of target URL, $_REQUEST thing works. But that's GET and not what I'm trying to do. What is the $_POST's deal?
Could you please try to invoke following code
function getXMLObject() {
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");// For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");// For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false;// No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();//For Mozilla, Opera Browsers
}
return xmlHttp;// Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject();//xmlhttp holds the ajax object
//use this method for asynchronous communication
function doRequest(params, callback) {
if (xmlhttp) {
xmlhttp.open("POST", "your_script.php?" + params, true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
callback(xmlhttp.responseText);
}
else {
alert("Error retrieving information (status = " + xmlhttp.status + ")\n" + response);
}
}
};
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(null);
}
}
and in your PHP script first thing off write
print_r($_POST);
You are passing in the parameters with the URL which is for GET, not the right way for POST.
See: http://www.openjs.com/articles/ajax_xmlhttp_using_post.php
Try taking the parameters off in the request here:
xmlhttp.open("POST","/mysite/oxifa/oxifat.php?tent=zuzu&zart=gagi",true);
And then uncommenting these:
//xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//xmlhttp.setRequestHeader("Content-length", mesparam.length);
//xmlHttp.setRequestHeader("Connection", "close");
You need to uncomment those 2 lines, otherwise you the php $_POST is not going to pick it up. also, as stonemonkey77 answered, you are also passing the parameters in the get url.
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", mesparam.length);
Related
my problem is I am not sure how to call my php function from JS. I am trying to learn xmlhttprequest but something seems to be wrong with my code:
HTML:
<input type="button" id="btn" value="Click">
JS:
window.onload = initForms;
function initForms(){
document.getElementById("btn").onclick = doSomething;
}
function doSomething(){
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
// response
}
}
try {
xmlhttp.open("GET", "test.php", true);
xmlhttp.send();
} catch (e) {
alert(e);
}
}
PHP:
<?php
echo "Echo!";
EDIT: My question is "Echo" doesn't appear, so test.php doesn't seem to be called?! Why not?
EDIT: In the Firefox console i get the following error: "XML Parsing Error: no root element found". Not sure what to make of it (yes, I googled it..)
"// Response, you have to actually do something with the response, such as console.log(xmlhttp.response);"
console.log is worthless, especially if you are wanting to do something with the data.
getElementById("idName").innerHTML = xmlhttp.response;
Is more likely what the OP is looking for.
I would like to transfer a large amount of text to the server using AJAX. I would like to attach this text using the POST method, but I get the following error:
request failed: URI too long (longer than 8190)
My javascript code:
function loadXMLDoc(data) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "http://www.mydomain.com/test2.php?blob=" + data, true);
xmlhttp.send();
}
My php code:
$dataraw = $_GET["blob"];
file_put_contents('/path/to/my/file/newfile.txt', $dataraw);
echo 'file saved';
You should change this
xmlhttp.open("POST","http://www.mydomain.com/test2.php?blob=" + data,true);
xmlhttp.send();
to this:
xmlhttp.open("POST", "http://www.mydomain.com/test2.php", true);
var payload = "blob=" + data;
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.setRequestHeader("Content-length", payload.length);
xmlhttp.send(payload);
In POST, parameters should go in the body of the message, not the URL.
At the same time, you should expect the parameters on the server-side in $_POST - that's where the body parameter will end up in in PHP.
You don't add post-data to the URL. Please check this link to find an example of a post-request:
http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");
I have an input field for a concept and when the user fills it out, he has to then check if the concept exists. So I made a check button, which checks a database using ajax and JavaScript to see if the concept exists. My problem is when using ajax and JavaScript I get this exception:
unexpected end of input
JS :
var concept = document.getElementById('acConceptName').value;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
var isexisted = JSON.parse(xmlhttp.responseText);
if(isexisted[0]==true){
var errorMessage = document.getElementById('acSuggesConcepts');
var p = document.createElement('p');
p.innerHTML="this concept is already existed";
errorMessage.appendChild(p);
errorMessage.style.display="block";
}
}
}
xmlhttp.open("GET","http://localhost/Mar7ba/Ontology/isExistedConcept/"+concept+"/TRUE",true);
xmlhttp.send();
What is the exception and how can I solve it ?
PHP : function to check database and I always return true in it
public function isExistedConcept($concpetName,$Ajax){
if($Ajax==true){
$results=true
$d=array($results);
return json_encode($d);
}
}
Demo: http://jsfiddle.net/Wiliam_Kinaan/s7Srx/2/
After looking at the code for a while, one thing that might be a suspect is your PHP.
Your function in php ends with a return command. What the AJAX call is actually waiting for is some data to be sent back. The return command simply passes that value back to the entity that originally called the function.
Try alter your function to echo the result as opposed to returning it. Save your return value for when you need the result to go into another PHP function, not when you are returning data to the client.
I only put this return command here for readability.
public function isExistedConcept($concpetName,$Ajax){
if($Ajax==true){
$results=true
$d=array($results);
echo json_encode($d);
}
return;
}
Try this:
public function isExistedConcept($concpetName,$Ajax) {
if( $Ajax) return "1";
}
// This is a simplified version of what you're doing, but it returns "1" instead of "[true]"
// Now for the JS:
if( xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var isexisted = xmlhttp.responseText == "1";
if( isexisted) {...}
If that doesn't work, try adding alert(xmlhttp.responseText) and see if you're getting anything other than what should be there.
try this :
var concept = document.getElementById('acConceptName').value;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://localhost/Mar7ba/Ontology/isExistedConcept/"+concept+"/TRUE",true);
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4){
if(xmlhttp.status==200){
var isexisted = JSON.parse(xmlhttp.responseText);
if(isexisted[0]==true){
var errorMessage = document.getElementById('acSuggesConcepts');
var p = document.createElement('p');
p.innerHTML="this concept is already existed";
errorMessage.appendChild(p);
errorMessage.style.display="block";
}
else{
console.log('error');
}
}
}
}
xmlhttp.send(null);
I am fluent with HTML, and mostly PHP.
I can do the scanning part with PHP.. I'm just not sure how to call a function in PHP with JavaScript, because I don't know JavaScript.
My PHP code will connect to my MySQL database and see if the text currently in the textbox (Not clicked enter yet, still typing) is in the database..
Do you know how to do this, or at least know a link that tells you how to do it?
This sounds like a problem for jQuery. I'd give you a long-winded example, but there are many people that would give you a much better one: like this guy.
Consider using jQuery in conjunction with jQuery UI, specifically something called autocomplete. I'm fairly certain it does what you're wanting, and it's completely themable for your site.
I see everybody likes jQuery so much, wow!
I'd tell you just need some very basic Ajax script to call your PHP script and receive the response.
Here's the simple Javascript function (actually two):
function getXMLObject() {
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");// For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");// For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false;// No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();//For Mozilla, Opera Browsers
}
return xmlHttp;// Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject();//xmlhttp holds the ajax object
//use this method for asynchronous communication
function doRequest(scriptAddressWithParams, callback) {
if (xmlhttp) {
xmlhttp.open("POST", scriptAddressWithParams, true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
callback(xmlhttp.responseText);
}
else {
alert("Error retrieving information (status = " + xmlhttp.status + ")\n" + response);
}
}
};
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(null);
}
}
and here's an example of usage:
<input type="text" onchange="doRequest('myphpscript.php?checkvalue='+this.value, function (returnedText) { alert(returnedText);});"/>
I have the below code, which was previously working fine:
var xmlHttp
var layername
var url
function update(layer, url) {
var xmlHttp=GetXmlHttpObject(); //you have this defined elsewhere
if(xmlHttp==null) {
alert("Your browser is not supported?");
}
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
document.getElementById(layer).innerHTML=xmlHttp.responseText;
} else if (xmlHttp.readyState==1 || xmlHttp.readyState=="loading") {
document.getElementById(layer).innerHTML="loading";
}
//etc
}
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function updateByPk(layer, pk) {
url = "get_auction.php?cmd=GetAuctionData&pk="+pk+"&sid="+Math.random();
update(layer, url);
}
function updateByQuery(layer, query) {
url = "get_records.php?cmd=GetRecordSet&query="+query+"&sid="+Math.random();
update(layer, url);
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
xmlHttp=new XMLHttpRequest();
}catch (e)
{
try
{
xmlHttp =new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
return xmlHttp;
}
function makewindows(){
child1 = window.open ("about:blank");
var phpstring = <?php $out = htmlspecialchars(json_encode($row2['ARTICLE_DESC']), ENT_QUOTES); echo("'$out'"); ?>;
child1.document.write(phpstring);
//child1.document.write("<?php echo htmlspecialchars(json_encode($row2['ARTICLE_DESC']), ENT_QUOTES); ?>");
child1.document.close();
}
The part that is commeneted out was working fine in a previus version, in that javascript was replacing row2['ARTICLE_DESC'], a php variable with the contents of the variable. This javascript file is included from a script tag in a php file, and always worked fine. I have changed something recently however, I am not sure what the specific thing was, butnow I get these errors, from firebug:
function makewindows(){
child1 = window.open ("about:blank");
child1.document.write("<br />
<b>Notice</b>: Undefined variable: row2 in <b>C:\Programme\EasyPHP 2.0b1\www\records4\fetchlayers.js</b> on line <b>57</b><br />
null");
child1.document.close();
}
unterminated string literal on line 57 and the updateByQuery is not defined.
I have no idea why I get either of those errors, and why updateByPk does not throw an error. I am even more confused as to what article_Desc is being expanded to and how. This happens on the index.php, which has a link to call updateByQuery, which would load a section via ajax which would have a link to updateByPk, which would display the final section, which would have a link to makewindows(), where article_Desc would relate to the relevant $pk
This was all working fine, and I can not find out why it no longer is.
would it help if I were to paste the php files somewhere?
edit.
i do not understand why this is happening, but have tried to modified the function so it takes a paramter.
function makewindows(html){
child1 = window.open ("about:blank");
child1.document.write(html);
child1.document.close();
}
in conjunction with thse two snippets of php
$html = json_encode(htmlspecialchars($row2['ARTICLE_DESC']));
and
<a href='#' onclick='makewindows(/"".$html."/"); return false;'>Click for full description </a></p>
Everything indicates the problem is in your PHP file. The notice you are getting is from PHP and not from JavaScript as you may be assuming.
<b>Notice</b>: Undefined variable: row2 in <b>C:\Programme\EasyPHP 2.0b1\www\records4\fetchlayers.js</b> on line <b>57</b><br />
null");
So the problem is in here:
<?php $out = htmlspecialchars(json_encode($row2['ARTICLE_DESC']), ENT_QUOTES); echo("'$out'"); ?>;
The $row2 array is not defined, so $row2['ARTICLE_DESC'] doesn't exist. You should verify from where it should come from because I couldn't find it in the code you provided.