How to Simply Ajax Script (Removing duplicate code)? - javascript

I want to simplify the following script, and create a reuseable funciton,
I use it with:
<span id="test"></span>
<span id="abc"></span>
<span id="123"></span>
here it is now:
<script>
$(document).ready(function(){
var callAjax = function(){
$.ajax({
method:'get',
url:'abctest.php',
success:function(data){
$("#test").html(data);
}
});
}
setInterval(callAjax,1000);
});
$(document).ready(function(){
var callAjax = function(){
$.ajax({
method:'get',
url:'getabc.php',
success:function(data){
$("#abc").html(data);
}
});
}
setInterval(callAjax,1000);
});
$(document).ready(function(){
var callAjax = function(){
$.ajax({
method:'get',
url:'123.php',
success:function(data){
$("#123").html(data);
}
});
}
setInterval(callAjax,1000);
});
</script>
as you can see, all I need is to change the url and #, so I create a function:
function good(url,tag){
var callAjax = function(){
$.ajax({
method:'get',
url:'url.php',
success:function(data){
$("#tag").html(data);
}
});
}
setInterval(callAjax,1000);
}
and rewrite the script to:
<script>
$(document).ready(good(abctest,test));
$(document).ready(good(getabc,abc));
$(document).ready(good(123,123));
</script>
looks much better. but seems not so easy.
it not working. how to solve this problem?

Your almost there. You need to manually concatenate the strings like
function good(url,tag){
var callAjax = function(){
$.ajax({
method:'get',
url:url+'.php',
success:function(data){
$("#"+tag).html(data);
}
});
}
setInterval(callAjax,1000);
}
Javascript is not like php where variables can be evaluated between double quotes.
Also, you need to pass your parameters in as strings
$(document).ready(function(){
good('abctest','test');
good('getabc','abc');
good('123','123');
});

Related

multiple ajax calls with codeigniter

excuse me sir/ma'am
i'm new to ajax, i'm trying to do multiple ajax call in one function to dislay info after an option in dropdown is selected and it goes into separate field ,something like
a goes into description field, b goes into schedule field
i already got the function for a 1 call but when i'm trying to do 2 it's just doesn't work
here is the code that i made for multiple call
<script>
// multiple ajax calls code that i make
// #paket is the dropdown id
$.when(
$('#paket').unbind('change');
$('#paket').change(function(){
var opt_sel = $('#paket').val();
$.ajax({
url:'bttdev3/tour/s1',
method: "POST",
data: {
sel_op:opt_sel
}
}),
$.ajax({
url:'bttdev3/tour/s2',
method: "POST"
data: {
sel_op:opt_sel
}
});
});
);
.then(function(a,b){
$.('#detail').html(a);
$.('#jadwal').html(b);
});
</script>
here is the previous code that works for 1 data call
<script>
1 call function
(function(){
$('#paket').unbind('change');
$('#paket').change(function(){
var opt_sel = $('#paket').val();
var baseurl = "www.dev3.gatra.com/bttdev3";
$.ajax({
method:"POST",
url: '/bttdev3/tour/s1',
// url: "/bttdev3/tour/" + s1,
data:{
sel_op:opt_sel
}
}).done(function(a){
$('#detail').html(a);
}).fail(function(){
alert("gagal memanggil data.");
});
});
});
</script>
any help would be appreciated
try this one
$(document).on('change', '#packet', function(){
_ajax('bttdev3/tour/s1', 'POST', {sel_op: $(this).val()}, function(res){
$('#detail').html(res);
});
_ajax('bttdev3/tour/s2', 'POST', {sel_op: $(this).val()}, function(res){
$('#jadwal').html(res);
});
});
function _ajax(url, method, data, callback){
$.ajax({
method,
url,
data
}).done(function(a){
if(typeof(callback) != 'undefined'){
callback (a);
}
}).fail(function(){
alert("gagal memanggil data.");
});
}

Set interval to ajax form

So I'm trying to send the form info to php with ajax form every second, but for some reason it doesn't want to.
Here is my latest attempt, I tried every other similar combination(like put everything in the function or just put everything into the setInterval).
$(document).ready(function() {
var ajaxCall=function() {
$("#myForm").ajaxForm(function(e) {
$.ajax({
type:'post',
url:'php1.php',
data:$("#myForm").serialize(),
success:function(data) {
document.getElementById("result").innerHTML=data;
}
});
});
}
setInterval(ajaxCall,1000);
});
EDIT
Solved with M.M answer, thank you for the help!
Simply change ajaxForm to ajaxSubmit
See this (question) and this (documentation) for more information on AjaxForm vs AjaxSubmit
Essentially AjaxForm submits when the user clicks the button and AjaxSubmit does it immediately so your code should be:
$(document).ready(function()
{
var ajaxCall=function()
{
$("#myForm").ajaxSubmit(function(e)
{
$.ajax(
{
type:'post',
url:'php1.php',
data:$("#myForm").serialize(),
success:function(data)
{
document.getElementById("result").innerHTML=data;
}
});
});
}
setInterval(ajaxCall,1000);
});
Update after comment explanation
$(document).ready(function(){
//live feed
var ajaxCall=function(){
$("#myForm").ajaxSubmit(function(e){
ajax_submit();
});
}
setInterval(ajaxCall,1000);
//real submit
$("#myForm").ajaxForm(function(e){
ajax_submit();
});
function ajax_submit(){//ajax_code
$.ajax({
type:'post',
url:'php1.php',
data:$("#myForm").serialize(),
success:function(data) {
document.getElementById("result").innerHTML=data;
}
});
}
});
If you wish to differentiate the feed from the submit you can pass a parameter to the ajax_submit function
Getting rid of the ajaxForm() call seems to accomplish what you are trying to do:
$(document).ready(function() {
var ajaxCall = function() {
$.ajax({
type: 'post',
url: 'php1.php',
data: $("#myForm").serialize(),
success: function(data) {
document.getElementById("result").innerHTML = data;
}
});
}
setInterval(ajaxCall, 1000);
});

