Transform this function completely to jQuery - javascript

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.

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

"input" element that created by AJAX can't detect by another 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.

ajax error only first request is send

$('#show_mess').click(function (){
$('#dropdown_mess').slideToggle("slow");
$('#arrow_mess').slideToggle("slow");
$('#arrow_not').hide("slow");
$('#dropdown_not').hide("slow");
function recall(){ setTimeout(function () {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "http://localhost/ajax/mess_data.php", true);
xmlhttp.onreadystatechange = function () {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('dropdown_mess').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send();
document.getElementById('dropdown_mess').innerHTML = "<img class='non_auto' id='ajax_loading' src='img/ajax_loading.gif'></img>";
recall();
}, 2000);
};
recall();
});
this function works fine but when each ajax call is done i need to colse and re-oper chrome in order to work, works fine in firefox
You are already using Jquery so why don't you try it's ajax function like below
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
....
});
You can find more information on the manual

How can I re-write this code without jQuery?

How can I rewrite this code without using jQuery? I need to do it in a mobile app where I can't use jQuery.
$.ajax({
type: "POST",
url:"../REST/session.aspx?_method=put",
data: JSON.stringify(dataObject, null,4),
cache: false,
dataType: "json",
success: onSuccessLogin,
error: function (xhr, ajaxOptions){
alert(xhr.status + " : " + xhr.statusText);
}
});
You can try this:
var xmlhttp;
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) {
// What you want to do on failure
alert(xmlhttp.status + " : " + xmlhttp.responseText);
 }
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// What you want to do on success
onSuccessLogin();
}
}
xmlhttp.open("POST", "../REST/session.aspx?_method=put", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Cache-Control", "no-cache"); // For no cache
xmlhttp.send("data=" + JSON.stringify(dataObject, null,4));
As for how to do more stuff with only javascript without jQuery library take a look at W3Schools AJAX Tutorial or Mozilla - Using XMLHttpRequest
And as duri said, you will have to find a way to convert dataObject to string, as not all browsers support JSON object.
try this
var xmlHttp = createXmlHttpRequestObject();
//retrieves the xmlHttpRequest Object
function createXmlHttpRequestObject()
{
//will store the refrence to the xmlHttpRequest Object
var xmlHttp;
//if running in internet explorer version below 7
if(window.ActiveXObject)
{
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
xmlHttp = false;
}
}
else
{
try{
xmlHttp = new XMLHttpRequest();
}
catch(e){
xmlHttp = false;
}
}
if(!xmlHttp)
alert("Error Creating the xmlHttpObject");
else
return xmlHttp;
}
function callThisFunction()
{
if(xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
{
var queryString = JSON.stringify(dataObject, null,4);
var url = "../REST/session.aspx?_method=put";
xmlHttp.open("POST", url, true);
//Send the proper header information along with the request
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", queryString.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.onreadystatechange = checkHandleServerResponse;
xmlHttp.send(queryString);
}
}
function checkHandleServerResponse()
{
if(xmlHttp.readyState == 4)
{
if(xmlHttp.status == 200)
{
var JSONFile = 'jsonFormatData = '+xmlHttp.responseText;
eval(JSONFile);
if(jsonFormatData.description == 'Success')
{
//showDialog('Success','Login Successful','success',3);
location.href='default.aspx';
//setTimeout(function(){location.href='myGrupio.php';},3000);
}
else
showDialog('Error','You Need a Valid Login.','error',3);
}
else if(xmlHttp.status == 400)
{
setTimeout( function()
{
alert('you have error');
},3000);
}
else
alert("Error Code is "+xmlHttp.status)
}
}
For the Ajax request itself, have a look at the XMLHttpRequest object (special treatment for IE).
To parse the JSON response (dataType: 'json'), use JSON.parse (you might need the json2.js library).
jquery is already javascript. It's a library, entirely written in javascript. So you can use it within every javascript project. If you want to write a rest client yourself, you might look at this article
You may also consider using jQuery Mobile edition - very light - 17KB minified. 1.0 is alpha now, but I think it will be more stable and portable than self-baked code.

Categories

Resources