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.
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