JavaScript - Ajax Not Displaying Success Function
Hello all;
Sorry if this is in the wrong forum, but I'm using a little bit of everything in this problem. What I have is an ajax function using JQuery that references to a separate PHP file, which also contains mySQL. Here is my code: Code: <!DOCTYPE html> <head> <script type="text/javascript" src="jquery-1.6.4.js"></script> </head> <body> <div onclick="addtask();" style="width:400px; height:200px; background:#000000;"></div> <script> function addtask() { var tid = (Math.floor(Math.random() * 3)) + 1; var tsk = (Math.floor(Math.random() * 10)) + 1; if(tsk !== 1) { $.ajax({ type: "POST", url: "taskcheck.php", dataType: "json", data: {taskid:tid}, success: function(task) {alert(task.name);} }); } } </script> </body> </html> What is happening is when the ajax function is called, the PHP runs fine and the mySQL adds the necessary data to the table, but the success function is not running. Here is the referenced PHP (taskcheck.php): PHP Code: session_start(); $connect = mysql_connect('x', 'x', 'x') or die('Not Connecting'); mysql_select_db('x') or die ('No Database Selected'); $task = $_REQUEST['taskid']; $uid = $_SESSION['user_id']; $q = "SELECT task_id, taskname FROM tasks WHERE task_id=" .$task. " LIMIT 1"; $gettask = mysql_fetch_assoc(mysql_query($q)); $q = "INSERT INTO user_tasks (ut_id, user_id, task_id, taskstatus, taskactive) VALUES (null, " .$uid. ", '{$gettask['task_id']}', 0, 1)"; $puttask = mysql_fetch_assoc(mysql_query($q)); $json = array( "name" => $gettask['taskname'] ); $output = json_encode($json); echo $output; If you have any more questions about the problem please let me know, and any suggestions or comments would be greatly appreciated. Thanks! Similar TutorialsI have to display a div before firing a sync ajax in javascript div is getting displayed in firefox but not in IE and chrome. I need to basically display a download bar to indicate the user that the request is in progress Hi, I am hoping I just need to be pointed in the right direction with this. I have Page1. When Page1 body onloads it uses Ajax to call PartA Within PartA I have a message board so members can write messages which will be sent to my database in PartA[1] and immediately posted for view on to PartA[2]. As I want to have my request to the server updating regularly I want to have PartA[2] on a timed loop to refresh - I do not need the content of PartA[1] to refresh. So the order of events would look like this: Page1 | onload call | v PartA / \ V V PartA[1] PartA[2] (loads once) (constantly refreshes) What I am not sure about is that I have <body> and <head> attributes in Page1 only. I have already used my body onload to call PartA (and can't use it to call PartA[2] before PartA has loaded anyway). I do not want the user to have to click a button or do anything to call up PartA[2]. So my question is how would I get PartA[2] to automatically load within PartA? I hope I have made this clear, but if I haven't let me know and I will try again. Hi, I've created a function that calls to get data from my MySQL database. If there is no data in my MySQL database, I want the page to just keep refreshing and then if it finds the data, I want it to echo it to the page. I'll post my code below and it'll give you an idea of what's going on. <script src="jquery.js" type="text/javascript"></script> <script type="text/javascript"> $.ajax({ url: 'retrieve.php', data: "", dataType: 'json', success: function(data) { var videoid = data[0]; if (videoid == false) { setTimeout("location.reload(true);",1000); } else { $('#youtube').html("<iframe width='400' height='225' src='http://www.youtube.com/embed/"+videoid+"?rel=0&autohide=1&showinfo=0' frameborder='0' allowfullscreen></iframe>"); } } }); </script> </head> <body onload="$.ajax();"> <div class="container"> <div id="youtube"> <!----- checkServer() output appears here !-----> </div> </div> </body> So as you can see the idea is that if there is a video id present in the database, it echoes the embed code for the YouTube video. If the database is empty, it just keeps refreshing the page. However this not what's happening. At the moment it just keeps echoing an empty YouTube video onto the page. I think it has something to do with my if and else syntax? Thanks for any help you can give. Also I apologize in advance if this a retarded way of doing things. I just need a basic proof concept before I make this code work any better. Scenario: Client Side : Simple functions that have events tied to different elements. Each time an event is triggered the function begins an Ajax call to an external server side page filled with JS functions. Server Side : Our client side AJAX call sends the name of the function we want to call out on this file. Once called and performed, it returns DOM edits that could be fired once our client side page receives the data back from Ajax. I know that data being returned from Ajax is always a string. But would it be possible? I mean could the server side file send out commands or rather DOM edits that the client side could pick up on and perform? I am almost 100% certain the answer is no due to JS needing to be cached in the browser and what not, but I figured I would ask the experts anyways. BTW: objective is to move sensitive core JS functions to prevent online application theft... without Flex or Air. I wrote a function (shown below) that is to take numbers from <div> tags add them up and display the value in a different <div> tag. It also prints the total in a hidden input tag to be sent when submitted. All was working fine until today I noticed that the total was no longer showing up in either the <div> tag or the hidden input tag. on change of any of the select menus correctly displays the expected value in its corresponding <div> tag I have no Idea what might be causing this, so I need fresh eyes. (My JavaScript skills are way below my php skills, I can't see anything wrong with what I have) PHP Code: // I am using a php function that spits out these // (one for each item listed in the JS function: <select name="body" onchange="document.getElementById('total_body').innerHTML = this.options[this.selectedIndex].getAttribute('cost_body');calcTotal();" id="frm"> <option value="2" cost_body="0">2</option> <option value="3" cost_body="10">3</option> <option value="4" cost_body="20">4</option> <option value="5" cost_body="30">5</option> <option value="6" cost_body="40">6</option> <option value="7" cost_body="65">7</option> </select> //Which displays in: <div id="total_body">0</div> //AND Calls this JavaScript Function: <script type="text/javascript"> function calcTotal(){ var numVal1=parseInt(document.getElementById("total_body").innerHTML); var numVal2=parseInt(document.getElementById("total_agility").innerHTML); var numVal3=parseInt(document.getElementById("total_reaction").innerHTML); var numVal4=parseInt(document.getElementById("total_strength").innerHTML); var numVal5=parseInt(document.getElementById("total_charisma").innerHTML); var numVal6=parseInt(document.getElementById("total_intuition").innerHTML); var numVal7=parseInt(document.getElementById("total_logic").innerHTML); var numVal8=parseInt(document.getElementById("total_willpower").innerHTML); var numVal9=parseInt(document.getElementById("total_edge").innerHTML); var numVal10=parseInt(document.getElementById("total_magic").innerHTML); var totalValue = numVal1 + numVal2 + numVal3 + numVal4 + numVal5 + numVal6 + numVal7 + numVal8 + numVal9 + numVal10; document.getElementById("grand_total").innerHTML = totalValue; document.getElementById("point_total").value = totalValue; } </script> //Which until today had been displaying in: <div align="center" id="grand_total">0</div> //AND <input type="hidden" name="point_total" value="" id="point_total"> Here is a page that shows what it is (not) doing. http://rpg.5150press.com/test.php Trying to create an eBay listing template with a form on it. The form will allow the buyer to enter in their ebay ID, item number, and 3 choices. Form is complete, using this javascript for validation: Code: <SCRIPT language=javascript> function validate(){ var ebayid= document.getElementById('ebayid').value; var itemnumber= document.getElementById('itemnumber').value; var choice1= document.getElementById('choice1').value; var choice2= document.getElementById('choice2').value; var choice3= document.getElementById('choice3').value; if (!ebayid){ alert('Ebayid is required!'); document.getElementById('ebayid').focus(); return false; } if (!itemnumber){ alert('Item Number is required!'); document.getElementById('itemnumber').focus(); return false; } if (!choice1){ alert('Choice 1 is required!'); document.getElementById('choice1').focus(); return false; } if (!choice2){ alert('Choice 2 is required!'); return false; } if (!choice3){ alert('Choice 3 is required!'); return false; } return true; } </SCRIPT> I like this because it gives a pop up alert box (with definition) if a field is left empty. Upon success though the user is redirected off the page to a success page. I was told that this has to happen because the .php for the form to work is hosted on my site and the user needs to be redirected to my site in order for the form to work. Since this is the case, I was told I could use javascript to open up a separate window for this to happen, thus allowing the buyer to stay on the eBay listing (and to stay compliant with eBay's html/javascript policy). I have pieced together code from numerous forums to actually do this but there is one flaw. Code: <form action="http://www.mysite.com/test.php" method="post" name="testform" id="testform" onsubmit="window.open('', 'success', 'width=450,height=300,status=yes,resizable=yes,scrollbars=yes'); javascript:return validate();" rel="nofollow" target="success"/> This code not only opens a new window but it opens the new window on any click to the submit button, even if the validation fails. How do I write this so that the new window is only opened when the validation completes all true and not when the validation returns an error/alert box? Additionally... how do I add to the javascript so that the field "ebayid" requires 6 characters and the "itemnumber" requires 12 numbers? I would also like for the form itself to erase after a successful submission to prevent the user from hitting the submit button 100's of times spamming me with email (if it's possible) Thanks Kemble Hi Guys, I'm developing a registration form to be viewed on an iPad, this will be put on display in store for customers to complete. The idea is that once the form has been completed a success message will show in lightbox form (currently using query reveal) and then after a few seconds disappear and the form will be refreshed. Any idea on how to do this? I am using the below code but the obvious error is with the action. "<form name="signup" class="form" id="signup" action="data-reveal-id="myModal"" method="post" onsubmit="return validate_signup(this)">" All help very much appreciated. Hi Friends, I am come with a new query in jQuery. I have a listing form in which the details showed , the View more Details is implemented using Ajax. When Click "+" sign there is a loading image show First then the Result show there ... It's all working Fine , But I need a way to show Error I mean some time Server Response is success with Empty String on that time I need to catch same .... I explain code Below: Code: if(proceed) { $.ajax({ type: "POST", data: "key="+id, dataType: 'json', async: true, url: "<?php echo site_url(); ?>/server/view_serverdet/", beforeSend: function() { $('#view_load'+id).show(); $('#view_load'+id).addClass(class); }, complete: function(){ $('#view_load'+id).hide(); } }, success: function (server_msg) { if (null == server_msg) { var warning = "<font color=\"red\">Unable to load server details</font>"; $('#view_load'+id).html(warning); } else { // Working Fine! } But that error Just Show and Hide ... How I can show that Error there, If you have any idea , pls help me ASAP... Thankfully Anes P.A After months of searching the web, and found nothing about javascript drag and drop kinetic scrolling, I decided to develop it by myself, relying on my flash knowledge, because I was created kinetic scrolling in flash with ease! And now, after learning javascript a little bit and spending almost a week, I finally succeded to create such a thing in javascript! And I'm ready to share it with you, but I need a little help from someone more experienced to fix an small issue ! Here is the code: Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>JavaScript Drag and Drop Tutorial</title> </head> <body onload="borders()"> <div style="position:absolute; left:0%; top:0%; "> <style type="text/css"> .drag { position: absolute; } </style> <div style=" position:absolute; width:100%; height = 100%; left:0%; top: 0%" id="pageContainer"> <input id="1" class="drag" style="width:100px; height:100px; top: 0px" type="submit" value="Drag 'n' throw me"> <input id="2" class="drag" style="width:100px; height:100px; top: 120px" type="submit" value="Drag 'n' throw me"> <input id="3" class="drag" style="width:100px; height:100px; top: 240px" type="submit" value="Drag 'n' throw me"> <pre id="debug"> </pre> </div> <script language="JavaScript" type="text/javascript"> <!-- //Kinetic moving script var x = "" var y = "" var i = 1 var dest_x = "" var dest_y = "" var date = new Date(); var time1=date.getTime(); var Xpos_diff = "" var Ypos_diff = "" var time_diff = "" var objID = "" function kinetic() { var dragobj = document.getElementById(objID); //Keep on moving the image till the target is achieved x = (x - dest_x) * 0.97 + dest_x; y = (y - dest_y) * 0.97 + dest_y; //Move the image to the new location dragobj.style.left = x+'px'; dragobj.style.top = y+'px'; if (i < 1) { window.setTimeout('kinetic()',10); } } //Drag and drop + thtow calculation___________________________________________________________________________________________________ function $(id){ return document.getElementById(id); } var _startX = 0; // mouse starting positions var _startY = 0; var _offsetX = 0; // current element offset var _offsetY = 0; var _dragElement; // needs to be passed from OnMouseDown to OnMouseMove var _oldZIndex = 0; // we temporarily increase the z-index during drag var _debug = $('debug'); // makes life easier InitDragDrop(); function InitDragDrop() { document.onmousedown = OnMouseDown; document.onmouseup = OnMouseUp; } function OnMouseDown(e) { i = 1 // IE is retarded and doesn't pass the event object if (e == null) e = window.event; // IE uses srcElement, others use target var target = e.target != null ? e.target : e.srcElement; objID = ExtractNumber(target.id) var dragobj = document.getElementById(objID); x=dragobj.style.left y=dragobj.style.top dest_x=dragobj.style.left dest_y=dragobj.style.top // for IE, left click == 1 // for Firefox, left click == 0 if ((e.button == 1 && window.event != null || e.button == 0) && target.className == 'drag') { // grab the mouse position _startX = e.clientX; _startY = e.clientY; // grab the clicked element's position _offsetX = x1 = ExtractNumber(target.style.left); _offsetY = y1 = ExtractNumber(target.style.top); // bring the clicked element to the front while it is being dragged _oldZIndex = target.style.zIndex; target.style.zIndex = 10000; // we need to access the element in OnMouseMove _dragElement = target; // tell our code to start moving the element with the mouse document.onmousemove = OnMouseMove; // cancel out any text selections document.body.focus(); // prevent text selection in IE document.onselectstart = function () { return false; }; // prevent IE from trying to drag an image target.ondragstart = function() { return false; }; // prevent text selection (except IE) return false; } } function ExtractNumber(value) { var n = parseInt(value); return n == null || isNaN(n) ? 0 : n; } function OnMouseMove(e) { if (e == null) var e = window.event; // this is the actual "drag code" _dragElement.style.left = (_offsetX + e.clientX - _startX) + 'px'; _dragElement.style.top = (_offsetY + e.clientY - _startY) + 'px'; x=_offsetX + e.clientX - _startX y=_offsetY + e.clientY - _startY dest_x = _offsetX + e.clientX - _startX dest_y = _offsetY + e.clientY - _startY Xpos_diff = (_offsetX + e.clientX - _startX) - x1 Ypos_diff = (_offsetY + e.clientY - _startY) - y1 x1 = _offsetX + e.clientX - _startX y1 = _offsetY + e.clientY - _startY var date = new Date() var time2 = date.getTime(); time_diff = time2-time1 time1 = time2 } function OnMouseUp(e) { if (_dragElement != null) { _dragElement.style.zIndex = _oldZIndex; // we're done with these events until the next OnMouseDown document.onmousemove = null; document.onselectstart = null; _dragElement.ondragstart = null; // this is how we know we're not dragging _dragElement = null; dest_x = x + time_diff * Xpos_diff*3 dest_y = y + time_diff * Ypos_diff*3 i = 0 kinetic() } else{ i = 1 x=_dragElement.style.left y=_dragElement.style.top dest_x=_dragElement.style.left dest_y=_dragElement.style.top } } //--> function borders(){ if(x<0){ dest_x = 0 } else if(x>document.documentElement.clientWidth-100){ dest_x = document.documentElement.clientWidth-100 } if(y<0){ dest_y = 0 } else if(y>document.documentElement.clientHeight-100){ dest_y = document.documentElement.clientHeight-100 } window.setTimeout('borders()',10) } </script> </div> </body> </html> What need to be fixed is an small issue when start dragging the object and then stop moving while you still drag object, after release the mouse in still position the object will make a small move! And that must not happening! You will see by yourself what I meant, just drag and throw object! If you like it you are free to use it! All I want is someone to help fix this issue! From my main page, I have a dropdown-login box. Is it possible login form go to my user's control panel if the login was successful, or go to the login page if it's not? Ideally, I don't want to use a re-direct. Do I need to use ajax? Thank you! Ahoy, Lemme try to explain this as best as I can. Bullet points might help: When someone clicks on an image here (http://gta.kwivia.co.uk/gta-iv/), the rest of the images collapse and become invisible Below the image, some links appear Also, there will be a "show other images" button which will then show the rest of the images http://gta.kwivia.co.uk/gta-iv/ I will appreciate all solutions to this problem. If you need to know anything, simply ask me. Hi, I am facing a problem in passing replace() function as an argument in user defined java function, can any one help me how to resolve it? intention is to pass a file path to my user defined function, but before passing the path i want to replace the character '\' to '\\' I am posting my javascript function he <a href="#" onclick="OpenDocPreview('<%# Eval("PATH")%>'.replace(/\\/g,"\\\\"), '<%# Eval("Filename")%>')"><%# Eval("DocTitle") %></a> function OpenDocPreview(url, docname) { alert('message from search base : ' + url + ' ' + docname); } thank you, I was working on a tutorial for some ajax uploading stuff and I ran across a new function syntax I don't recognize. I am not a Javascript pro, but I am not a newbie either. here is the code I am working on: Code: function handleFileSelect(e){ var files = e.target.files; var output = []; for(var i=0,f;f=files[i];i++){ if(f.type.match('image.*')){ var reader = new FileReader(); reader.onload = (function(theFile){ return function(e){ var span = document.createElement('span'); span.innerHTML = ['<img class="thumb" src="',e.target.result,'" title="',theFile.nbame,'" />'].join(''); document.getElementById('list').insertBefore(span,null); }; })(f); reader.readAsDataURL(f); } } document.getElementById('list').innerHTML = '<ul>'+output.join('')+'</ul>'; } document.getElementById('files').addEventListener('change',handleFileSelect,false); To be a little more clear, the code in question is that is the very middle. The syntax I don't understand is: Code: class.event = (function(arguments){ //stuff you put in a function... })(more Arguments?); I tried to customize a simple one to learn for myself and I wrote this: Code: var a = 'A'; var b = 'B'; test = (function(t){ alert(t); alert(b); })(b); test(a); The browser would alert 'B' and that's it. The console would tell me that 'test is not a function.' OK, so I am confused. The topmost code works. What I am wondering is what the syntax is called for creating a function (or event listener?) that way, and how it works. Although if I new what it was called I could just google how it works. i keep getting error Call to undefined function codeandurl() below is my code PHP Code: <?php $value= strip_tags(get_field('link',$post)); $resultid=get_field('resultid',$post); codeandurl($resultid,$value); ?> <div id="result"></div> <script type="text/javascript"> function codeandurl(resultid,url){ $( "#result" ).text(resultid); $( "#result" ).dialog({ modal: true, buttons: { Ok: function() { $( this ).dialog( "close" ); } } }); window.open(url); return false; } </script> <p> <script type="text/javascript">// <![CDATA[ var metrics = { "mm" : 1, "cm" : 10, "m" : 1000, "inch" : 25.4, "foot" : 304.8 }; function convert(num, dec){ var val = document.getElementById("fromVal").value; if(isNaN(val)){ return } function roundNumber(num, dec) { var result = Math.round( Math.round( num * Math.pow( 10, dec + 1 ) ) / Math.pow( 10, 1 ) ) / Math.pow(10,dec); return result; } document.getElementById("toVal").value = val * metrics[document.getElementById("fromSystem").value]/ metrics[document.getElementById("toSystem").value]; } var interval = null; function watchChanges(){ interval == null ? setInterval("convert()", 500) : clearInterval(interval); } // ]]></script> </p> <table> <tbody> <tr> <td><input id="fromVal" style="width: 100px;" onfocus="watchChanges()" onblur="watchChanges()" type="text" /><select id="fromSystem" onchange="convert()"> <option value="mm">millimeters</option> <option selected="selected" value="cm">centimeters</option> <option value="m">meters</option> <option value="foot">feet</option> <option value="inch">inches</option> </select></td> </tr> <tr> <td colspan="1" align="center">=</td> </tr> <tr> <td><input id="toVal" style="width: 100px;" type="text" disabled="disabled" /><select id="toSystem" onchange="convert()"> <option value="mm">millimeters</option> <option value="cm">centimeters</option> <option value="m">meters</option> <option selected="selected" value="foot">feet</option> <option value="inch">inches</option> </select></td> I found this script, and it works great: Code: <script type="text/javascript"> function disable(element) { var input = document.getElementById(element).getElementsByTagName("input"); for(var i = 0; i < input.length; i++) { input[i].setAttribute("disabled","true"); } } </script> I tried to make the inverse by simply reversing the setAttribute() like so: Code: <script type="text/javascript"> function enable(element) { var input = document.getElementById(element).getElementsByTagName("input"); for(var i = 0; i < input.length; i++) { input[i].setAttribute("disabled","false"); } } </script> But that didn't do it. Can someone show me why, and how to fix it? Here's the sample form which I'm trying to test it on: Code: <form> <input type="radio" name="test" onclick="disable('D1')" /> disable<br/> <input type="radio" name="test" onclick="enable('D1')" /> enable<br/> <fieldset id="D1"> <input class="" type="text" value="test value1" /><input class="" type="text" value="test value2" /><br/> <input class="" type="text" value="test value3" /><input class="" type="text" value="test value4" /><br/> <input class="" type="text" value="test value5" /><input class="" type="text" value="test value6" /><br/> </fieldset> </form> Edit: The ultimate goal which I'm working toward now (step by step =) is to have a form more like: Code: <form> <input type="radio" name="test" onclick="disable('D1')" /> <fieldset id="D1"> <input class="" type="text" value="test value1" /><input class="" type="text" value="test value2" /> </fieldset> <input type="radio" name="test" onclick="disable('D2')" /> <fieldset id="D2"> <input class="" type="text" value="test value3" /><input class="" type="text" value="test value4" /> </fieldset> <input type="radio" name="test" onclick="disable('D3')" /> <fieldset id="D3"> <input class="" type="text" value="test value5" /><input class="" type="text" value="test value6" /> </fieldset> </form> And have the fieldsets enable and disable according the selection of the radio buttons. Also, the fieldsets (and their ID's) will be dynamically generated via PHP Thanks-a-bunch, ~ Mo Hi All, I'm trying to convert an anonymous function to a real function (nesting is getting out of hand), however the msg object becomes undefined after conversion. Here is the converted anonymous function which fails: https://gist.github.com/2587613 and here is the original anonymous function which works: https://gist.github.com/2587667 Any help would be greatly appriciated Hi! I'm trying to toggle a class and one works and the other does not and I don't know why. I'm just getting my feet wet with jquery and javascript and I figured this was a pretty easy task to take on! Maybe. Link to the page: Franklin Township Soccer Club - Change Field Status My sad, sorry attempt =| Code: $( "li.open" ).click(function() { $( this ).toggleClass( "closed" ); }); $( "li.closed" ).click(function() { $( this ).toggleClass( "open" ); }); The first function works with open, so I figured I'd just use opposite on closed! Ha! I don't think so! In the end within those function there is an element in a form on that page it's hidden. I'd like to change the value from a 0 to 1 for vice versa. That' will be my next step. If you could give me a little nudge in the right direction I'd appreciate it! But first understanding why one works and the other does not, that is the primary mission! I do appreciate any help given! Dave How can I call a PHP Function inside a Javascript Function? This is what I have so far, but I don't think I'm doing it the right way. Any suggestions? PHP Code: <?php function phpQuery(){ $query = mysql_query("INSERT INTO mytable VALUES('','name','email')"); } ?> <script type="text/javascript"> function delayQueries() { timeoutID = window.setTimeout(doQueries, 2000); } function doQueries() { var runQuery = "<?php phpQuery(); ?>"; } </script> Thank you in advance if someone can help. I have been banging my head against the wall for hours now. Here is the code: Code: for (var i = 0; i < BS_crm['activityTypes'].length; i++) { var clickFunc = function(){ activityList.showForm( -1, {blockType:[""+BS_crm['activityTypes'][i]['id'], "0"]} ); }; var type = { value: BS_crm['activityTypes'][i]['id'], label: "Add New "+BS_crm['activityTypes'][i]['label'], css: BS_crm['activityTypes'][i]['css']+"_16", onClick: clickFunc }; previewLinks.items.push( type ); } Now, basically what I am doing here is running through one array to create an array of objects, that will be used to create links that will use whatever onClick function I pass it. The problem is that on the second line I need the BS_crm['activityTypes'][i]['id'] to be a value, not a reference. If that line was simply changed to: Code: var clickFunc = function(){ activityList.showForm( -1, {blockType:["3", "0"]} ); }; then everything would work as I need. How can I make this happen? I would really appreciate any help. Thank you again in advance. |