AJAX being stubborn? - javascript

I've been struggling with some AJAX. Here's my code, if anyone could point me in the direction of where I'm going wrong it would be a great help!
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<!DOCTYPE html>
<head>
<meta charset="UTF-8"></meta>
<style media="print">
#goBack,
#printRow {
display: none;
}
</style>
</head>
<body id="body" class="body">
<table>
<form id="addUser" onsubmit="return false;">
<tr>
<td>Username:</td>
<td>
<input name="user" />
</td>
<td rowspan="2">
<button id="createUser" name="submit" onclick="getAddUserStatus()">Add User</button>
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input name="pass" type="password" />
</td>
</tr>
</form>
</table>
<div id="container" class="container">
div contents here
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src=""></script>
<script>
function getAddUserStatus() {
$('#addUser').on('submit', function() {
var postData = $(this).serializeArray();
$.ajax({
url: 'response.php',
data: postData,
type: "POST",
}).done(function(data) {
console.debug(data);
marker = JSON.stringify(data.message);
console.debug(marker);
alert(marker);
$('.container').html(marker); // Or whatever
});
});
}
</script>
</body>
</html>
Basically where I'm asking for help is that I need to write the response of the json to the DIV, an example json response is
Object {
saved: false,
user: "discoverexcel",
message: "User already exists"
}
I've figured out how to obtain just "message" from it and throw it into an alert, but no luck with the DIV. I'm not sure where I'm going wrong at all.
Next big thing is, why is the page reloading? I was under the impression that was a good reason to use AJAX, so anything here is greatly appreciated as well!
Also, my last question is, if I was to do multiple ones of these on a page, how would I go about doing so? Nesting each one in a new function for each time they're clicked? Also, what about a loading image to appear to show the status?

Yay! I finally got it, thanks all for the supportive help! To clarify, the answer I found here:
Ajax response inside a div
The selector should be .result not #result
It's the little things, thanks all!

Related

Show html data from a JS Table in a <h2/> title

I have a JS table generated by the data entered in textareas by users on my web site (so the data is not there when you first load the page: your have to enter something in the textarea and then generate the table). Now I'm trying to get that data (from the generated table) and show it in a (h2/) for exemple.
So I made a script to get that information:
<script type="text/javascript">
function buttonTEST()
{
document.getElementById('excel_table1').getElementsByTagName('tr')[0].cells[1].innerHTML;
}
</script>
and a Button to use that script:
<input id=GetTest type="button" onclick="buttonTEST()" value="TEST ME"/>
When I enter the "document.getElementById....etc" in the console, it shows the data that I want so I think the script is fine.
But how can I get it to SHOW that data (alphanumeric) in a (h2) plain text?
Can someone help? :)
EDIT! I tried this:
<div>
<script type="text/javascript">function buttonTEST(){document.getElementById("yourID").innerHTML="document.getElementById('excel_table1').getElementsByTagName('tr').
[0].cells[1]";
}
</script>
<h2 id="yourID"></h2>
<input id="anotherID" type="button" onclick="buttonTEST()" value="TEST ME"/>
</div>
But when I click, I just get "document.getElementById('excel_table1').getElementsByTagName('tr')[0].cells[1]" as a H2.
The problem in your case, seems to be the extra " around your expression to get the value.
If a value is already a string, you don't need to wrap it in quotes, since doing so makes javascript think that you want to litteraly write that piece of code to the h2 output
<div>
<script type="text/javascript">
function buttonTEST() {
document.getElementById("yourID").innerHTML = document.getElementById('excel_table1').getElementsByTagName('tr').
[0].cells[1].innerHTML;
}
</script>
<h2 id="yourID"></h2>
<input id="anotherID" type="button" onclick="buttonTEST()" value="TEST ME"/>
</div>
Ok, solved it ! Thanks everybody for putting me in the right track :D
So, what worked for me:
<script type="text/javascript">
function buttonTEST()
{
document.getElementById('yourID').innerHTML=document.getElementById('excel_table1').getElementsByTagName('tr')[0].cells[1].innerHTML;
}
</script>
<h2 id="yourID"></h2>
<input id="anotherID" type="button" onclick="buttonTEST()" value="TEST ME"/>
</div>
#vhoyer was right, I needed to take off the extra " otherwise JS thinks that I want to litteraly write that piece of code to the h2 output.
And the other think is that I needed to put ".innerHTML" again after all my tr and cells (yes, it makes a .innerHTML inside another .innerHTML xD )
Hope that might help someone!
Cheers
You need to create a <h2> element in your html file to replace its value (which should be empty in your html file) using javascript.
Make sure you have assigned that <h2> an id.
Then, using document.getElementById, access it in your script and change it.
An example below.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>title</title>
</head>
<body>
<h2 id="yourID"></h2>
<input id="anotherID" type="button" onclick="buttonTest()" value="TEST ME"/>
<script>
function buttonTest() {
//Grab the ID and change it
document.getElementById("yourID").innerHTML = "whatever you want it to display";
}
</script>
</body>
</html>
Also, make sure to surround the html attributes' values in single or double quotes.
Edit:
Here is an example for your use case:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>title</title>
</head>
<body>
<h2 id="yourID"></h2>
<input id="anotherID" type="button" onclick="buttonTest()" value="TEST ME" />
<p>Press me to find out the second cell in the second row</p>
<table id="table">
<tr>
<th>Color</th>
<th>Object</th>
</tr>
<tr>
<td>Red</td>
<td>Poppy</td>
</tr>
</table>
<script>
function buttonTest() {
//Here we grab the value of the second cell in the second row in a variable called value. You can change the row and cell index to access specific values.
var value = document.getElementById("table").rows[1].cells[1].innerHTML;
//Then we display it
document.getElementById("yourID").innerHTML = value;
}
</script>
</body>
</html>

