Ajax calls in symfony framework - javascript

I wanna make ajax calls in symfony2. I already done with ajax with flat php and i have no idea how to set up in this symfony framework.
<html>
<head>
<script>
function showBook(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
function showAuthor(str){
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getAuthor.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form action="">
Book name: <input type="text" id="txt1" onkeyup="showBook(this.value)">
<br><br>
Author name:<input type="text" id="txt1" onkeyup="showAuthor(this.value)">
</form>
<br>
<div id="txtHint"><b>book info will be listed here...</b></div>
</body>
</html>
Where should i pass this request?? to controller??
how to set routes??
is there any way to use flat php instead of controller??

You would pass the request to a controller action exposed using a route:
http://symfony.com/doc/current/book/routing.html
Then in your html code, if you are using twig and including javascript in a script tag, you can do
xmlhttp.open("GET","{{ path("route_name", {"parameter_name":"parameter_value"}) }}");
If you want to access the route in an attached .js file, you can use FOSJsRoutingBundle to generate the route url

If you are in a form, you can do something like :
$(document).submit(function () {
var url = $('form').attr('action');
var data = $('form').serialize();
$.post(url, data, function (data) {
window.location.href = data.redirect;
})
.fail(function () {
$('form').replaceWith(data.form);
});
});
You just need to send the correct url :
$(document).on('click', 'a', function () {
var url = window.location.href;
$.get(url, function (data) {
$('.container').replaceWith(data);
});
});
It is also possible to use a routing generate, simply add:
"friendsofsymfony/jsrouting-bundle": "dev-master" to your composer.json.
AppKernel.php :
new FOS\JsRoutingBundle\FOSJsRoutingBundle()
Then config it in your routing.yml :
fos_js_routing:
resource: "#FOSJsRoutingBundle/Resources/config/routing/routing.xml"
And finally use "expose" arg in your routing :
#Route("/{table}/index", name="beta.index", options={"expose"=true})
I use annotation routing
In your JS :
var url = Routing.generate('beta.index', { 'table': 'foo' });
Hope it'll help you :)

Related

Get string from javascript on the same page

Problem is that i have dynamic changing script for mysql query
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
</script>
I need to get str from this code to php.
from the html point of view i get string from
<select name="users" onchange="showUser(this.value)">
adn in the other file getuser.php I have
$q = $_GET['q'];
$sql="SELECT * FROM articles WHERE type = '".$q."'";
The biggest problem is that i put onchange this parameters so i can get values to my page without refreshing it. But now i cant get value from combobox to php.
How can i do this ???
Thanks in advance

Cannot click on the content which is loaded through ajax function

Currently, I cannot load the second content using ajax. Actually, I have loaded the first content using ajax. In order to go to the second content, i need to call the ajax function but after i click to load the second content using ajax it does not work. I have checked my code, its working fine if i directly call the second ajax function, unless i call the first ajax function after that the ajax is not working again. Are there any ways to solve this problem.
This is the first ajax code:
function showMusic(str) {
if (str == "") {
document.getElementById("albums").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("albums").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getAlbums.php?q="+str,true);
xmlhttp.send();
}
}
The above function works. The above function is at another php file
This is the second ajax code:
$(document).ready(function(){
function showArtistDetails(str) {
if (str == "") {
alert("hi");
document.getElementById("artist").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
alert("hi1");
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
alert("hi2");
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("artist").innerHTML = xmlhttp.responseText;
alert("hi3");
}
};
xmlhttp.open("GET","getArtist.php?title="+str,true);
alert("hi4");
xmlhttp.send();
alert("hi5");
}
}
$("#clickme").click(showArtistDetails);
});
This is the php code which is at another php file:
echo "<td id=\"clickme\">" . $row['CDTitle'] . "</td>";
I have been trying to solve this for the past 2 days but i am unable to solve it. Some are saying its a bug. But i really i dont know what causes this problem. Thanks in advance.

Simple AJAX example - load data from txt file

