I am developing a social network web site using Symfony2. In fact, I would like to know how I can get an array field value from a PHP file using jquery/Ajax in Symfony2. Among the files that I have in my project folder there are two files: test.html.twig and moslem1.php. The code of each of that two files is below:

The code of test.html.twig:

 <html>
    <head>
    </head>
    <body>
        <script src="{{asset('bundles/moslemtest/src/jquery.min.js')}}" type="text/javascript"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                $.ajax({
                    url: '{{asset('bundles/moslemtest/phptest/moslem1.php')}}',
                    type: 'POST',
                    dataType: 'JSON',
                    success: function(data1) {
                        var id=data1.id;
                        document.write(id);
                    }
                });
            });
        </script>
    </body>
</html>

The code of moslem1.php:

    <?php
$con=mysqli_connect("localhost","root","","test");
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM jqcalendar ORDER BY id DESC LIMIT 0, 1");
while($row = mysqli_fetch_array($result)) {
    $notification = array('id'=>$row['Id'],'subject'=>$row['Subject'],'location'=>$row['Location'],'description'=>$row['Description'],'starttime'=>$row['StartTime'],'endtime'=>$row['EndTime']);
}
echo json_encode($notification);
mysqli_close($con);
?>

The issue is whenever I run the file test.html.twig it displays the out below:

undefined

What is strange is that it works when I put the code of the file test.html.twig in a html file. in fact I created two other files (not in Symfony2) which are t1.html and moslem1.php. their codes are as below:

The code of t1.html:

    <html>
    <head>
    </head>
    <body>
        <script src="jquery.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                $.ajax({
                    url: 'moslem1.php',
                    type: 'POST',
                    dataType: 'JSON',
                    success: function(data1) {
                        var id=data1.id;
                        document.write(id);
                    }
                });
            });
        </script>
    </body>
</html>

The code of moslem1.php:

    <?php
$con=mysqli_connect("localhost","root","","test");
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM jqcalendar ORDER BY id DESC LIMIT 0, 1");
while($row = mysqli_fetch_array($result)) {
    $notification = array('id'=>$row['Id'],'subject'=>$row['Subject'],'location'=>$row['Location'],'description'=>$row['Description'],'starttime'=>$row['StartTime'],'endtime'=>$row['EndTime']);
}
echo json_encode($notification);
mysqli_close($con);
?>

As I said above, it works when I deal with a HTML file, but as I work on Symfony2 I have to use files with "html.twig" extension for view(output). So my question is what shall I do to make it works correctly with my twig file?

Thanks in advance.

share|improve this question
    
You're trying to do that in a very very weird way. Instead of using moslem1.php create controllers' action which will return the JsonResponse. Try to refactor your code and when you're done, come back here again and ask if you're still facing some problems – bartek May 28 '14 at 14:28
    
@bartek: I think the problem is about the two lines: var id=data1.id; document.write(id); For more explanation, please have a look at the comments that I typed for the answer of Mr. vobence – Nadim Akram May 28 '14 at 15:07
up vote 6 down vote accepted

It's a very bad idea to put the php file into the bundles folder, it's a huge security issue. If you want an AJAX response then put it into the Controller.

Create a new action in the Controller as you normally do. Write the AJAX action and give back a JSONResponse as a response.

/**
* Return an ajax response
*/
public function ajaxAction(){
   // do the controller logic
   // $response is an array()
   return new JSONResponse($response);
}

Then in jQuery ajax set the url like this:

$.ajax({
  url: 'url/to/your/controller', // If you use the FOSJsRoutingBundle then it will be Routing.generate('route_name')
  type: 'POST',
  dataType: 'JSON',
  success: function(data1) {
    var id=data1.id;
    document.write(id);
  }
});

In the new action you can use the EntityManager to access your database.

Here is a good article about this issue: http://symfony2forum.org/threads/5-Using-Symfony2-jQuery-and-Ajax

You should also consider to use the FOSJsRoutingBundle for javascript routing. It's a very great bundle that allows you to generate routes in javascript files as you can do it in twig with the path('path_name') command.

Here is the GitHub project for this bundle: https://github.com/FriendsOfSymfony/FOSJsRoutingBundle

Try to understand the Symfony Request -> Response process, because if you don't follow it, it will cause serious problems for you.

share|improve this answer
    
Thanks a lot for your answer, by the way I changed the code of test.html.twig as below: – Nadim Akram May 28 '14 at 14:56
    
<html> <</head> <body> <script src="{{asset('bundles/moslemtest/src/jquery.min.js')}}" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function() { $.ajax({ url: '{{asset('bundles/moslemtest/phptest/moslem1.php')}}', type: 'POST', dataType: 'JSON', success: function(data1) { document.write(data1); } }); }); </script></body></html> – Nadim Akram May 28 '14 at 14:58
    
And it works...it displays for me this output: {"id":"2","subject":"ss","location":null,"description":null,‌​"starttime":"2014-05‌​-26 01:00:00","endtime":"2014-05-26 02:00:00"} So as you can you see here, the problem is in the two lines: var id=data1.id; document.write(id); – Nadim Akram May 28 '14 at 15:01

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.