0

Hi I'm trying to pass a variable named url from javascript to a php function called parse all within the same page, Here is my following attempt but it renders nothing. I'm also trying to innerthml the function parse as well. What I'm I doing wrong? Note:the function parse is cut out completely for sake of simplicity, It actually does more not just echo a variable, it echos more html.

here is my AJAX REQUEST inside a javascript script inside a php script.

"<script type=\"text/javascript\">\n".
 "\n".
 "// create and return an  XMLHttpRequest object\n".
 "function createRequest() {\n".
 "    var ajaxRequest;  // the xmlrequest object\n".
 "    try{\n".
 "     // Opera 8.0+, Firefox, Safari\n".
 "  ajaxRequest = new XMLHttpRequest();\n". 
 "    } catch (e){\n".
 "     // Internet Explorer Browsers\n". 
 "  try{\n".
 "      ajaxRequest = new ActiveXObject(\"Msxml2.XMLHTTP\");\n".
 "  } catch (e) {\n". 
 "      try{\n".
 "      ajaxRequest = new ActiveXObject(\"Microsoft.XMLHTTP\");\n".
 "      } catch (e){\n".
 "         // Something went wrong\n".
 "      alert(\"Your browser broke!\");\n". 
 "      return false;\n".
 "      }\n". 
 "  }\n". 
 "    }\n".
 "    return ajaxRequest;\n".
"} // end of createRequest\n".

Here is my actual javascript, and the variable url that I want to pass and the innerhtml of the function parse

 "var spellcheck =  function(data){\n".
 "    var found=false;var url='';\n". 
 "    var text=data[0];\n".
 "      if(text!=document.getElementById('spellcheckinput').value)return;\n".
 "      for(i=0;i<data[1].length;i++){if(text.toLowerCase()==data[1][i].toLowerCase()){found=true;url='http://en.wikipedia.org/wiki/'+text;document.getElementById('spellcheckresult').innerHTML='<b style=\"color:green\">Correct</b> - <a target=\"_top\" href=\"'+url+'\">link</a>';}}\n".
 "      if(!found)\n".
 "      document.getElementById('spellcheckresult').innerHTML='<b style=\"color:red\">Incorrect</b>';};\n".
 "      var getjs=   function(value){\n".
 "      if(!value)return;".
 " var url='http://en.wikipedia.org/w/api.php?action=opensearch&search='+value+'&format=json&callback=spellcheck';".  // this is the variable I want to pass
 "document.getElementById('spellcheckresult').innerHTML='Checking ...';".
 "var elem=document.createElement('script');".
 "elem.setAttribute('src',url);".
 "elem.setAttribute('type','text/javascript');".
 "document.getElementsByTagName('head')[0].appendChild(elem);};\n".
 "document.getElementById('resultdiv').innerHTML='" . parse() . "';\n".  //here wanting to innerhtml my php function 

Here is my unsuccessful ajax JavaScript variable passing to my php function down below

 " var requestone = createRequest();"
        "var variabletosend = url;"
        "var vars = "deletenode=" + encodeURIComponent(variabletosend);"
           "requestone.open("POST", "parse()", true);"
           "requestone.setRequestHeader("Content-type", "application/x-www-form-urlencoded");"
           "requestone.onreadystatechange = function(){"
           "handleRequest(requestone);"
           "}"
          "requestone.send(vars);"


 "</script>\n".
 "\n".
 "<form action=\"#\" method=\"get\" onsubmit=\"return false\">\n".
 "<p>Enter a species here : <input id=\"spellcheckinput\" onkeyup=\"getjs (this.value);\" type=\"text\"> <span id=\"spellcheckresult\"></span></p>\n".
 "</form>\n".
 "<div id=resultdiv></div>".
 "</body>\n". 
 "</html>\n". 
 "\n";

 function parse($url){
 print $url;
 }
 ?>
3
  • added function parse note Commented May 26, 2013 at 1:00
  • 3
    Why is your javascript inside a PHP string? Is it being echoed? Why not just save the script in a .js file an reference it from your HTML document? Commented May 26, 2013 at 1:04
  • @PhpMyCoder your right, sorry for the formatting. Commented May 26, 2013 at 1:06

