"input" element that created by AJAX can't detect by another javascript? - javascript

We are using http://jscolor.com (JavaScript Color picker) without any problem normally. But when we create the input element by AJAX, it don't work correctly and jscolor.js can not detect class (color) of the input, while the input show correctly. What we should do?
The HTML code is:
<html>
<head>
<script src='/js/jscloro.js'></script>
<script>
function showHint(str)
{
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
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","gethint.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
FORM
<div id="txtHint"></div>
</body>
</html>
Our PHP response to ajax is:echo "<input class=\"color\" type=\"text\" value=\"66ff00\">";

I think, when you create new DOM element after documentload, you should bind the event's after where you create that's element.
UPDATED PART OF ANSWER
See this html and script:
<div id="container"></div>
$(document).ready(function () {
// if you add the event for element that currenlty not exist on
// page, and later may be created, the even cannot fired
$('#elem').click(function () {
alert('You are clicked on input!');
});
$.ajax({
url: 'somePage.aspx',
type: 'POST',
contentType: 'application;json/ charset=utf-8',
dataType: 'json',
data: {},
success: function (msg) {
// if you create your own element here
$('#container').append(function () {
return $('<span>')
.text('This Is New Element')
.attr('id', '#elem');
});
}
});
});
But the correct way is to add event after where DOM element is created, as you see below:
$(document).ready(function () {
$.ajax({
url: 'somePage.aspx',
type: 'POST',
contentType: 'application;json/ charset=utf-8',
dataType: 'json',
data: {},
success: function (msg) {
// if you create your own element here
$('#container').append(function () {
return $('<span>')
.text('This Is New Element')
.attr('id', '#elem')
.click(function () { // you should bind your events here
alert('You are clicked on input!');
});
});
}
});
});
UPDATED PART 2
you should initialize the new jscolor instance, for example use this code
new jscolor.color($('.color'), {});
after you created your own element.
UPDATED PART 3
<html>
<head>
<script src='/js/jscloro.js'></script>
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
}
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;
/* YOU SHOULD INITIALIZE THE NEW JSCOLOR INSTANCE HERE */
var myPicker = new jscolor.color(document.getElementById('myField1'), {})
myPicker.fromString('99FF33') //
/**/
}
}
xmlhttp.open("GET", "gethint.php?q=" + str, true);
xmlhttp.send();
}
</script>
</head>
<body>
FORM
<div id="txtHint"></div>
</body>
</html>
Please mark it as answer if it helped you.

Related

Load file Javascript on referer main page

My Script like this :
function showBrand(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
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","index?modul=sgob&q="+str,true);
// xmlhttp.open("GET","window.location.href + "?q="+str,true);
xmlhttp.send();
}
But get file modul=sgob not refered with file javascript.. so I can't run checkbox select all.
Yes, i has been solved this case, i'm finally change my code in javascript, like this :
jQuery(function() {
$("#getBus").change(function() {
var id = $(this).find(":selected").val();
var dataString = 'action='+ id;
$.ajax({
url: "index?modul=sgob",
data: dataString,
cache: false,
success: function(response) {
/* If Success */
$("#show-bus").html(response);
}
});
});
});
Then modul=sgob can run checkbox select all..

Ajax calls in symfony framework

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 :)

html form does not fire javascript

I have following form and javascript which is not activated on submit. I can not understand where is the problem so that the javascript is not fired by pressing the button. The script is included in the html of course and the path is correct.
var req;
function addProductToCart(){
var url = "/addToCart";
var productReference = document.getElementById("selectedProductRef");
var size = document.getElementById("selectedProductSize");
req = initRequest();
req.open("POST", url, true);
//req.onreadystatechange = callback;
req.send("selectedProductRef="+productReference.value+"&selectedProductSize="+size.value);
}
function callback(){
if (req.readyState == 4) {
if (req.status == 200) {
parseMessages(req.responseText);
}
}
}
function initRequest(){
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
req = new XMLHttpRequest();
}
else if (window.ActiveXObject){
// code for IE6, IE5
req = new ActiveXObject("Microsoft.XMLHTTP");
}
}
<form name="addToShoppingBag" id="addToShoppingBag" >
<input type="hidden"
form="addToShoppingBag"
id="selectedProductRef"
name="selectedProductRef"
value="${selectedCart.productReference}">
<input type="button"
form="addToShoppingBag"
name="addToCart"
id="addToCart"
onclick="addProductToCart()"
class="css-button primary"
value="ADD TO SHOPPING BAG">
</form>
Here's a nice blog post on why to move away from using inline javascript.
You might want to consider using jQuery as a way to facilitate going to a more event-driven scripting approach. It also makes async requests pretty straight-forward with its $.ajax() method.
Here's your addProductToCart() in jQuery format:
$('body').on('click', '#addToCart', ({
var url = "/addToCart";
$.ajax({
type: "POST",
url: url,
data: '{selectedProductRef: "'+ $('#selectedProductRef').val() + '", selectedProductSize:"' + $('#selectedProductSize').val() + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json"
});
});
var req;
function addProductToCart(){
var url = "/addToCart";
var productReference = document.getElementById("selectedProductRef");
productReferenceValue =productReference ;
var size = document.getElementById("selectedProductSize");
sizeValue=size .value;
rm = initRequest();
rm.open("POST", url, true);
//req.onreadystatechange = callback;
rm.send("selectedProductRef="+productReferenceValue +"&selectedProductSize="+size.sizeValue);
}
function callback(){
if (req.readyState == 4) {
if (req.status == 200) {
parseMessages(req.responseText);
}
}
}
function initRequest(){
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
else if (window.ActiveXObject){
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
<!-- language: lang-html -->
<form name="addToShoppingBag" id="addToShoppingBag" >
<input type="hidden"
form="addToShoppingBag"
id="selectedProductRef"
name="selectedProductRef"
value="${selectedCart.productReference}">
<input type="button"
form="addToShoppingBag"
name="addToCart"
id="addToCart"
onclick="addProductToCart()"
class="css-button primary"
value="ADD TO SHOPPING BAG">
</form>
<!-- end snippet -->
A little change in your code instead of req = initRequest(); just call initRequest()
var size = document.getElementById("selectedProductSize");
initRequest();
req.open("POST", url, true);
initRequest() does not return any value.

Transform this function completely to jQuery

I need this function as jQuery.
There is a part jQuery but I am finding a tough time to write the code!
function showUser(str) {
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("drop_em").innerHTML = xmlhttp.responseText;
$('#scrollbar3').tinyscrollbar();
}
}
xmlhttp.open("GET", "list_playlist_popup.php?qq=" + str, true);
xmlhttp.send();
}
What have you tried? Where are you stuck? (Because this is the most basic form of AJAX call in jQuery)
$.get(
"list_playlist_popup.php",
{ qq: str },
function success(data) {
$('#drop_em').html(data);
$('#scrollbar3').tinyscrollbar();
});
Use jQuery Ajax :
$.ajax({
url:'list_playlist_popup.php',
type:'POST',
data:{
variable : value
},
success:function(data){
alert('success');
}
})
Just copy paste this over the existing function.
function showUser( str ) {
$.ajax({
url: 'list_playlist_popup.php',
data: {
'qq': str
}
}).done(function( data ) {
$('#drop_em').html(data);
$('#scrollbar3').tinyscrollbar();
});
}
function showUser(str) {
$.get('list_playlist_popup.php',{qq:str},function(response) {
$('#drop_em').html(response);
$('#scrollbar').tinyscrollbar();
});
};
This is your jQuery equivalent.

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