pass a string from ajax function to spring controller - javascript

I'm working on a standalone application and I'm trying to pass a string which is an output of change event, to the spring controller using the code below
HTML CODE
<!DOCTYPE HTML>
<html xmnls:th="http://www.thymeleaf.org">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<title>ADD NEW BILL</title>
<!-- jquery -->
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script type="text/javascript">
$(function() {
$("#Mandy_Name").autocomplete({
source: "autocomplete",
minLength: 3
});
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#Mandy_Name").change(function(){
var changed = $(this).val();
console.log(changed);
$.ajax({
type : "POST",
dataType : 'json',
url : "mandyname",
data: {name:changed},
success: function(data) {
console.log(data);
return false;
}
});
});
});
</script>
</head>
<body>
<div class="container">
<hr>
<p class="h4 mb-4">SAVE NEW PURCHASE BILL</p>
<form action="#" th:action="#{/savePurchase}"
th:object="${purchase}" method="post">
<!-- add a hidden field to handle update -->
<!-- <input type="hidden" th:field="*{idPurchaseDetails}"> -->
<input type="hidden" th:field="*{ID}">
MANDY NAME : <input id="Mandy_Name" type="text" th:field="*{mandyName}"
class="form-control mb-4 col-4" placeholder="Mandy Name">
GSTIN : <input type="text" th:field="*{gstin}"
class="form-control mb-4 col-4" value = gst() placeholder="GSTIN">
<button type="submit" class="btn btn-info col-2">SAVE</button>
</form>
<br><br>
<a th:href="#{/purchaselist}">BACK TO PURCHASE LIST</a>
</div>
</body>
</html>
controller code
#RequestMapping(value = "mandyName", method = RequestMethod.POST)
public ModelAndView getSearchResultViaAjax(#RequestBody Purchase purchase, HttpServletRequest request,
HttpServletResponse response)
{
ModelAndView mv = new ModelAndView();
String name = purchase.getMandyName();
System.out.println(name);
return mv;
}
I'm getting an error "Failed to load resource: the server responded with a status of 404 ()" in the browser console.
Help me to pass the string "changed" to the controller.
I'm using these dependencies
jquery from "org.webjars" ,
spring-boot-starter-actuator ,
spring-boot-starter-data-jpa ,
spring-boot-starter-web ,
spring-boot-starter-data-rest ,
spring-boot-starter-thymeleaf ,
spring-boot-devtools ,
spring-boot-starter-json ,
mysql-connector-java ,
spring-boot-starter-test ,
junit-vintage-engine ,
spring-boot-maven-plugin
Should I be using any other dependencies ??

The HTTP Status 404 means that the URL provided, cannot be found on the server.
I see that you make the Ajax call with an incorrect URL. Change it to the correct one depending on your Spring App and port.
Normally it should be under: http://localhost:8080/mandyName. But this you have to check and examine.
Sample JS code:
$(document).ready(function(){
$("#Mandy_Name").change(function(){
var changed = $(this).val();
console.log(changed);
$.ajax({
type : "POST",
dataType : 'json',
url : "http://localhost:8080/mandyName", // ~~ HERE ~~
data: {name:changed},
success: function(data) {
console.log(data);
return false;
}
});
});
});

Related

HTML range slider to Flask with AJAX call

