jQuery not executing .then() - javascript

I am having trouble with a .when() .then() call in jQuery.
I am a teacher taking attendance in class by scanning student IDs. So I have a form that the ID scanner successfully populates and then hits the submit button. This successfully triggers a .when() call and the .ajax() successfully calls my code that populates a Google Sheet.
What I want is a list of students that I have successfully scanned to appear at the bottom of the page. I try to append to this list in the .then() call but it doesn't seem to execute.
<!DOCTYPE html>
<html>
<head>
<title>Student Automations</title>
<!--[if IE]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
<link rel="stylesheet" type="text/css" href="../css/main.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('button').click(function() {
var student = $('#studentId').val();
var response;
$.when(
$.ajax('/logAttendance.php', {
type: 'POST', // http method
data: {
studentId: $('#studentId').val(),
spreadsheetId: $('#spreadsheetId').val(),
worksheet: $('#worksheet').val(),
studentIdCol: $('#studentIdCol').val()
}, // data to submit
success: function(data, status, xhr) {
response = student + " - added sucessfully";
},
error: function(jqXhr, textStatus, errorMessage) {
response = student + " - something went wrong";
}
})
).then(function(response) {
$('#listOfScanned').append('<li>' + response + '</li>'); //does not work
return false;
})
});
});
</script>
</head>
<body>
<form id='studIdForm'>Student ID: <input type='text' name='studentId' id='studentId' value=''>
<input type='hidden' name='spreadsheetId' value='mygooglesheetid' id='spreadsheetId'>
<input type='hidden' name='worksheet' value='Sheet1' id='worksheet'>
<input type='hidden' name='studentIdCol' value='A' id='studentIdCol'>
<button>Submit</button>
</form>
<script type='text/javascript' language='JavaScript'>
document.forms['studIdForm'].elements['studentId'].focus();
</script>
<p>Already scanned:</p>
<ul id="listOfScanned">
</ul>
</body>
</html>
Edit:
Thank you all for so much quick input. I had a few things wrong, including the fact that the URL that I was calling was not returning JSON which meant that the success: statements were not being called. I removed the .when and have added some bells and whistles and ended up with this.
<!DOCTYPE html>
<html>
<head>
<title>Student Automations</title>
<!--[if IE]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
<link rel="stylesheet" type="text/css" href="../css/main.css" />
</head>
<body>
<form id='studIdForm'>Student ID: <input type='text' name='studentId' id='studentId' value=''>
<input type='hidden' name='spreadsheetId' value='mygooglesheetid' id='spreadsheetId'>
<input type='hidden' name='worksheet' value='Sheet4' id='worksheet'>
<input type='hidden' name='studentIdCol' value='A' id='studentIdCol'>
<button>Submit</button>
</form>
<script type='text/javascript' language='JavaScript'>document.forms['studIdForm'].elements['studentId'].focus();</script>
<p>Already scanned:</p>
<ul id="listOfScanned">
</ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function()
{
$('button').click(function(e){
e.preventDefault();
var student = $('#studentId').val();
$('#studentId').val('');
$.ajax('/logAttendance.php', {
type: 'POST', // http method
data: { studentId: student,
spreadsheetId: $('#spreadsheetId').val(),
worksheet: $('#worksheet').val(),
studentIdCol: $('#studentIdCol').val()
}, // data to submit
success: function (data, status, xhr) {
$('#listOfScanned').prepend('<li>'+ student + ' - added sucessfully</li>');
return false;
},
error: function (jqXhr, textStatus, errorMessage) {
$('#listOfScanned').preppend('<li>'+ student + ' - something went wrong</li>');
return false;
}
});
$('#listOfScanned').find('li').eq(3).remove();
$('#listOfScanned').find('li').eq(4).remove();
$('#listOfScanned').find('li').eq(5).remove();
});
});
</script>
</body>
</html>

Related

why when i reload a page using AJAX the data disappears

