user123
user123

Reputation: 5407

Getting value from file called by ajax request using json

On button click I submit the form and post some data to data.php. Form to be submitted is: <form action="data.php" method="POST" onsubmit="showUser(this, event)">

index.php

function showUser(form, e) {
      //alert(myid);
      e.preventDefault();
      e.returnValue=false;
      var xmlhttp;

     //Get value for sent, text1, text2, text3      
      console.log(sent);
      if (window.XMLHttpRequest) {
        xmlhttp=new XMLHttpRequest();
      }
      else {
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
      xmlhttp.onreadystatechange = function(e) {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200){

xmlhttp.responseText.resultOne;  // Is this correct? Should be here? I dont know correct
xmlhttp.responseText.resultTwo;

document.getElementById("myFirstDiv").innerHTML=xmlhttp.responseText.resultOne;
document.getElementById("mySecondDiv").innerHTML=xmlhttp.responseText.resultTwo;
        }
      }
        xmlhttp.open(form.method, form.action, true);
      xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
      deURIComponent(text3);
      xmlhttp.send('sent=' + sent + '&text1=' + text1 + '&text2=' + text2 + '&text3=' + text3);
    }

data.php

<?php 
    ob_start(); 
    echo "1:blah\n"; 
    echo "</br>";
    echo "shonice";
    echo "1:blahDFDFD\n"; 
    $div1 = ob_get_clean();

    ob_start(); 
    echo "2:blah"; 
    echo "</br>";
    echo "2:DFDFDFblah\n"; 
    $div2 = ob_get_clean();

$resultArray = array("resultOne" => $div1,"resultTwo" => $div2);

echo json_encode($resultArray);

?> 

How can I fetch json value from `data.php` into `myFirstdiv` aand `mysecondDiv`?

What's wrong with code I have created. It show undefined value in div as a result.

Upvotes: 0

Views: 139

Answers (1)

Joss
Joss

Reputation: 57

lets assume that there is a result from the data.php file and it is json encoded..

              if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
                 {
                     var div1=document.getElementById("myFirstDiv");
                     var div2=document.getElementById("mySecondDiv");

                       var data=JSON.parse(xmlhttp.responseText);
                        //alert data to see what u get..
                        div1.innerHTML=data['resultOne'];
                        div2.innerHTML=data['resultTwo'];
                  }

hoping this helps..

Upvotes: 1

Related Questions