Showing Django comments after submission with ajax - ajax

I implemented Django ajax comment submission in my app using Nick Carroll's method here. I'd like the user that posted the comment, date of submission and comment to appear on the page using ajax after the server has received and saved it. What's a good way to do this?

Use jquery's post method to post the comment to server and on successful response,display the comment on the page from the success call back function.

Alright this is kind of a hackerish way to go about this, but I think I've figured out a decent solution:
<script type="text/javascript" charset="utf-8">
function bindPostCommentHandler() {
$('#comment_form form input.submit-preview').remove();
$('#comment_form form').submit(function() {
var comment_text = $('#id_comment').val();
$.ajax({
type: "POST",
data: $('#comment_form form').serialize(),
url: "{% comment_form_target %}",
cache: false,
dataType: "html",
success: function(html, textStatus) {
$('#comment_form form').fadeTo(500, 0, function(){
$(this).remove();
});
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;
var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm} var today = mm+'/'+dd+'/'+yyyy;
var comment = "<div class='comment'><h4>User " + "\"{{ user.username }}\"" + " Rating <small>" + today + "</small></h4>" + comment_text + "</div><hr />";
$(comment).hide().prependTo("#comments_loc").fadeIn(1000);
bindPostCommentHandler();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$('#comment_form form').replaceWith('Your comment was unable to be posted at this time. We apologize for the inconvenience.');
}
});
return false;
});
}
$(document).ready(function() {
bindPostCommentHandler();
});
</script>
I'm relatively new to javascript so I put this together with what little I know. Feel free to leave some comments if you think this could be cleaned up.

<script type="text/javascript" charset="utf-8">
function bindPostCommentHandler() {
$('#comment_form form input.submit-preview').remove();
$('#comment_form form').submit(function() {
$.ajax({
type: "POST",
data: $('#comment_form form').serialize(),
url: "{% comment_form_target %}",
cache: false,
dataType: "html",
success: function(html, textStatus) {
$('#comment_form form').replaceWith(html);
$('.comt_message').show();
bindPostCommentHandler();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$('#comment_form form').replaceWith('Your comment was unable to be posted at this time. We apologise for the inconvenience.');
}
});
return false;
});
}
$(document).ready(function() {
bindPostCommentHandler();
});
</script>

Related

Ajax post calling wrong url

Good day.
I want to know why is my project calling the wrong url? The code is:
SCRIPT
$.ajax({
type: "POST",
url: "/Application/Franchise",
data: JSON.stringify(sendInfo),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
$('#myModal3').modal('hide'); //hide the modal
},
error: function () {
alert("Error while inserting data");
}
});
CONTROLLER
public class ApplicationController : Controller
{
public ActionResult Franchise()
{
return View();
}
}
I even tried changing the url by 'Url.Action("Franchise", "Application")' but still the system kept on bringing me to http://localhost:49267/Home/Franchise.
I can't understand what is wrong here. Is there a bug in jquery ajax url post?
Thanks in advance.
UPDATE
<button class="btn btn-success" type="button" id="btnCapture">Submit</button>
#section Scripts{
<script src="~/Scripts/webcam.min.js"></script>
<script src="~/Scripts/webcam.js"></script>
<script language="JavaScript">
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 90
});
Webcam.attach( '#my_camera' );
</script>
<script language="JavaScript">
function take_snapshot() {
Webcam.snap( function(data_uri) {
document.getElementById('results').innerHTML =
'<img id="base64image" src="' + data_uri + '"/>';
} );
}
</script>
<script>
$(document).on("click", ".open-camera", function () {
var myBookId = $(this).data('id');
$(".modal-body #franid").val(myBookId);
})
</script>
<script>
$(function(){
$('#btnCapture').on('click', function(){
var file = document.getElementById("base64image").src;
var franid = $("#franid").val();
var sendInfo = {
Imagee: file,
FranIDD: franid
};
$.ajax({
type: "POST",
url: "/Application/Franchise",
data: JSON.stringify(sendInfo),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
$('#myModal3').modal('hide'); //hide the modal
},
error: function () {
alert("Error while inserting data");
}
});
});
});
</script>
}
This is all my code.
Ok. So I found my problem. It was in my controller.
In my controller I tried adding return RedirectToAction("Franchise", "Home"); after the save command. As soon as I commented this, everything worked.
Thanks for the help again guys.
Please use the browser to access directly, not from within the IDE directly access, from the localhost:49267 should be from the IDE access, and you will write URL as http://www.google.com try.

