0

I'm using Jquery to make an AJAX call to a PHP page which outputs JSON with the json_encode function. This PHP page contains javascript code as well, which is sent along with the JSON code, resulting in a JSON parse error. Is there a way to prevent this? Many thanks for your support.

enter image description here

PHP page:

<script type="text/javascript">
//javascript needed on this page
</script>

//json output
$data = array('one'=> 'hello', 'two' => 'world');
echo json_encode($data);
4
  • Can you show us the PHP page? Commented Apr 26, 2014 at 14:17
  • Not sure how to do this the proper way :( Commented Apr 26, 2014 at 14:22
  • The only reasonable solution is to fix the php script so that it only outputs JSON . Commented Apr 27, 2014 at 7:55
  • @Felix You are right, but I can't seem to get it right. Anyway not with a Javascript code snippet on that page. Commented Apr 27, 2014 at 8:01

2 Answers 2

0

Wrap your json in a div and then parse it on success.

From this: jquery ajax fetch only one div block from other page

Here is your calling page:

 $.ajax({
    url:"page.php",
    success:function(data){
       var returnData = $(data).find('#dataWrap').text();
    }
 });

Here is your php page:

<script>
   //Your Code Here
</script>

<div id="dataWrap">
   {"Your JSON":"Here"}
</div>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you user3280891. This does the job.
0

Without more detail is difficult to know, but I think your PHP page has different roles, one of them to print JSON as a result of an ajax request. I think you should print JSON only for this role, and Javascript and Html for the rest of roles, differentiating the type of http response using exclusive parameters, playing with Accept http header and Content-Type or using different http methods (GET, POST, ...) for your different purposes (for this last you can read about REST).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.