yossi
yossi

Reputation: 296

How can I display parameter from PHP to jQuery?

Using success: function(data) in the jquery code, when I retrieve the data from PHP, I can't display the parameter str"=>$dataString in the jQuery code.

success: function(data) {
    alert(data[0]);
    $("#display").html(data[str]);
}

ajax.php:

<?php
  if (isset($_POST['dataString'])) {
    $dataString=$_POST['dataString'];
    echo (array("str"=>$dataString));
  } else {$_POST['dataString']="";}
?>

    <html>
    <head>
    <link rel="stylesheet" type="text/css" href="./public/stylesheets/stylesheets.css"  >
    <script type="text/javascript" src="./public/js/jquery-1.7.1.min.js"></script>
    <script type="text/javascript" >
    $(document).ready(function() {
      var dataString;
      $("#valueforajax").blur(function() {
        dataString = $.trim(this.value);
        if (dataString){
        // until here it works
          $.ajax({
            type: "POST",
            dataType: 'html',
            url: "ajax.php",
            data: 'dataString=' + dataString,
            //{"dataString": dataString}
            cache: false,
            success: function(data) {
              alert(data[0]);
              $("#display").html(data[str]);
            }
          });
        }
      });
    });
  </script>
  <meta http-equiv="Content-Type" content="text/html; charset=windows-1255">
  <title>mange panel</title>
  </head>
  <body>
    <br>Type value for test in ajax<input id="valueforajax" type=text name='ajaxtest'>
    <div id="display">show</div>
  </body>
</html>

Upvotes: 1

Views: 168

Answers (3)

Nick
Nick

Reputation: 1869

I believe that the response from the server should be a json string or just a string.

<?php
   if (isset($_POST['dataString'])) {
     $dataString=$_POST['dataString'];
     echo json_encode(array("str"=>$dataString));
     exit(0);
    }
     else {
        echo json_encode(array("str"=>""));
        exit(0); //you don't want rest of html in respose too.
    }

?>

And in success

var obj = jQuery.parseJSON(data);
alert( obj.str);

Upvotes: 0

Saurabh Kumar
Saurabh Kumar

Reputation: 5945

ajax.php

<?php
  if (isset($_POST['dataString'])) {
     echo $_POST['dataString'];
     exit(0);  //this will supress html output
  }
  else {
   //do nothing
  }
?>

 $.ajax({
    type: "POST",
    dataType: 'html',
    url: "ajax.php",
    data: 'dataString=' + dataString, //{"dataString": dataString}
    cache: false,
    success: function(data)
    {
       alert(data);
       $("#display").html(data);
       }
    });

Upvotes: 1

ashryalls
ashryalls

Reputation: 308

If I understand you want to return the php array to Jquery and work with it there?

If so json_encode the array in php then return it to javascript, you should be able to work with it then.

Upvotes: 1

Related Questions