ajax post no update in django template - ajax

I want to post some text in django with ajax,and save the input data,show the data in same page and no refresh,like twitter.
my js:
$('#SumbitButton').click(function(){
var data_1 = $('#data_1').val()
var data_2 = $('#data_2').val()
var data_3 = $('#data_3').val()
var data_4 = $('#data_4').val()
var user = $('#AuthorName').text()
var authorprotrait = $('#UserProprait').html()
if(data_1.length>0){
$.ajax({
type: 'POST',
url: '/post/',
data:{'data_1':data_1,'data_2':data_2,'data_3':data_3,'data_4':data_4},
async: false,
error: function(msg){alert('Fail')},
success: function(msg){
$('#TopicWrap').prepend("<div class='topic-all even'><div class='topic-left'><div class='topic-author'><div class='topic-author-protrait'>"+authorprotrait+"</div><div class='topic-author-nickname'>"+authorname+"</div></div></div><div class='topic-right'><div class='topic-meta'><span class='topic-datetime'></span></div><div class='topic-content-wrap'><div class='topic-content'>"+msg+"</div></div></div><div class='clearfix'></div></div>");
$('#data_1').val('');
$('#data_2').val('');
$('#data_3').val('');
$('#data_4').val('');
}
});
} else {
alert('The data_1's length error !'+data_1.length);
}
});
and the html:
<div id="TopicTextarea">
<div>
data1:<input tabindex="4" id="data_1" type="text" name="data1" value="" maxlength="6" placeholder=""/></br>
data2:<input tabindex="4" id="data_2" type="text" name="data2" value="" maxlength="8" placeholder=""/></br>
data3:<input tabindex="4" id="data_3" type="text" name="data3" value="" maxlength="10" placeholder=""/></br>
data4:<input tabindex="4" id="data_4" type="text" name="data4" value="" maxlength="10" placeholder=""/>
<div id="TopicFormControl">
<button type="button" id="SumbitButton" class="button orange">sumbit</button>
</div>
</div>
   <div class="clearfix"></div>
</div>
<div id="TopicWrap">
{% include 'topics.html'%}
</div>
and the views:
#login_required
def post(request):
assert(request.method=='POST' and request.is_ajax()==True)
data_1 = smart_unicode(request.POST['data_1'])
data_2 = smart_unicode(request.POST['data_2'])
data_3 = smart_unicode(request.POST['data_3'])
data_4 = smart_unicode(request.POST['data_4'])
data_obj = DataPool(user=request.user,data_1=data_1,data_2=data_2,data_3=data_3, data_4=data_4)
data_obj.save()
content = '"+data_3+"  "+data_4+" "+data_1+"("+data_2+")'
response = HttpResponse(cgi.escape(content))
return response
when I input the data and click the sumbit button,it can save the data ,but it can't show the data.what's wrong in my code?
thanks.

First, use something like Poster to test that your view is returning what you expect. Only then should you start building the AJAX part.
As for what's wrong... it's a bit difficult to say since you just write that it "can't show the data" instead of saying what it's actually doing. I suspect it has to do with this line in your view:
content = '"+data_3+"  "+data_4+" "+data_1+"("+data_2+")'
It's not really clear to me what you think this would do, but what it actually does is:
>>> '"+data_3+"  "+data_4+" "+data_1+"("+data_2+")'
'"+data_3+" \xe3\x80\x80"+data_4+"\xe3\x80\x80"+data_1+"("+data_2+")'
That is to say that it produces a string containing the substrings "data_3" (etc..) It does not include the submitted data.

Related

Count the number of inputs in a page

Is there a way I can count the number of inputs in a single page?
Say if the page has 5 inputs, a save button will appear- and if there is no inputs on the page, the save button will not appear. How do i do this?
i have this but i dont think this is right
<script>
var x = 0;
var ins = 0;
$(':input').each(function(){
x++;
});
ins = x;
and pass the ins variable to php like
<?php echo '<script>ins</script>';?>
but it doesnt echo anything? is the code right tho
Two line code is enough for you.If you have not any input fields the submit button will be automatically hide.
var inputs = document.querySelectorAll('input');
console.log(inputs);
alert(inputs.length);
if(inputs.length==0)
{
document.querySelector('#button').style.display = 'none';
}
<input type="text" name="name1" value="1111974167" />
<input type="text" name="name2" value="1392666449" />
<input type="text" name="name3" value="1329903177" />
<input type="text" name="name4" value="913532785" />
<button id="button">submit</button>
JS fiddle:
https://jsfiddle.net/njv5e8yc/1/
I am not sure if you actually need to have JavaScript be echoed in php since you can determine count in the first line, but you can not pass javascript to php without ajax. Here is a basic example:
/index.php
<input type="text" name="name1" value="1111974167" />
<input type="text" name="name2" value="1392666449" />
<input type="text" name="name3" value="1329903177" />
<input type="text" name="name4" value="913532785" />
<script>
$(document).ready(function() {
// Get the count of the inputs found
var x = $('input').length;
// Pass the count to php
$.ajax({
url: '/count.php',
data: {
"count": x
},
type: 'post',
// This is what happens with the ajax returns from count.php
success: function(response) {
alert(response);
}
});
});
</script>
/count.php
<?php
if(!empty($_POST['count'])) {
$count = $_POST['count'];
die('The count is: '.$count);
}
You would get an alert dialogue box that says:
The count is: 4

how to update 2 text fields on click of a search button in the same form by fetching data from Grails Controller using AJAX in Grails 2.1.0

I have a controller(SearchController) which fetches data on clicking a search button (inside myview.gsp) i want to populate 2 text fields present in the same myview.gsp with the data i have in my controller (SearchController) .I know i need to do ajax calling because i want to populate only 2 fields and dont want to reload the page which contains other valuable information . How can i achieve it please guide me
here is my Controller
def searchItem() {
def itemFound = MyService.searchP20Code(params["item"])
def resultMap = [:]
if (itemFound!=null)
{
resultMap.put("CODE",itemFound[1])
resultMap.put("DESC",itemFound[2])
}
println "Result:"+resultMap
session.setAttribute("searchResult", resultMap)
render(view: myview" )
}
myview.gsp
myview.gsp
<div class="leftPanel filter-label">
<a href="#" class="tt"> <g:message
code="Normal.label.Code" />
</a>
</div>
<div class="rightPanel filter-field-wrapper">
<input type="text"
name="Code" maxlength="30"
value=""
id="i_code" />
</div>
</div>
<div class="formLables">
<div class="leftPanel filter-label">
<a href="#" class="tt"> <g:message
code="Normal.label.Description" />
</a>
</div>
<div class="rightPanel filter-field-wrapper">
<input type="text"
name="Desc" maxlength="30"
onkeyup="fieldMaxlength('material_code')" value=""
id="i_description" />
</div>
</div>
<g:actionSubmit
value="${message(code:'Normal.button.search', default: 'Search Code')}"
action="searchItem" />
please help my how can i update only these two text fields in myview.gsp onclicking search button using ajax .I am using grails 2.1.0
Here you can find a detailed example with Grails build-in Ajax support.
You can also use JQuery (example here)
EDIT:
Your controller needs to look like this:
import grails.converters.JSON
class ExampleController {
....
def searchItem() {
def itemFound = MyService.searchP20Code(params["item"])
def resultMap = [:]
if (itemFound!=null) {
resultMap.put("CODE",itemFound[1])
resultMap.put("DESC",itemFound[2])
}
println "Result:"+resultMap
//session.setAttribute("searchResult", resultMap)
render(resultMap as JSON )
}
}
and your gsp
<head>
...
<g:javascript plugin="jquery" library="jquery" src="jquery/jquery-{WRITE_YOUR_VERSION_HERE}.js"/>
<script>
function callAjax(e){
e.preventDefault();
$.ajax({
url: "example/search",
type:"post",
dataType: 'json',
success: function(data) {
console.log(data);
$("input[name='Code']").val(data.CODE);
$("input[name='Desc']").val(data.DESC);
}
});
}
</script>
...
</head>
<body>
....
<input type="submit" value="Call Ajax Function" onclick="callAjax()">
....
</body>

WebMatrix AJAX INSERT not working

i'm trying to add an entry into my database and update a table i have created using AJAX. I think i'm halfway there, i can send my form contents to the "partial" page, but thats where it gets stuck?
Here's my content page:
#{
Layout = "~/_SiteLayout.cshtml";
WebSecurity.RequireAuthenticatedUser();
var db = Database.Open("StayInFlorida");
var rPropertyId = Request.QueryString["PropertyID"];
var Roominfo = "SELECT * FROM RoomInfo WHERE PropertyID=#0";
var qRoominfo = db.Query(Roominfo, rPropertyId);
}
<h2>Current Rooms</h2>
<table id="room-table" class="table table-bordered">
<tr>
<th>Room Name</th>
<th>Room Type</th>
<th>Room Description</th>
</tr>
#foreach(var row in qRoominfo){
<tr>
<td>#row.RoomName</td>
<td>#row.RoomType</td>
<td>#row.RoomDescription</td>
</tr>
}
</table>
<form id="add-room-form" action="#Href("~/Partials/AddRoom")">
<div class="row">
<span class="label"><label for="title">Room Name:</label></span>
<input type="text" name="roomname" id="roomname" size="50" />
</div>
<div class="row">
<span class="label"><label for="title">Room Type:</label></span>
<input type="text" name="roomtype" id="roomtype" size="50" />
</div>
<div class="row">
<span class="label"><label for="title">Room Description:</label></span>
<input type="text" name="roomdescription" id="roomdescription" size="50" />
</div>
<input type="hidden" name="propertyid" value="#rPropertyId" />
<button class="btn btn-success" id="submitbutton">Submit</button>
</form>
<script type="text/javascript">
$(function(){
$('#submitbutton').click(function(){
$.ajax({
type: "POST",
url: "/Partials/AddRoom",
data: $("#add-room-form").serialize(),
dataType: "text/plain",
success: function (data) {
$('#room-table').html(data);
}
return false;
});
});
});
</script>
and here is the partial page which "should" insert the data into the database:
#{
var db = Database.Open("StayInFlorida");
var sql = "INSERT INTO RoomInfo (PropertyID, RoomName, RoomType, RoomDescription, LastModified) " +
"VALUES (#0, #1, #2, #3, GetDate())";
var propertyid = Request["propertyid"];
var roomname = Request["roomname"];
var roomtype = Request["roomtype"];
var roomdescription = Request["roomdescription"];
db.Execute(sql, propertyid, roomname, roomtype, roomdescription);
}
In theory, it should write the info to the database, and then refresh my table, so im guessing something isn't quite right with the javascript?
You cannot sent the data through an ajax call is because you cannot even start the request. You are using the function to trigger when a click is made. But there will be no click event.
Reason: There is no button with the ID for click event. See Click trigger issue section below.
Tip: To check whether there is any Request to the server or not, you should make use of this. In every browser when you press F12 you get Developer Tools opened. Make sure you are on network tab. You will be able to check any network request made to server through there. Ajax requests are also saved there as a log, there status and everything is present there. That will be a basic but a powerfull tool to help you out in understanding how Ajax requests are made.
There are certain issues in your code too.
Issue in the HTML: There is an error in your code, look at the submit button. Its having code as:
<button class="btn btn-success" type="submit" value="Submit"/>Submit</button>
Which should be:
<button class="btn btn-success" type="submit" value="Submit">Submit</button>
And then, I should change that too the following because the type="submit" will submit the form instead of creating an ajax request. I used your page in my website and just replaced the DataBase objects and replaced them with simple Response like Response.Write() and wrote the variables that I caught:
<button class="btn btn-success" id="submitbutton">Submit</button>
So the code that I changed the above one to is like this:
#{
if(IsPost){
var propertyid = "1";
var roomname = Request["roomname"];
var roomtype = Request["roomtype"];
var roomdescription = Request["roomdescription"];
var lastmodified = DateTime.Now;
// here you will write the data to database using Database.Execute
// Remember you should write the ajax response
// here as a result of Response.Write()
// However if you still want to load that page, its OK!
}
}
As mentioned earlier, you were write the propertyid as "'1'" I changed that to "1". But in case you want to execute as "'1'" its ok too.
Click trigger issue:
There were some other issues too. You were using:
$('#submitbutton').click(function(){
But there was no button with the ID submitbutton. So I changed the id of the button you were using there.
What I changed in your code:
What change I made in your code was I changed the POST request to GET. To have a look at what variables are being sent to server and what results I get. I had it easier to make use of this code as GET request was easily able to check then POST request.
If you still want to use POST request you should try to serialize() the form as JSON and send it to server. But GET will be easy.
Then I gave another field to the $.ajax section as:
data: 'roomname=' + $('#roomname').val() +
'roomtype=' + $('#roomtype').val() +
'roomdescription=' + $('#roomdescription').val(),
This will create a string of the data to be sent. And then it will be caught on that page. And I removed if(IsPost) too. I was able to get the result of the Response. So what you can do is to change the Response of the request and write is as:
$("#room-table").html(response);
And the table will be changed! This will remove the previous data in the table Or even whole of the table and update it with the data recieved from the Response. And then I was able to send the request to server, process the QueryString and then write a response and then using $('#idofelement').html(response) I wrote it in the specific area. You can try it as I did.
The full code that I used was:
One the main page I had this code:
#{
Layout = "~/_SiteLayout.cshtml";
}
<h2>Current Rooms</h2>
<div class="row">
<span class="label"><label for="title">Room Name:</label></span>
<input type="text" name="roomname" id="roomname" size="50" />
</div>
<div class="row">
<span class="label"><label for="title">Room Type:</label></span>
<input type="text" name="roomtype" id="roomtype" size="50" />
</div>
<div class="row">
<span class="label"><label for="title">Room Description:</label></span>
<input type="text" name="roomdescription" id="roomdescription" size="50" />
</div>
<button class="btn btn-success" id="submitbutton" value="Submit" >Submit</button>
<script type="text/javascript">
$(function(){
$('#submitbutton').click(function(){
$.ajax({
url: '/Partials',
data: 'roomname=' + $('#roomname').val() + 'roomtype=' +
$('#roomtype').val() + "roomdescription=" +
$('#roomdescription').val(),
dataType: 'text',
contentType: 'text/html',
success: function(response) {
$("#body").html(response);
},
error: function(data){
alert('Something went wrong');
}
});
});
});
</script>
I changed the page to partials only and used it. Here is the content for that page.
#{
var propertyid = "1";
var roomname = Request["roomname"];
var roomtype = Request["roomtype"];
var roomdescription = Request["roomdescription"];
var lastmodified = DateTime.Now;
Response.Write("Room name: " + roomname + "<br>Room Type: "
+ roomtype + "<br>Room Description: " + roomdescription +
"<br>Property: " + propertyid);
}
Now its upto you to use the Database variables here. Where I used Response.Write and other codes You can use the Database methods. And also you can add WebSecurity method.
The Database.Execute method requires the SQL to be executed to be passed in first. You don't appear to be passing it in at all. Also, I assume that PropertyId is an integer? If so, you should not surround it in quotes. In fact, you should try delimiting values that will be passed in via parameter at all. That's one of the benefits of using parameters. Try this:
#{
if(IsPost){
var db = Database.Open("StayInFlorida");
var sql = "INSERT INTO RoomInfo (PropertyID, RoomName, RoomType, RoomDescription, LastModified) " +
"VALUES (#0, #1, #2, #3, GetDate())";
var propertyid = 1;
var roomname = Request["roomname"];
var roomtype = Request["roomtype"];
var roomdescription = Request["roomdescription"];
db.Execute(sql, propertyid, roomname, roomtype, roomdescription);
}
}
You are hardcoding the Properytid at the moment. If you want that to be dynamic, add a hidden field to your AJAX form and set the value to rPropertyId:
<input type="hidden" name="propertyId" value="#rPropertyId" />
Then you can alter the 4th line in the snippet above:
var propertyId = Request["propertyId"];