ajax code to check new records at database

I am using laravel, and I want to check if there are new records inserted into the database, I want an Ajax code the returns with the result, I don't know ajax so please help me
this is my controller
public function newrecord($target_id){
$record = Message::where('target_id', $target_id)->get();
return $record->count();
}**strong text**
and this is my ajax code
$(document).ready(function(){
var ajaxCall=function()
{
$.ajax({
url:"{{ url('/record/'.$auth->id) }}" ,
type: "GET",
datatype:"html",
data:{},
success:function(data) {
$('.msgnum').html(data)
console.log('new record);
},
error: function(data) {
console.log('error');
}
});
}
setInterval(ajaxCall,5000);
});
all I get is just a loop or " new record " in the console log
Do I need to return anything to tell that there is a new file, any help?
Try this, of course modify the code to how you want it to work but wrap the whole thing in setInterval, you don't even need the document.ready()
<script type="text/javascript">
setInterval(function() {
$.ajax({
url:"{{ url('/record/'.$auth->id) }}",
type: "GET",
datatype:"html",
data:{},
processData:false,
success: function(data){
$('.msgnum').html(data)
console.log('new record');
error: function(data) {
console.log('error');
}
},
error: function(){}
});
}, 5000);
</script>

call server-side REST function from client-side

In the case, on the server side have some archive restApi.js with REST functions. My REST functions works fine, i test with Prompt Command.
In my client side have some archive index.ejs, And I want to call with this file.
My restApi.js: Server-side
var Client = require('./lib/node-rest-client').Client;
var client = new Client();
var dataLogin = {
data: { "userName":"xxxxx","password":"xxxxxxxxxx","platform":"xxxx" },
headers: { "Content-Type": "application/json" }
};
var numberOrigin = 350;
client.registerMethod("postMethod", "xxxxxxxxxxxxxxxxxx/services/login", "POST");
client.methods.postMethod(dataLogin, function (data, response) {
// parsed response body as js object
// console.log(data);
// raw response
if(Buffer.isBuffer(data)){
data = data.toString('utf8');
console.log(data);
re = /(sessionID: )([^,}]*)/g;
match = re.exec(data);
var sessionid = match[2]
console.log(sessionid);
openRequest(sessionid, numberOrigin); // execute fine
}
});
function openRequest(sessionid, numberOrigin){
numberOrigin+=1;
var dataRequest = {
data: {"sessionID":sessionid,"synchronize":false,"sourceRequest":{"numberOrigin":numberOrigin,"type":"R","description":"Test - DHC","userID":"xxxxxxxxxx","contact":{"name":"Sayuri Mizuguchi","phoneNumber":"xxxxxxxxxx","email":"xxxxxxxxxxxxxxxxxx","department":"IT Bimodal"},"contractID":"1","service":{"code":"504","name":"Deve","category":{"name":"Developers"}}} },
headers: { "Content-Type": "application/json" }
};
client.post("xxxxxxxxxxxxxxxxxxxxxxxxx/services/request/create", dataRequest, function (data, response) {
// parsed response body as js object
// console.log(data);
// raw response
console.log(data);
});
}
My index.ejs: Client side
<html>
<head> ------------- some codes
</head>
<meta ------- />
<body>
<script>
function send() {
$.ajax({
type: "POST",
url: "restApi.js",
data: '{ sendData: "ok" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert("successful!" + result.d);
}
});
}
</script>
<script src="restApi.js"></script>
</body>
</html>
I've try see others examples but does not work (Ajax).
And I need to know how to solved this, if have other Best practice for it, please let me knows.
In my console (Chrome) show if I call the ajax function:
SyntaxError: Unexpected token s in JSON at position 2 at JSON.parse (<anonymous>) at parse (C:\xxxxxxxxxxxxxxxxxxxxxxxxx\node_modules\body-parser\lib\types\json.js:88:17) at C:\xxxxxxxxxxxxxxxxxxxxxxxxx\node_modules\body-parser\lib\read.js:116:18
And if I click (BAD Request) show:
Obs.: Same error than app.js, but app.js works fine.
Cannot GET /restApi.js
In the case the file restApi.js Is a folder behind the index.
Folder:
Obs.: public folder have the index.ejs
Your problem is bad url. In case if you have fiule structure like this you have to point as shown in image
Based on the error I think the data you are posting via AJAX is not in correct syntax.
Change function send() as following.
function send() {
var obj = { "sendData" : "ok" };
$.ajax({
type: "POST",
url: "restApi.js",
data: obj,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert("successful!" + result.d);
}
});
}
This should resolve the error you are facing.
Try this now...
function send() {
var obj = {
sendData : "ok"
};
$.ajax({
type: "POST",
url: "Your url",
data: obj,
dataType: "json",
success: function (result) {
alert("successful!" + result.d);
},
error: function (error) {
console.log("error is", error); // let us know what error you wil get.
},
});
}
Your url is not pointing to js/restapi js.
and what code do you have in js/restapi js?
if your action page is app js you have to put it in url.
url:'js/restapi.js',