I'm trying to do a basic AJAX tutorial to read data from a file, hello.txt, into my webpage. hello.txt and my current html webpage are in the same directory. Does anyone know what I'm doing wrong? Nothing happens when I load the page.
<!DOCTYPE html>
<head><title>Ajax Test</title>
<script type="text/javascript">
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "hello.txt", true);
xmlHttp.addEventListener("load", ajaxCallback, false);
xmlHttp.send(null);
function ajaxCallback(event){
alert( "Your file contains the text: " + event.target.responseText );
}
</script>
</head>
<body>
</body>
</html>
here is a function i always use for simple async get ajax:
1.use onload as it's shorter to write and as you don't need to add multiple eventhandlers.
2.don't do syncronous ajax.
js
function ajax(a,b,c){//url,function,just a placeholder
c=new XMLHttpRequest;
c.open('GET',a);
c.onload=b;
c.send()
}
function alertTxt(){
alert(this.response)
}
window.onload=function(){
ajax('hello.txt',alertTxt)
}
example
http://jsfiddle.net/9pCxp/
extra info
https://stackoverflow.com/a/18309057/2450730
full html
<html><head><script>
function ajax(a,b,c){//url,function,just a placeholder
c=new XMLHttpRequest;
c.open('GET',a);
c.onload=b;
c.send()
}
function alertTxt(){
alert(this.response)
}
window.onload=function(){
ajax('hello.txt',alertTxt)
}
</script></head><body></body></html>
Here is your answer.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var allText = this.responseText;
alert(allText);
}
};
xhttp.open("GET", "filename.txt", true);
xhttp.send();
The below code may be useful for someone...
<!DOCTYPE html>
<html>
<body>
<h1>Load Data from text file </h1>
<button type="button" onclick="loadDoc()">Change Content</button>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "info.txt", true);
xhttp.send();
document.getElementById("demo").innerHTML = xhttp.responseText;
}
</script>
</body>
</html>
Open an empty .PHP file or .ASPX file (or just any server-side language that can run javascript)
Paste this code between "head" tags.
<script>
var xmlhttp;
function loadXMLDoc(url, cfunc) {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = cfunc;
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function myFunction() {
loadXMLDoc("hello.xml", function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
});
}
</script>
As you see, javascript is referring to "hello.xml" file to get information from.
Open an empty XML file inside the project folder you have created in. Name your XML file as "hello.xml"
Paste this code to your XML file.
<?xml version="1.0" encoding="utf-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
Run your php (or .aspx) file on localhost.
Click on button, your page must acquire the XML data into your website.
function Go() {
this.method = "GET";
this.url = "hello.txt";
if (window.XMLHttpRequest && !(window.ActiveXObject)) {
try {
this.xmlhttp = new XMLHttpRequest();
}
catch (e) {
this.xmlhttp = false;
}
// branch for IE/Windows ActiveX version
}
else if (window.ActiveXObject) {
try {
this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
this.xmlhttp = false;
}
}
}
if (this.xmlhttp) {
var self = this;
if (this.method == "POST") {
this.xmlhttp.open("POST", this.url, true);
}
else {
//remember - we have to do a GET here to retrive the txt file contents
this.xmlhttp.open("GET", this.url, true);
}
this.xmlhttp.send(null);
//wait for a response
this.xmlhttp.onreadystatechange = function () {
try {
if (self.xmlhttp.readyState == 4) {
if (self.xmlhttp.status == 200) {
if (self.xmlhttp.responseText != null) {
self.response = self.xmlhttp.responseText;
alert(self.xmlhttp.responseText);
}
else {
self.response = "";
}
}
else if (self.xmlhttp.status == 404) {
alert("Error occured. Status 404: Web resource not found.");
}
else if (self.xmlhttp.status == 500) {
self.showHtmlError("Internal server error occured", "Status: " + self.xmlhttp.responseText);
}
else {
alert("Unknown error occured. Status: " + self.xmlhttp.status);
}
}
}
catch (e) {
alert("Error occured. " + e.Description + ". Retry or Refresh the page");
}
finally {
}
};
}
}
//Use the function in your HTML page like this:
Go();
</script>

Javascript does not return servlet response

I have wriiten welcome screen which basically use below javascript to call creditCheck servlet. Within servlet, there is method which will check the username and password. Servlet returns value properly. alert is not getting generated after servlet excutation within javascript.
however if execute simple servlet ( not doing anything, just printing variables), it will generate alert.
below is my javascript within JSp file:
############################################
<script type="text/javascript">
function getXmlHttpRequestObject(){
var xmlHttp = false;
if (window.XMLHttpRequest){
return new XMLHttpRequest(); //To support the browsers IE7+, Firefox, Chrome, Opera, Safari
}
else if(window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP"); // For the browsers IE6, IE5
}
else {
alert("Error due to old verion of browser upgrade your browser");
}
}
var xmlhttp = new getXmlHttpRequestObject(); //xmlhttp holds the ajax object
function servletPost() {
if(xmlhttp) {
var username = document.getElementById("uname");
var password = document.getElementById("pass");
xmlhttp.open("POST","CredCheck",true);
xmlhttp.onreadystatechange = handleServletPost;
req.onreadystatechange = callback;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("uname=" + username.value + "&pass=" + password.value );
}
}
function handleServletPost() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
else {
alert("Ajax calling error");
}
}
}
</script>
#
I have changed xmlhttp.open("POST","CredCheck",true); to
xmlhttp.open("POST","CredCheck",false);
xmlhttp.onreadystatechange = handleServletPost;

xmlhttp.responseText not outputting to innerHTML

I'm trying to familiarize myself with Ajax as I will need to use it continually for work. I'm working through the W3Schools tutorial trying things with my Apache2 server. I have a file called ajax_info.txt on the server (under /var/www (ubuntu)). I'm making a call to it and with Firebug I see I get a good response (4 & 200) but it isn't outputting the contents of the file to the DOM. Here's the code:
<!DOCTYPE html>
<html>
<head>
<script>
var xmlhttp;
var url = "http://192.168.0.5/ajax_info.txt";
function loadXMLDoc(url, cfunc) {
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = cfunc;
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function myFunction() {
loadXMLDoc(url, function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
});
}
</script>
</head>
<body>
<div id="myDiv">
<h2>Let AJAX change this text</h2>
</div>
<button type="button" onclick="myFunction()">Change Content</button>
</body>
</html>
I'm not exactly sure what it is I'm doing wrong. The w3schools tutorial isn't exhaustive by any stretch. I plan on buying a book, but I'd love to learn these simple GET calls as it will get me headed in the proper direction. Any suggestions would be greatly appreciated.
function ajax(x) {
var a;
if (window.XMLHttpRequest) {
a = new XMLHttpRequest();
} else if (window.ActiveXObject) {
a = new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Browser Dosent Support Ajax! ^_^");
}
if (a !== null) {
a.onreadystatechange = function() {
if (a.readyState < 4) {
//document.getElementById('cnt').innerHTML = "Progress";
} else if (a.readyState === 4) {
//respoce recived
var res = a.responseText;
document.getElementById('center_scrolling_div').innerHTML = res;
eval(document.getElementById('center_scrolling_div').innerHTML);
}
};
a.open("GET", x, true);
a.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
a.send();
}
}

Categories

Resources