Can't get Jquery to work correctly outside of JSFiddle

I have a basic table that I am creating from text input and when you click the "addTask" button it adds a tr with an empty text box and clicking the "delTask" button should delete the rows from the table that have checkboxes checked.
Everything works perfectly in JSFiddle (except the line to render last textbox readonly which only works outside of JSFiddle) but when I try to test the code out live the "delTask" button does not work correctly. It will delete all rows except the first one in the table.
I'm fairly new to JQuery so please don't judge if it's something simple but I have really searched for an answer and tried everything I could find. Can anyone help me figure out what is wrong here? Thanks in advance.
EDIT I have fixed the initial issue of the delTask button not working at all by changing $(":checkbox[checked='true']") to $(".checkbox:checked") when testing outside of JSFiddle but still cant get the button to delete the first row on the table in a live test.
JSFiddle link: http://jsfiddle.net/2aLfr794/14/
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
</head>
<body>
<table id="tasks" cellpadding="3" cellspacing="3" border="0">
<tr>
<td><input type="checkbox"></td>
<td><input type="text" class="text"></td>
</tr>
</table>
<br>
<input type="button" id="addTask" value="Add Task" />
<input type="button" id="delTask" value="Delete Tasks" />
<script>
$("#addTask").click(function(){
var newTxt = $('<tr><td><input type="checkbox"></td><td><input type="text" class="text"></td></tr>');
$(".text").last().prop("readonly", true);
$("#tasks").append(newTxt);
});
$("#delTask").click(function(){
$(".checkbox:checked").each(function(){
var curTask = $(this).parents('tr');
curTask.remove();
});
});
</script>
</body>
</html>
Your Issues:
1.You are not assigning class checkbox to default checkbox and dynamically created checkboxes.
2.To access a checked element the syntax is $(".checkbox[checked='checked']")
Your Updated Code:
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<body>
<table id="tasks" cellpadding="3" cellspacing="3" border="0">
<tr>
<td>
<input type="checkbox" class="checkbox">
</td>
<td>
<input type="text" class="text">
</td>
</tr>
</table>
<br />
<input type="button" id="addTask" value="Add Task" class="addSubmit" />
<input type="button" id="delTask" value="Delete Selected Tasks" />
<script>
$("#addTask").click(function() {
var newTxt = $('<tr><td><input type="checkbox" class="checkbox"></td><td><input type="text" class="text"></td></tr>');
$(".text").last().prop("readonly", true);
$("#tasks").append(newTxt);
});
$(document).ready(function() {
$("#delTask").click(function() {
console.log($(".checkbox[checked='checked']"))
$(".checkbox:checked").each(function() {
var curTask = $(this).parents('tr');
curTask.remove();
});
});
});
</script>
</body>
if you get "$ is not defined" error, try writing
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> as <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
Note the "http:" before "//cdnjs" which is needed when you are running those from local machine, and not a webserver. At least it was always required for me.
$("input[type=checkbox]:checked")
worked for me