1 Answer 1

0

Mhh, your ajax call is wrong. You cannot call a php function with AJAX. You can call a php page, whitch has a php function. So you need to call your page with your param. If you detect the param, then execute parse() , if not, echo the javascript code.

Assuming your code is in a page called "parser.php", here is a code that should work :

<?php
//We check if we have the param within the page call
$theDeletenode = false;
if(isset($_POST['deletenode']))
    $theDeletenode = $_POST['deletenode'];

if($theDeletenode)
{
    //The param 'deletenode' is given, so we juste have to call the php function "parse", to return the value
    parse($theDeletenode);
}else
{
    // No parametre, so we echo the javascript, and the form (without the quote and \n, it's much better)
?>
<html><head>
<script type="text/javascript">
 // create and return an  XMLHttpRequest object
 function createRequest() {
    var ajaxRequest;  // the xmlrequest object
   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;
                }
            }
        }
    return ajaxRequest;
}; // end of createRequest

var spellcheck =  function(data){
    var found=false;var url=''; 
    var text=data[0];
   if(text!=document.getElementById('spellcheckinput').value) return;
      for(i=0;i<data[1].length;i++)
          {
          if(text.toLowerCase()==data[1][i].toLowerCase())
              {found=true;
              url='http://en.wikipedia.org/wiki/'+text;document.getElementById('spellcheckresult').innerHTML='<b style=\"color:green\">Correct</b> - <a target=\"_top\" href=\"'+url+'\">link</a>';
              }
          }
      if(!found)
        document.getElementById('spellcheckresult').innerHTML='<b style=\"color:red\">Incorrect</b>';
        };


var requestone = createRequest();

var getjs=   function(value)
{
    if(!value) return;
    var url='http://en.wikipedia.org/w/api.php?action=opensearch&search='+value+'&format=json&callback=spellcheck'; // this is the variable I want to pass
    document.getElementById('spellcheckresult').innerHTML='Checking ...';
    var elem=document.createElement('script');
    elem.setAttribute('src',url);
    elem.setAttribute('type','text/javascript');
    document.getElementsByTagName('head')[0].appendChild(elem);

    // Ajax call to this page, this time with the 'deletenode' parameter
    var vars = "deletenode=" + encodeURIComponent(url);
    requestone.open("POST", "parser.php", true); // parser.php : the name of this current page
    requestone.onreadystatechange = handleRequest;  // function to handle the response
    requestone.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    requestone.send(vars);

};      

  function handleRequest()
  {
    //here we handle the php page response by echoing de result of the php page (normally the result of the parse function) 
    try{
        if(requestone.readyState == 4 && requestone.status == 200)
          document.getElementById('resultdiv').innerHTML= requestone.responseText;
    } catch (e) {
        //Wrong server answer...
    }
  }; 
</script>
</head>
<body>

<form action="#" method="get" onsubmit="return false">
<p>Enter a species here : <input id="spellcheckinput" onkeyup="getjs (this.value);" type="text"> <span id="spellcheckresult"></span></p>
</form>
<div id=resultdiv></div>
</body>
</html>

<?php 
// end of the javascript+form echo
}


function parse($url){
// this function is only called when the POST param is given
 print $url;
 }

?>
3
  • Hey CrtlX I entered this but I literally just get the php function spit out from the get go and the javascript and php arent talking to each other, here is what I get Commented May 30, 2013 at 3:58
  • Enter a species here : [text box] -link find('table.infobox'); foreach($html->find('img') as $element) { $image[]= $element; } Print $image[1]; $data = array(); foreach($table[0]->find('tr') as $row) { $td = $row->find('> td'); if (count($td) == 2) { $name = $td[0]->innertext; $td = $td[1]->find('a'); $text = $td[0]->innertext; $data[$name] = $text; } } print ""; foreach($data as $value => $before ) { print ""; } print " $value $before "; } ?> Commented May 30, 2013 at 3:58
  • Sorry, i'd forget a line in the code. I missed the encoding part of the POST request. that line : requestone.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); I have updated the code sample with the right line. It's works fine now Commented Jun 14, 2013 at 7:26

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.