jquery ajax multiple form submission

need a little help. My jQuery was going smooth today until I hit a wall. I am trying to have multiple forms (individual line items) editable on the fly via AJAX, with a text submission link or some kind of submit button. Problem is, I can get it to submit the form via the AJAX, but without any of the data from the form... i.e. hit submit, it sends the request, but no querystring. Can someone please help me identify what's missing?
Here is my jquery:
$('.submitLineChanges').click(function() {
var formID = $(this).closest('form').attr('ID')
datastring = $(formID).serialize();
$.ajax({
type:'POST',
url: 'update_ajax.asp',
data: datastring,
success: function(response) {
alert("Success " + id)
//$('#ContactForm').find('.form_result').html(response);
}//end ajax options
});//end ajax
return false;
});//end of click function
And my form:
<form id="line-item-<%= intRecID %>-form" class="submitLineForm">
<input type="hidden" name="UpdateLineItem" value="true" />
<span class="edit" id="edit-line-<%= intRecID %>" style="display: none;">
<span class="quantity"><input name="part_qty" id="part_qty_<%= intRecID %>" type="text" value="<%=FormatNumber(rs("quote_part_qty"),0)%>"></span>
<span class="partno"><input name="part_no" id="part_no_<%= intRecID %>" type="text" value="<%=rs("quote_part_id")%>"></span>
<span class="descrip"><Textarea name="part_descrip" type="text" id="descrip<%= intRecID %>" rows="3"><%=rs("quote_part_descrip")%></Textarea></span>
<span class="sellprice">$<input name="part_sale" id="part_sale_<%= intRecID %>" type="text" value="<%=FormatNumber(rs("quote_part_sale"),2)%>"></span>
<span class="margin" id="emargin_<%= intRecID %>"><%=margin%></span>
<span class="cost"><strong>Cost: </strong>$<input name="part_cost" id="part_cost_<%= intRecID %>" type="text" value="<%=FormatNumber(cost,2)%>"></span>
<span class="wt"><strong>Weight: </strong><input name="part_wt" id="part_wt_<%= intRecID %>" type="text" value="<%=FormatNumber(rs("quote_part_wt"),2)%>"></span>
<span class="update"><input type="button" value="Save Changes" class="submitLineChanges" /></span>
</span>
</form>
As you should be able to tell, I'm running this in ASP. The form is for each line item in a cart basically. Because of the nature of the page, I don't want to have a separate page to edit all the info. It seems this should work, but its likely I'm missing something through the tunnel vision I'm in now.
I should note, the form is for each line, I don't need it to submit all the forms, just the one.
Thanks
Change
datastring = $(formID).serialize();
to
var datastring = $('#' + formID).serialize();
You need to use a # prefix using the ID selector. Also - without the var keyword you polluting the global namespace for no reason.
Or even better ... you could replace
var formID = $(this).closest('form').attr('ID');
var datastring = $('#' + formID).serialize();
with
var datastring = $(this).closest('form').serialize();
Which finds the form and serialises it all in one go !!
Thanks to #MikeBrant for that suggestion.