Assistance with rebinding jQuery following dynamic loaded AJAX content

Basically I have a page that has a drop down <select> listing a number of items / models which when selected triggers an AJAX call to dynamically display a form with all the details pertaining to that model to allow editing and updating.
<script type="text/javascript">
function item_loader(x) {
req = $.ajax({
type: "GET",
url: x,
datatype: "html",
success: function(data){
$('#item_table').html(data);
}
});
}
</script>
Within the form I have a "preview" button which displays dialog popup giving a preview of how the item will be displayed.
<script>
$(function(){
$("#wrapper").dialog({
autoOpen:false,
width:780,
height:800,
title: 'Item Preview'
});
$("#opener").click(function() {
$("#wrapper").dialog("open");
});
});
</script>
Everything works as intended when the page is loaded or refreshed, but the dialog portion breaks when the original content is dynamically updated/changed via AJAX. Doing research on this I'm finding old references suggesting modifying the code to use live(), but have read that is deprecated and to use on()? I am still fairly new to all of this and from the examples I've found on the net going through trial and error has always ended up in error. Hoping someone can share a resource or possibly offer some assistance. Thank you.
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>Basic Page</title>
<script type="text/javascript" src="/JS/jquery-1.10.2.js"></script>
<script type="text/javascript" src="/JS/jquery-ui-1.10.4.custom.js"></script>
<script type="text/javascript" src="/JS/jquery-ui-1.10.4.custom.min.js"></script>
<script type="text/javascript" src="/JS/tinymce/tinymce.min.js"></script>
<link rel="stylesheet" type="text/css" href="/css/intranet-theme/jquery-ui-1.10.4.custom.css"/>
<script type="text/javascript">
function item_loader(x) {
req = $.ajax({
type: "GET",
url: x,
datatype: "html",
success: function(data){
$('#item_table').html(data);
}
});
}
</script>
<script>
$(function(){
$("#wrapper").dialog({
autoOpen:false,
width:780,
height:800,
title: 'Item Preview'
});
$("#opener").click(function() {
$("#wrapper").dialog("open");
});
});
</script>
</head>
<body bgcolor='#FFFFFF'>
<form>
<select name="period_select" id="item_dropdown" onChange="javascript:item_loader(this.value);">
<option value="Item_AJAX.php?Model_ID=0"> Choose Model</option>
<option value="Item_AJAX.php?Model_ID=404">AEROCOOL 100</option>
</select>
</form>
<div id="item_table" align="center">
<!-- Start of AJAX Dynamic Content -->
<form method="POST" enctype="multipart/form-data" action="" name="model_item">
<input name="Start_Special" type="hidden" value="2014-06-01"/>
<input name="Model_ID" type="hidden" value="model_id"/>
<table border="1" width="800">
<tr>
<td colspan="3" align="center">
[Form displaying item details for editing]
</td>
</tr>
<tr>
<td align="center" colspan="2">
<input type="submit" name="Update_Model" value="Save Model Info"/>
<input type="submit" name="Update_Listing" value="Update Listing"/>
<input type="submit" name="Delete" value="Remove Item"/>
<button type="button" id="opener">Preview</button>
<div id="wrapper" align="center">
<!-- Start of Hidden diolog Content -->
[Hidden Preview Content]
<!-- End of Hidden dialog Content -->
</div>
</td>
</tr>
</table>
</form>
<!-- End of AJAX Content -->
</div>
</body>
</html>
Either you can rebind in success method of ajax:
success: function(data){
$('#item_table').html(data);
$("#wrapper").dialog({
autoOpen:false,
width:780,
height:800,
title: 'Item Preview'
});
$("#opener").click(function() {
$("#wrapper").dialog("open");
});
}
or you can try with event delegation:
$("#wrapper").on("click", "#opener", function() {
$("#wrapper").dialog("open");
});
i guess you have #opener in #wrapper element. if not then try to delegate to the closest parent or to $(document).
Change:
$("#opener").click(function() {
$("#wrapper").dialog("open");
});
To:
$(document).on("click", "#opener", function() {
$("#wrapper").dialog("open");
});
$("#elem").click() only binds to the elements currently on the page. Placing the event on the document itself will allow the event to work on newly created elements.