Basically i find code on the internet to test and use it.
the problem is that when i reload the page, the data disappears.
what i want to happen is for the data or the value to just stay.
Thanks guys
Here is the code in index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pass Data to PHP using AJAX without Page Load</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script
src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<h2>Enter Some Data Pass to PHP File</h2>
<div class="row">
<div class="col-md-3">
<form>
<div class="form-group">
<input type="text" id="pass_data" class=" form-control">
<input type="button" class="btn btn-success" onclick="passData();" value="Set">
<p id="message"></p>
</div>
</form>
</div>
</div>
</div>
</body>
<script type="text/javascript">
function passData() {
var name = document.getElementById("pass_data").value;
var dataString = 'pass=' + name;
if (name == '') {
alert("Please Enter the Anything");
} else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
cache: false,
success: function(data) {
$("#message").html(data);
},
error: function(err) {
alert(err);
}
});
}
return false;
}
</script>
</html>
and here is my php code
<?php
$pass=$_POST['pass'];
echo json_encode($pass);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pass Data to PHP using AJAX without Page Load</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script
src="https://code.jquery.com/jquery-2.2.4.js"
integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<h2>Enter Some Data Pass to PHP File</h2>
<div class="row">
<div class="col-md-3">
<form>
<div class="form-group">
<input type="text" id="pass_data" class=" form-control">
<input type="button" id="success" class="btn btn-success" value="Set">
<p id="message"></p>
</div>
</form>
</div>
</div>
</div>
</body>
<script type="text/javascript">
$("#success").click(function () {
var name = document.getElementById("pass_data").value;
var dataString = 'pass=' + name;
if (name == '') {
alert("Please Enter the Anything");
} else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
cache: false,
success: function (data) {
$("#message").html(data);
localStorage.setItem("data",data);
},
error: function (err) {
alert(err);
}
});
}
return false;
})
$(document).ready(function () {
var someVarName = localStorage.getItem("data");
console.log(someVarName)
$("#message").html(someVarName);
});
</script>
</html>
First of all i changed your js code to use more jquery syntax, as you already have included it (i trigger the on click event on the script and i don't put it in in html). After that in order not to lose your variable after refresh on ajax success i pass the value of data to localstorage, and after refresh (on document ready) i retrieve it and display it in the label.
Of course every time you put a new value and display it, it over-writes the previous one, so after refresh you display the latest value put in your input field.
I am not sure I understand what you mean but...
Before this line:
<!DOCTYPE html>
enter
<?php session_start(); ?>
In this line add
<input type="text" id="pass_data" class=" form-control" value="<?php echo $_SESSION['VAL']; ?>">
and in your php file:
<?php session_start();
$pass=$_POST['pass'];
$_SESSION['VAL'] = $pass;
echo json_encode($pass);
?>

Access the php value on the same page using jquery and ajax

i am trying to echo the value entered by the user in the input tag using jquery and ajax .
the following is my code
< script src = "//code.jquery.com/jquery-1.11.0.min.js" > < /script> <
script type = "text/JavaScript" >
function showMessage() {
var message = document.getElementById("message").value;
$.ajax({
url: 'value_pass.php',
type: 'GET',
data: {
var_PHP_data: message
},
success: function(data) {
alert("success");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
//case error
}
});
} <
/script>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
Enter message: <input type="text" id="message">
<input type="submit" onclick="showMessage()" value="submit" />
<?php echo "hi".$_GET['var_PHP_data'];?>
</body>
</html>
My php script is:
<?php
echo "hi".$_GET['var_PHP_data'];
?>
the code alert the success prompt , but i am not able to access the value using GET , any pointers on what i am doing wrong.
If you are doing this on same page add your php script at the top of the page that handle your ajax request
Like this
<?php if(isset($_GET['var_PHP_data'])){
echo "hi".$_GET['var_PHP_data'];
die;
}?>
<!-- rest of your html code start from here -->
<!DOCTYPE html>
<html>
<head>
</head>
<body>
Enter message: <input type="text" id="message">
<input type="submit" onclick="showMessage()" value="submit" />
</body>
</html>
If you using ajax, follow below code
<!DOCTYPE html>
<html>
<head>
</head>
<body>
Enter message: <input type="text" id="message">
<input type="submit" onclick="showMessage()" value="submit" />
<span id = 'PHP_data'></span>
</body>
</html>
<script src = "//code.jquery.com/jquery-1.11.0.min.js" > < /script>
<script type = "text/JavaScript" >
function showMessage() {
var message = document.getElementById("message").value;
$.ajax({
url: 'value_pass.php',
type: 'GET',
data: {
var_PHP_data: message
},
success: function(data) {
message1 = "Hi "+message
$('#PHP_data').html(message1);
alert("success");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
//case error
}
});
}
</script>
If you are using form submit use below code
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method ='GET'>
Enter message: <input type="text" id="message" name = "message">
<input type="submit" value="submit" />
<?php if(isset($_GET['message'])){
echo "hi".$_GET['message'];
die;
} ?>
</form>
</body>
</html>

How to filter xml data according to the search?

<pages>
<link>
<title>HTML a tag</title>
<url>http://www.w3schools.com/tags/tag_a.asp</url>
</link>
<link>
<title>HTML br tag</title>
<url>http://www.w3schools.com/tags/tag_br.asp</url>
</link>
<link>
<title>CSS background Property</title>
<url>http://www.w3schools.com/cssref/css3_pr_background.asp</url>
</link>
<link>
<title>CSS border Property</title>
<url>http://www.w3schools.com/cssref/pr_border.asp</url>
</link>
<link>
<title>JavaScript Date Object</title>
<url>http://www.w3schools.com/jsref/jsref_obj_date.asp</url>
</link>
<link>
<title>JavaScript Array Object</title>
<url>http://www.w3schools.com/jsref/jsref_obj_array.asp</url>
</link>
</pages>
this is the sample xml data which i am parsing and getting the output from
SEARCH.HTML
<!DOCTYPE html>
<html>
<head>
<link
href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.js"></script>
<script>
$(document).ready(function () {
var myArr = [];
$.ajax({
type: "GET",
url: "http://localhost/category/links.xml",
dataType: "xml",
success: parseXml,
complete: setupAC,
failure: function (data) {
alert("XML File could not be found");
}
});
function parseXml(xml) {
//find every query value
$(xml).find("link").each(function () {
myArr.push($(this).find('title').text());
});
}
function setupAC() {
$("input#searchBox").autocomplete({
source: myArr,
minLength: 3,
select: function (event, ui) {
$("input#searchBox").val(ui.item.value);
$("#searchForm").submit();
}
});
}
});
</script>
</head>
<body style="font-size: 62.5%;">
<form name="search_form" id="searchForm" method="GET" action="http://localhost/search_result1.html">
<label for="searchBox">Keyword Search</label>
<input type="text" id="searchBox" name="searchString" />
<button name="searchKeyword" id="searchKeyword">Sumbit</button>
</form>
</body>
</html>
and this my search bar with auto complete feature. In it i first parse the above xml and then store the title in an array which i can use it for auto completeion feature. and on clicking the submit i redirect the page to another html page where i show all the results.
the code for the second html page is as given below..
RESULT.HTML
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="1.7.2.jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("#dvContent").append("<div></div>");
$.ajax({
type: "GET",
url: "http://localhost/category/link.xml",
dataType: "xml",
success: function (xml) {
$(xml).find('link').each(function () {
var stitle = $(this).find('title').text();
var surl = $(this).find('url').text();
$("<li></li>").html(stitle + ", " + surl).appendTo("#dvContent div");
});
},
error: function () {
alert("An error occurred while processing XML file.");
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="dvContent">
</div>
</form>
</body>
</html>
but what i want is to show only the title and url of the searched term. In this i am getting the entire xml as output. So in there a way by which i can show only the title and url of the searched term.
that is i get the output in result.html as
. HTML a tag, http://www.w3schools.com/tags/tag_a.asp
. HTML br tag, http://www.w3schools.com/tags/tag_br.asp
on searching for the term HTML in the search in search.html
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="1.7.2.jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("#dvContent").append("<div></div>");
var searchValue = $('#searchBox').val(); // Here you get the search text
$.ajax({
type: "GET",
url: "http://localhost/category/link.xml",
dataType: "xml",
success: function (xml) {
$(xml).find('link').each(function () {
var stitle = $(this).find('title').text();
var surl = $(this).find('url').text();
if (searchValue === stitle) { // Only append those if search text matches with title
$("<li></li>").html(stitle + ", " + surl).appendTo("#dvContent div");
}
});
},
error: function () {
alert("An error occurred while processing XML file.");
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="dvContent">
</div>
</form>
</body>
</html>

Basic POST with JQuery Mobile from form using php

Firstly I apologize for posting another one of these questions, but I've dove through a ton of SO questions related to this topic and haven't be able to figure out my problem. I'm new to PHP and an amature at best using Jquery mobile and the like.
I'm attempting to post to a .php file and get a response back. Eventually this will evolve into a database posting yada yada. For now, I can't seem to get my response back from my post. I'm running Xampp to host the php, Jquery Mobile is being used in other functions so it does work properly,
HTML:
<form>
<p>Username: </p><input type="text" id="username" value="" />
<p>Password: </p><input type="text" id="password" value="" />
<input type="button" onclick="submitLogIn()" value="Log In" />
</form>
Javascript:
function submitLogIn() {
alert("Submitting: " + $('#username').val() + $('#password').val());
var dbURL = "http://localhost/testerpage.php";
$.post(dbURL, {
//These are the names of the form values
Username: $('#username').val(),
Password: $('#password').val()
}, function (data,status) {
alert(status); //Won't fire
alert(html); //Won't fire
var response = html;
alert(response); //Won't fire
if (response == "Success")
{
alert("Success!"); //Won't fire
//testlog.innerHTML = "Success";
}
else
{
alert("Failure!");//Won't fire
//testlog.innerHTML = "Failure";
}
});
alert("Finished"); //Fires
};
PHP
<?php
// VARS
$Username=$_GET["Username"]; //Also tried _POST
$Password=$_GET["Password"]; //Also tried _POST
//VALIDATION
if(
$Username=="" ||
$Password==""
) {
echo "Error";
} else {
echo "Success";
}
?>
My best guess is that something is wrong with the .php because all of the questions I've looked at seem to confirm my JavaScript is right. All of my alerts fire except the ones in the call back function. The username and password are also correctly being set so that isn't the problem. I tried using _POST and _GET in my .php, I originally was using _POST because I was posting data but I was following this question: (Phonegap contact form not working over PHP) and it did the opposite so I changed it. No difference. My .php is actually hosted for sure (I can navigate to it without an error). I also tried using the $.ajax function but had the same issues.
Thanks in advance.
EDIT: Added more of the HTML (all that should be relevant) per request, can't add it all as it is too long.
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<!-- Stylesheets -->
<link rel="stylesheet" href="css/snctfy2/snctfy2.css" />
<link rel="stylesheet" href="css/snctfy2/jquery.mobile.icons.min.css" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<link href="jquerymobile/jquery.mobile.structure-1.4.2.min.css" rel="stylesheet" type="text/css" /> <!-- Add .structure after theme-->
<!-- Jquery core -->
<script src="js/jquery.js" type="text/javascript"></script>
<!-- Jquery mobile library file -->
<script src="jquerymobile/jquery.mobile-1.4.2.min.js" type="text/javascript"></script>
<!-- DateBox -->
<link rel="stylesheet" type="text/css" href="css/jqm-datebox.css" />
<script type="text/javascript" src="js/datebox/jqm-datebox.core.js"></script>
<script type="text/javascript" src="js/datebox/jqm-datebox.mode.calbox.js"></script>
<script type="text/javascript" src="js/datebox/jqm-datebox.mode.datebox.js"></script>
<script type="text/javascript" src="js/datebox/jquery.mobile.datebox.i18n.en_US.utf8.js"></script>
<!-- Scripts (pre-load)-->
<script src="js/scripts.js" type="text/javascript"></script>
<!-- CSS Override -->
<link rel="stylesheet" type="text/css" href="css/override.css" />
<title>SNCTFY</title>
</head>
<body>
<!--there is some more <div> tags here unrelated-->
<!--------------------------------------------------------Login Page---------------------
-------------------------------------------->
<div data-role="page" id="login" data-theme="a" class="bPage">
<div data-role="content">
<form>
<p>Username: </p><input type="text" id="username" value="" />
<p>Password: </p><input type="text" id="password" value="" />
<input type="button" onclick="submitLogIn()" value="Log In" />
</form>
Register
<button onclick="showAlert()">Test</button>
<p id="testlog">Results</p>
</div>
</div>
<!-- more <div> pages -->
<!-- Scripts (post-load)-->
<script type="text/javascript" src="phonegap.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
app.initialize();
</script>
</body>
</html>
EDIT2: Changed JavaScript to one of the answers to test
function submitLogIn() {
alert("Submitting: " + $('#username').val() + $('#password').val());
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
type: "POST",
url: "http://localhost/testerpage.php",
data: { "Username": username, "Password": password },
success: function (data) {
if (data) {
alert(data);
}
else {
alert('Successfully not posted.');
}
}
});
};
Just try jquery Ajax
<body>
<form>
<p>Username: </p><input type="text" id="username" value="" />
<p>Password: </p><input type="text" id="password" value="" />
<input type="button" onclick="submitLogIn()" value="Log In" />
</form>
<script>
function submitLogIn() {
alert("Submitting: " + $('#username').val() + $('#password').val());
var username =$('#username').val();
var password = $('#password').val();
$.ajax({
type: "POST",
url: "http://localhost/testerpage.php",
data:{"Username":username,"Password":password},
success: function(data) {
if (data) {
alert(data);
}
else {
alert('Successfully not posted.');
}
}
});
}
</script>
</body>
</html>
in PHP
<?php
$Username=$_POST["Username"]; //Also tried _POST
$Password=$_POST["Password"]; //Also tried _POST
//VALIDATION
if(
$Username=="" ||
$Password==""
) {
echo "Error";
} else {
echo "Success";
}
?>
Try this:
function submitLogIn() {
alert("Submitting: " + $('#username').val() + $('#password').val());
var dbURL = "http://localhost/testerpage.php";
//These are the names of the form values
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
url: dbURL,
type:'post',
data:'&username='+username+'&pass='+password,
success:function(response){
alert(response);
}
});
};
<?php
// VARS
$Username=$_POST["username"]; //Also tried _POST
$Password=$_POST["pass"]; //Also tried _POST
//VALIDATION
if(
$Username=="" ||
$Password==""
) {
echo "Error";
} else {
echo "Success";
}
?>
try this code
script
<script>
function submitLogIn() {
alert("Submitting: " + $('#username').val() + $('#password').val());
var dbURL = "http://localhost/testerpage.php";
$.post(dbURL, {
//These are the names of the form values
Username: $('#username').val(),
Password: $('#password').val()
}, function (data,status) {
if (data == "Success")
{
alert("Success!"); //Won't fire
//testlog.innerHTML = "Success";
}
else
{
alert("Failure!");//Won't fire
//testlog.innerHTML = "Failure";
}
});
alert("Finished"); //Fires
};
</script>
PHP
// VARS
$Username=$_POST["Username"]; //Also tried _POST
$Password=$_POST["Password"]; //Also tried _POST
//VALIDATION
if(
$Username=="" ||
$Password==""
) {
echo "Error";
} else {
echo "Success";
}

Not printing results from AJAX

I am working on a script to send data to a mysql table and I have it all working properly but the success part of the call, it is not loading my results in to my results column on my page. My code is below.
Any suggestions on what I can do to fix that? I am guessing the problem is within my "success:" option in my AJAX call.
<!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" />
<title>Facebook like ajax post - jQuery - ryancoughlin.com</title>
<link rel="stylesheet" href="css/screen.css" type="text/css" media="screen, projection" />
<link rel="stylesheet" href="css/print.css" type="text/css" media="print" />
<!--[if IE]><link rel="stylesheet" href="css/ie.css" type="text/css" media="screen, projection"><![endif]-->
<script src="js/jquery.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
/* <![CDATA[ */
$(document).ready(function(){
$('p.validate').hide();
$.getJSON("readJSON.php",function(data){
$.each(data.posts, function(i,post){
content = '<div id="post-'+ post.id +'">\n';
content += '<h3>' + post.author + '</h3>\n';
content += '<p class="small quiet">' + post.date_added + '</p>\n';
content += '<p>' + post.post_content + '</p>';
content += '<hr/>';
$("#contents").append(content).fadeIn("slow");
});
});
$(".reload").click(function() {
$("#posts").empty();
});
$("#add_post").submit(function() {
$('p.validate').empty();
// we want to store the values from the form input box, then send via ajax below
var author = $('#author').attr('value');
var post = $('#post').attr('value');
if(($('#author').val() == "") && ($('#post').val() == "")){
$("p.validate").fadeIn().append("Both fields are required.");
$('#author,#post').fadeIn().addClass("error");
}else{
$.ajax({
type: "POST",
url: "ajax.php",
data: "author="+ author + "&post=" + post,
success: function(result){
$('#contents').after( "<div>" +result +"</div>" );
}
});
}
return false;
});
});
/* ]]> */
</script>
<style type="text/css">
h3{margin:10px 0;}
p{margin:5px 0;}
#posts{display:none;}
</style>
</head>
<body>
<div class="container">
<div class="span-24">
<div id="post-container" class="span-9 colborder">
<h2>Posts loaded via Ajax:</h2>
<div id="contents"></div>
</div>
<div id="form" class="span-11">
<h2>New Post:</h2>
<form name="add_post" id="add_post" action="">
<label>Author:</label><br />
<input type="text" name="author" id="author" size="15" class="text" /><br />
<label>Post:</label><br />
<textarea name="post" id="post" rows="5" cols="5" class="text"></textarea><br />
<input type="submit" value="Post" id="submit" /><br />
</form><br />
<p class="validate error"></p>
</div>
</div>
<div class="span-24">
Reload
</div>
</div>
</body>
</html>
Questions to ask yourself...
Does jQuery even run your success callback?
If so is the response data well formed markup?
To begin I would add a "debugger;" statement to your success function (assuming you have firefox and firebug). This will enable you to break into the script console and get a better understanding of what is happening.
The debugger statement will cause the script execution to pause and break into the firebug console. Try the following
success: function(result){
debugger;
$('#contents').after( "<div>" +result +"</div>" );
}
If your script hits this I suspect your response markup is not well formed and jQuery is having issues parsing into the div but you can check all this when your at that breakpoint in firebug.
Another easy thing to check and dismiss in your debugging is
does your web server serve a valid (status 200) response (check the console or net tab in firebug to see this, or use the likes of fiddler if running in ie)
Let me know how you get on.
You might be getting an error try adding a debug statement to your ajax call using the error setting
$.ajax({
type: "POST",
url: "ajax.php",
data: "author="+ author + "&post=" + post,
error: function(XMLHttpRequest, textStatus, errorThrown)
{ alert(errorThrown); },
success: function(result){
$('#contents').after( "<div>" +result +"</div>" );
}
});

Categories

Resources