Redirecting after Ajax post

I want the success on ajax post to go to the home page. For some reason I keep doing it wrong. Any idea what I should do to fix this?
window.APP_ROOT_URL = "<%= root_url %>";
Ajax
$.ajax({ url: '#{addbank_bankaccts_path}',
type: 'POST',
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', '#{form_authenticity_token}')},
dataType: "json",
data: 'some_uri=' + response.data.uri ,
success: function(APP_ROOT_URL) {
window.location.assign(APP_ROOT_URL);
}
});
success: function(response){
window.location.href = response.redirect;
}
Hope the above will help because I had the same problem
You can return the JSON from server with redirect status and redirect URL.
{"redirect":true,"redirect_url":"https://example.com/go/to/somewhere.html"}
And in your jQuery ajax handler
success: function (res) {
// check redirect
if (res.redirect) {
window.location.href = res.redirect_url;
}
}
Note you must set dataType: 'json' in ajax config. Hope this is helpful.
Not sure why, but window.location.href did not work for me. I ended up using window.location.replace instead, which actually worked.
$('#checkout').click(function (e) {
e.preventDefault();
$.ajax('/post/url', {
type: 'post',
dataType: 'json'
})
.done(function (data) {
if (data.cartCount === 0) {
alert('There are no items in cart to checkout');
}
else {
window.location.replace('/Checkout/AddressAndPayment');
}
});
});

How to post like with ajax to instagram? Help me please

i have this code but its not working. it says to me ajax post is success but when i look make refresh i saw its not liked.
<?
if ($data->user_has_liked == false)
{
?>
<span class="<?=$data->id;?>">Like</span>
<? } else { echo 'Liked'; } ?>
<script type="text/javascript">
$('a.like').click(function() {
var mediaId = $(this).attr('id');
$.ajax({
url: "https://api.instagram.com/v1/media/" + mediaId + "/likes?callback=?",
dataType: "jsonp",
data: {
access_token: '<?=$access_token;?>',
_method: 'POST'
},
type: "POST",
success: function(data, textStatus, jqXHR) {
$("."+mediaId+"").text('Liked');
},
error: function(jqXHR, textStatus, errorThrown) {
$("."+mediaId+"").text('Error!<br/>' + textStatus + ' - ' + errorThrown);
}
});
});
</script>
I am building something similar and have ran into this problem recently.
Even though your request is sent as a type: POST the request itself is actually sent as GET. This causes your request to return successful without liking anything. Instead it will return all the data for that Media ID.
If you change your datatype to JSON instead of JSONP you request should work as you wish; however, it may require an HTTPS connection requiring an SSL.

Resources