1

I must be doing something stupid here. I have this php file:

$arr = array("result" => "dasdasds;bks fjsdgjdklsds j&*", "text" =>"23 + 2   =   ?");

echo json_encode($arr);

And I call it in my js file:

/*
   * PHP array to json
   */

  $("#jsonform").submit(function(e){

      $.ajax({
          url:"/phparraytojson/Helper.php", 
          success: function(data){ 
             console.log(data.result) //undefined
             console.log(data); //{"result":"dasdasds;bks fjsdgjdklsds j&*","text":"23 + 2 =   ?"} 
          }

      })
      e.preventDefault();
  })
4
  • What exactly is your error? Don't you mind adding more information to your question? Commented Apr 18, 2015 at 7:31
  • 1
    use dataType: "json", Commented Apr 18, 2015 at 7:31
  • I get undefined when calling data.result Commented Apr 18, 2015 at 7:32
  • Just a side notice, if you are going to output JSON on your server you should adjust the headers accordingly, place next line as first in your script : header('Content-type: application/json'); Commented Apr 18, 2015 at 8:23

3 Answers 3

1

Adding dataType: "json" should fix this:

$.ajax({
      url:"/phparraytojson/Helper.php", 
      dataType: "json",
      success: function(data){ 
         console.log(data.result) //undefined
         console.log(data); //{"result":"dasdasds;bks fjsdgjdklsds j&*","text":"23 + 2 =   ?"} 
      }

  })
Sign up to request clarification or add additional context in comments.

Comments

1
you should be use datatype:'json' in ajax call
$.ajax({
    url:"/phparraytojson/Helper.php", 
    async: false,
    dataType: 'json',
    success: function(data){ 
       console.log(data.result) //undefined
       console.log(data); //{"result":"dasdasds;bks fjsdgjdklsds j&*","text":"23 + 2 =   ?"
                   } 
     }

});

Comments

1

In ajax call you have to add format of output you are receiving from php. ie: dataType:"json"

$("#jsonform").submit(function(e){

  $.ajax({
      url:"/phparraytojson/Helper.php", 
      dataType:"json",              //Dont miss to add
      success: function(data){ 
         console.log(data.result) //undefined
         console.log(data); //{"result":"dasdasds;bks fjsdgjdklsds j&*","text":"23 + 2 =   ?"} 
      }

  })
  e.preventDefault();  });

Comments

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.