jQuery: jQuery.ajax() and the problem with anchors

Hi all I have a problem with anchors and dynamic content loaded thought $.ajax().
Let suppose this is my jQuery code:
$("a.false").live("click", function() {
var data = $(this).attr("href");
$("div#text").hide("fast");
$("div#loader").show("fast");
$.ajax({
type: "GET",
url: "callback.php",
data: data,
dataType: "html",
cache: false,
success: function(result){
$("div#loader").hide("fast");
$("input#data").val(data);
$("div#text").html(result);
$("div#text").show("fast");
}
});
});
I think everybody knows what means this code and I'll no explain it.
callback.php answer is:
<div class="name">
<div class="replic_id">
<input type="hidden" id="replica_1" name="replica_1" value="1" />
<a id="rp1">#1</a>
</div>
<div class="names">Name 1</div>
<div class="replicas">Replica 1</div>
</div>
<div class="name">
<div class="replic_id">
<input type="hidden" id="replica_2" name="replica_2" value="2" />
<a id="rp2">#2</a>
</div>
<div class="names">Name 2</div>
<div class="replicas">Replica 2</div>
</div>
And now I javascript variable "data" value is = "movie=scarymovie#255" the page must start from anchor #255 but it starts from the begin. How I can fix it to start from anchor 255, no from begin?
with regards ;]
Fixed: Correct a IDs
It is easier to send back the anchor as its own value and just use:
window.location.hash = '#255';
It is worth noting that even though it may work, 255 is not a valid value for an ID attribute in HTML: What are valid values for the id attribute in HTML?
Edit: fixed a typo in the variable name

Resources