I have a HTML control panel with various buttons and sliders. All of the buttons are operational and when clicked send a post request which my Python app receives and then executes functions.
I cannot seem to get the slider controls to work, When I adjust the slider I get the following error:
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: 'button'
This is promising as at least I can see it trying to do something and failing, which is the best result achieved thus far. My javascript and AJAX knowledge is limited and I need a solution for the slider to POST request on any onchange value that python can then interpret.
I initially had the following HTML:
<input id="slider" type="range" min="0" max="100" value="50" onchange="updateVolume(getElementById('slider').value); return false;">
Javascript:
<script>
function updateVolume (vol) {
$.ajax({
method: "POST",
url: '{{ url_for('main.control_panel', video_id=video.id) }}',
data: { volume: vol}
})
.done(function( msg ) {
// optional callback stuff if needed
// alert( "Data Saved: " + msg );
});
}
</script>
This threw up the same error.
This is my current code that also throws the same error:
HTML:
<input id="slide" type="range" min="1" max="100" step="1" value="10" name="slide">
<div id="sliderAmount"></div>
Javascript:
var slide = document.getElementById('slide'),
sliderDiv = document.getElementById("sliderAmount");
slide.onchange = function() {
sliderDiv.innerHTML = this.value;
$.ajax({
url: '{{ url_for('main.control_panel', video_id=video.id) }}',
data: $('form').serialize(),
type: 'POST',
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
}
Python:
#main.route("/control_panel/<int:video_id>", methods=['GET', 'POST'])
def control_panel(video_id):
video = video.query.get_or_404(video_id)
if request.method == 'POST':
... #IF ELIF for various button functions here
volume = request.form['slider']
return json.dumps({'volume': volume})
return render_template('/control_panel.html', title=video.video, video=video)
Any support would be greatly appreciated as I'm struggling to find solutions on the web along with me aforementioned js/ajax knowledge.
Thanks
EDIT:
This is a recreation of the problem:
python:
from flask import Flask, request, redirect, url_for, render_template, json
app = Flask(__name__)
#app.route('/', methods=['GET', 'POST'])
def control_panel():
if request.method == 'POST':
if request.form['button'] == 'button-play':
print("play button pressed")
elif request.form['button'] == 'button-exit':
print("exit button pressed")
elif request.form['slider']:
volume = request.form['slider']
return json.dumps({'volume': volume})
print(volume)
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
HTML:
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<title>Slider</title>
</head>
<body>
<div class="container" id="control_panel_1">
<form action="/" method ="post" enctype="multipart/form-data" id="form">
<div class="row">
<div class="col">
<button class="btn btn-primary" button type="submit" name="button" value="button-play">PLAY</button>
<button class="btn btn-primary" button type="submit" name="button" value="button-exit">EXIT</button>
<input id="slide" type="range" min="1" max="100" step="1" value="10" name="slide">
<div id="sliderAmount"></div>
</div>
</div>
</form>
<!--- SCRIPTS --->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
</body>
<script>
var slide = document.getElementById('slide'),
sliderDiv = document.getElementById("sliderAmount");
slide.onchange = function() {
sliderDiv.innerHTML = this.value;
$.ajax({
url: '/index.html',
data: $('form').serialize(),
type: 'POST',
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
}
</script>
</html>
Problem is because $('form').serialize() sends only values from <input> but not from <button> but in Flask you check request.form['button'] and it raises error because key button doesn't exists in dictionary request.form.
You have to use
request.form.get('button')
and then it returns None when button doesn't exists in dictionary
BTW:
you have only #app.route("/", ...) so AJAX has to send to /, not to
/index.html
using print(volume) after return ... is useless becuse return ends function
in Flask you can use return jsonify(dict) instead of return json.dumps(dict) and then it sends special headers and JavaScript converts it to object and you can get response.volume. Using json.dumps(dict) it sends it as html/text and you would have to use JSON.parse(response).volume
Working code in one file (using template_render_string instead of template_render) so everyone can easily test it.
from flask import Flask, request, redirect, url_for, render_template, json, render_template_string, jsonify
app = Flask(__name__)
#app.route('/', methods=['GET', 'POST'])
def control_panel():
print('request.form:', request.form)
if request.method == 'POST':
if request.form.get('button') == 'button-play':
print("play button pressed")
elif request.form.get('button') == 'button-exit':
print("exit button pressed")
elif request.form.get('slide'):
volume = request.form.get('slide')
print('volume:', volume)
#return jsonify({'volume': volume})
return json.dumps({'volume': volume})
print('render')
return render_template_string('''<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<title>Slider</title>
</head>
<body>
<div class="container" id="control_panel_1">
<form action="/" method ="post" enctype="multipart/form-data" id="form">
<div class="row">
<div class="col">
<button class="btn btn-primary" button type="submit" name="button" value="button-play">PLAY</button>
<button class="btn btn-primary" button type="submit" name="button" value="button-exit">EXIT</button>
<input id="slide" type="range" min="1" max="100" step="1" value="10" name="slide">
<div id="sliderAmount"></div>
</div>
</div>
</form>
<!--- SCRIPTS --->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
</body>
<script>
var slide = document.getElementById('slide'),
sliderDiv = document.getElementById("sliderAmount");
slide.onchange = function() {
sliderDiv.innerHTML = this.value;
$.post({
url: '/',
data: $('form').serialize(),
success: function(response){
alert(response);
alert(response.volume); // works with jsonify()
alert(JSON.parse(response).volume); // works with json.dumps()
console.log(response);
},
error: function(error){
alert(response);
console.log(error);
}
});
}
</script>
</html>''')
if __name__ == '__main__':
app.run(debug=True, use_reloader=False)

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);
?>

Chat not closing and not showing response

I made a qnamaker service and build a chat to show the response of the question.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Live Chat</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Droid+Sans:400,700">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="chat.js"></script>
<script src="rispostachat.js"></script>
<link rel="stylesheet" href="chat.css">
<script src="jquery-3.3.1.min.js"></script>
</head>
<body>
<div id="live-chat">
<header class="clearfix">
x
<h4>Bot</h4>
</header>
<div class="chat">
<h3>Risposta:</h3>
<div id="answer"></div>
<input type="text" id="question" name="question">
<button type="button" class="button" id="post-btn"> Chiedi</button>
</br>
</body>
</html>
This is for close and show the chat box
(function() {
$('#live-chat header').on('click', function() {
$('.chat').slideToggle(300, 'swing');
});
$('.chat-close').on('click', function(e) {
e.preventDefault();
$('#live-chat').fadeOut(300);
});
}) ();
And this is for take the response inserted and show the response to the user
$("#post-btn").click(function(){
jQuery.ajax ({
url: "https://westus.api.cognitive.microsoft.com/qnamaker/v2.0/knowledgebases/idknowledgebasetoinsert/generateAnswer",
type: "POST",
data: '{"question" : "'+$("#question").val()+'"}',
dataType: "json",
contentType : "application/json",
headers: {"Ocp-Apim-Subscription-Key": "subscriptionkeytoinsert"},
success: function(msg, status, jqXHR){
$('#answer').html(msg.answers[0].answer);
}
});
});
When i click on the header of the chat , the chat not close and the chat not disappear when i clcik on the close button x of the chat.
When i click on Chiedi to send the answer nothing happen. I don't see the response of the service in the chat.
it looks like you have included the jQuery twice (2 different versions) in your header
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="jquery-3.3.1.min.js"></script>

Use JQuery to get data from JSON file

Overflow!
I'm currently working on a little application I have to finish for school monday. I didn't have a lot of time to make something big. So I decided, why not retrieve information of Steam's Web Api and get the stats of players.
The url to the steam api:
http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key=DA697BB2D106697D5F8AC7E7A2BFAC52&steamid=76561198263871727
The last parameter &steamid= represents the id of the player. Now I have found out how to get the steamid into a variable, but when trying to add the id to the rest of the url (http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key=DA697BB2D106697D5F8AC7E7A2BFAC52&steamid=id should be here and fetching the data with the Ajax.getJson method.. It just doesn't work.. I'm for very experienced with JSON btw.. Can someone help me out with this?
My Web Page:
<!DOCTYPE html>
<html lang="en">
<head>
<!--Meta Information-->
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--JQuery Mobile-->
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<!--FontAwesome-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<!--Custom Styles-->
<link href="css/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div data-role="page" id="index">
<div data-role="header">
<h1>CS:GO Stats</h1>
</div>
<div data-role="main" class="ui-content">
<div class="search">
<label for="search">Enter SteamID:</label>
<input type="search" name="search" id="inputSearch" />
<input type="submit" id="butSearch" data-inline="true" value="Search SteamID">
</div>
<div id="result">
</div>
</div>
</div>
<!--getSteamUserId function-->
<script src="js/getSteamUserId.js"></script>
</body>
</html>
My Javascript Code:
$(document).ready(function() {
$('#butSearch').click(function(event) {
var input = $('#inputSearch').val();
$.getJSON( "http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key=DA697BB2D106697D5F8AC7E7A2BFAC52&steamid=" + input, function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "#result" );
});
})
})
Now what I want is to get the stats data from the JSON file into my web page. Would anyone know how to do this? I can also see the JSON is not only a flat JSON file.. Like it has different layers (if that's a good explenation)..
Thanks in advance!
Work with jsonP like here:
$.ajax({
url: url,
dataType: 'JSONP',
type: 'GET',
jsonp: 'jsonp',
success: handler
});
Working example here
I'm not entirely sure about the first part. It gives me an error which after googling led me to "No 'Access-Control-Allow-Origin' header is present on the requested resource" which advises using CORS. Error:
XMLHttpRequest cannot load http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key=DA697BB2D106697D5F8AC7E7A2BFAC52&steamid=&76561198263871727. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 400.
Once you have the JSON it's easier. If it's stringified you can turn it into a javascript object with
steamObject = JSON.parse(steamJsonData);
and then navigate through it like a normal javascript object. Cycle through playerstats.stats[i] with a for loop and you can add the data to your page using normal DOM manipulation.

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