innerHTML javascript changing

I am trying to make this code work, I want the innerHTML to be changed but It's instantly changing and gets back to its initial state . Any help ?
<!DOCTYPE html>
<html>
<head>
<script>
function click_me(){
alert('fdsfs');
var tweety=document.getElementById('text_this').innerHTML;
alert(tweety);
var text_area="<input type=text value='"+tweety+"'>";
alert(text_area);
document.getElementById('text_this').innerHTML=text_area;
}
</script>
</head>
<body>
<form name="form1">
<table border=1>
<tr>
<td>
<div id="text_this">123</div>
</td>
<td>
<button onclick="click_me();">Edit</button>
</td>
</tr>
</body>
</html>
Your form is getting submitted. Add a return false; to your button onclick event.
<button onclick="click_me(); return false;">Edit</button>
Or, make the button type='button' (This is the better option)
<button onclick="click_me();" type='button'>Edit</button>
The reason is because the button type is submit by default if a type is not specified.
From MDN,
submit: The button submits the form data to the server. This is the
default if the attribute is not specified, or if the attribute is
dynamically changed to an empty or invalid value.
<!DOCTYPE html>
<html>
<head>
<script>
function click_me(){
alert('fdsfs');
var tweety=document.getElementById('text_this').innerHTML;
alert(tweety);
var text_area="<input type=text value='"+tweety+"'>";
alert(text_area);
document.getElementById('text_this').innerHTML=text_area;
}
</script>
</head>
<body>
<form name="form1">
<table border=1>
<tr>
<td><div id="text_this">123</div></td>
<td><button onclick="click_me();return false;">Edit</button></td>
</tr>
</table>
</form>
</body>
</html>
added a return false statement to the onclick event. without it, the form gets submitted and the page reloads
jsfiddle here

Web forms: body onload event can't find a Javascript function

I come from MVC background and I have little experience with web forms.
I have established where the problem is, but so far I have been unable to fix this.
I have a form which is meant to execute Javascript function when body of the form loads. Please notice that head tag has a run at server attribute as it needs to use Request.QueryString.
The code is below:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type="text/javascript">
function doSomething()
{
// Use web forms to do something
var foo = <%= Request.QueryString["input"] %>;
}
</script>
<title>Foo</title>
</head>
<body onload="doSomething()">
<form id="MainForm" runat="server">
<table width="272px" border="0" cellpadding="0" cellspacing="0">
<tr>
<td class="body">
...
</td>
</tr>
</table>
</form>
</body>
</html>
I get the following error:
SCRIPT5007: The value of the property doSomething is null or undefined, not a Function object.
My guess is that something executes on a server or other way round. This has worked previously (over a year ago), so potentially something in a web config was overwritten. I have spent the most of day on this and had no luck so far.
Edit: Generated output is below
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function doSomething()
{
debugger;
var o = crmForm.queryString;
}
</script>
<title></title>
</head>
<body onload="doSomething()">
<form name="MainForm" method="post" action="fooPage.aspx?input=queryString" id="MainForm">
<div>
// hidden fields
<table width="272px" border="0" cellpadding="0" cellspacing="0">
<tr>
<td class="body">
// inputs
</td>
</tr>
</table>
</form>
</body>
</html>
Instead of using the onload attribute of the body tag, you can also add the following code within the <script> tags:
if(window.addEventListener) window.addEventListener("load", doSomething, true);
else window.onload = doSomething;

Categories

Resources