How access data in JavaScript arrays using $.ajax

This is a script when the script is executed I want to load the data into the div of id #trial. The script is an external array with three names the second I am trying to call is 'sarah'. Whats wrong?
<script>
$(document).ready(function(){
$("#trial").click(function(){
var attempt=$.ajax({
url: "names.js",
dataType: "script"
});
var msg=names[1];
attempt.done(function( msg ) {
$( "#trial" ).html( msg );
});
});
});
</script>
Change your code to this:
<script>
$(document).ready(function(){
$("#trial").click(function(){
$.ajax({
url: "names.js",
dataType: "script",
success: function(res){
//todo something with res
}
});
});
});
</script>

getjson query is not working

Json page is : http://freegeoip.net/json/59.92.78.49
and my code is
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("http://localhost/02/t.php",function(result){
alert(result.ip);
});
});
});
</script>
this simple code is not working :(
Seem like freegeoip.net support jsonp,you can do:
$('button').click(function () {
$.ajax({
url: "http://freegeoip.net/json/59.92.78.49",
dataType: "jsonp",
success: function (result) {
alert(result.ip); // server response
}
});
});
Fiddle Demo

Javascript only working when placed below HTML

I couldn't find a solution for the following problem I'm having. I'm using some javascript code to make my (live) search work (via ajax). The problem is that the Javascript only works when I place it below the HTML:
<form action="filter.php" name="filter" method="get" id="filter">
<input type="text" id="search_bar" name="s" placeholder="Type hier je zoekterm..." />
</form>
<ul id="result"></ul>
Javascript
$("#filter").submit(function(event) {
event.preventDefault();
$("#result").html('');
var values = $(this).serialize();
$.ajax({
url: "tracks_content.php",
type: "get",
data: values,
success: function(data){
$('#result').html(data);
},
});
});
$(this).mouseup(function() {
document.getElementById('result').style.display='none';
});
$("#result").mouseup(function(){
return false;
});
$("#filter").bind('input',(function(event){
var query = document.getElementById('search_bar').value;
if(query!=""){
$("#filter").submit();
document.getElementById('result').style.display='block';
}
else{
$('#result').html('');
document.getElementById('result').style.display='none';
}
}));
How can I make it work when putting the Javascript in front of the HTML?
This is because you are referring to HTML that doesn't exist yet when the JavaScript is on top.
Wrap your code in $( document ).ready(). Thi smakes the browser wait until the DOM is loaded before firing the JavScript.
$( document ).ready(function() {
$("#filter").submit(function(event) {
event.preventDefault();
$("#result").html('');
var values = $(this).serialize();
$.ajax({
url: "tracks_content.php",
type: "get",
data: values,
success: function(data){
$('#result').html(data);
},
});
});
$(this).mouseup(function() {
document.getElementById('result').style.display='none';
});
$("#result").mouseup(function(){
return false;
});
$("#filter").bind('input',(function(event){
var query = document.getElementById('search_bar').value;
if(query!=""){
$("#filter").submit();
document.getElementById('result').style.display='block';
}
else{
$('#result').html('');
document.getElementById('result').style.display='none';
}
}));
});
FYI, why are you uisng document.getElementById() when you have jQuery available to you and are already using it?
If you put that before the HTML, then you are trying to add a submit event to a form which doesn't exist at the time the JavaScript runs.
Wrap the script in a function, then use that function as an event handler for the ready or load event.
Passing a function (instead of a selector, DOM element or strong of HTML) as the argument to jQuery will bind as the ready handler.
jQuery(bind_form_event_handler);
function bind_form_event_handler() {
$("#filter").submit(function(event) {
// etc etc
}
Change you javascript to this
wrap with $(function(){}
like this
$(function(){
$("#filter").submit(function(event) {
event.preventDefault();
$("#result").html('');
var values = $(this).serialize();
$.ajax({
url: "tracks_content.php",
type: "get",
data: values,
success: function(data){
$('#result').html(data);
},
});
});
$(this).mouseup(function() {
document.getElementById('result').style.display='none';
});
$("#result").mouseup(function(){
return false;
});
$("#filter").bind('input',(function(event){
var query = document.getElementById('search_bar').value;
if(query!=""){
$("#filter").submit();
document.getElementById('result').style.display='block';
}
else{
$('#result').html('');
document.getElementById('result').style.display='none';
}
}));
})

Categories