In one of my Active Admin index pages, I list some records in a table.
I've added the jQuery sortable plugin to be able to sort the records by dragging the items vertically. This works fine, and the position attribute for every records updates correctly (via ajax).
Though, if I refresh Active Admin after the ajax call, I get signed out and have to login again.
Ajax sends this data:
faq[]=1&faq[]=3&faq[]=2
The sort method:
def sort
params[:faq].each_with_index do |id, index|
Faq.update_all({position: index+1}, {id: id})
end
render nothing: true
end
The ajax response is empty and doesn't give any exception.
Why I am signed out?
I had to add the X-CSRF-Token to the ajax headers for some reason. I'm not sure why. Shouldn't rails.js do that for me?
Working solution:
$.ajax({
url: "/faqs/sort",
type: "post",
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
},
data: $(this).sortable('serialize')
});
Related
I need to render a Flask template but the ajax data is only accessible within the POST if statement and does not show when I call a get direct after a posted the data.
I have a working ajax here
$.ajax({
type: 'post',
url: "/query",
dataType: 'text',
data: JSON.stringify({hostname:hostname, bf_id:computerID}),
contentType: 'application/json;charset=UTF-8',
success: function () {
window.location.href = "/query";
}
});
});
The data is successfully posted and the redirect is working. But when the redirect calls the function to render the template, the posted ajax cannot be retrieved.
#app.route('/query', methods=["GET", "POST"])
def query():
hostname=""
if request.method == "POST":
#these values only exist in if statement
hostname = request.json['hostname']
bf_id = request.json['bf_id']
return render_template('query.html', hostname=hostname)
Am I using an incorrect work flow?
Am I using an incorrect work flow?
Yes.
You make the POST request with the data.
You get a response which does things with that data
You then make a GET request without the data
You get a response which can't do things with the data that it doesn't have
The point of Ajax is to make an HTTP request without loading a whole new page.
If you want to load a whole new page, then use a regular form submission without involving JavaScript at all.
I'm using Laravel 5.2 and its Auth scafolding.
I'm trying to make the default login form, to work with Ajax (without reloading page).
I'm using reqwest.js for ajax requests.
Here's my ajax code:
<script data-cfasync="false" type="text/javascript" src="{{asset('js/lib/reqwest.min.js')}}"></script>
<script type="text/javascript">
var thisForm = document.querySelector('#authLogin');
thisForm.addEventListener('submit', function(f){
f.preventDefault();
reqwest({
url: thisForm.getAttribute('action'),
method: thisForm.getAttribute('method'),
contentType: 'application/json',
headers: {
'X-CSRF-TOKEN': document.getElementById('csrf_meta').getAttribute('content')
},
data: '_token='+thisForm.elements._token.value+'&email=myemail#live.com&password=12345',
success:function (response){
}
});
});
</script>
It uses \vendor\laravel\framework\src\Illuminate\Foundation\Auth\AuthenticatesUsers.php login() function to handle the login requests: https://i.gyazo.com/bfe6790934f711f4c1d35f6670c20caa.png
Here's the problem:
1) when I use the default normal login form /login (without ajax), $request->all() in the above class returns all the form fields that were submitted (great, this is perfect)
2) but when I submit the same form /login via an Ajax POST request, $request->all() returns empty array: https://i.gyazo.com/44e2fc6f438bba27a2baab9f7d3b38d6.png
Can anyone tell what I'm doing wrong here? I'm going insane and have no idea what may going wrong. I have searched everywhere for a solution, still nothing.
Thanks.
Sorry, I'm stupid, I figured out the reason it returns empty array.
In my ajax request I had contentType: 'application/json', but my form data was not in JSON format but string params format.
I used this code from
Change table cell from span to input on click-
The replace one for inline edit now i want to post values through ajax and i am not sure how.
I just want to post the comments the users have edited and update them on the database
This is how i got so far:
$.ajax({
type: "POST",
url: "comments.php",//to update the comments
data: "data"
});
Not sure what to put next. Is it possible to post values when user click out of input area? and does the data have to be serialize?
Thanks in advance!
$.ajax({
type: "POST",
url: "comments.php",//to update the comments
data: {"comments":$("yourformId").serialize()},
success:function(res)
{
//Do what ever you want
}
});
And in your comments.php just print_r($_POST) will give you the posted array via ajax
If you use form.serialize you will get all the data from the form you submitted
I am new to ajax so maybe this is obvious. I've tried many different not-working approaches. I have javascript that when you click on a button:
an ajax call that grabs some data from a controller - returns an object
display that data in a template that I will show on the page
Here is the javascript/ajax:
<script type="text/javascript">
$("#show").click(function () {
$.ajax({ url: '/Myproject/result/index',
type: "POST",
data: { id: id},
success: function(result) {
alert("Success:" + result); // Can see getting object back.
}});
$(".resulttable").show();
});
Here is the key line in grails view template:
<g:each in="${allResults}" status="i" var="result">
How do I get the data from the javascript to the gsp code (ie allResults)?
Do I have to "refresh" this template to display new data?
thanks.
You just can't make your javascript/jquery code populate things in the gsp, since the gsp is processed server-side and javascript is processed client-side, after the gsp rendered all html documents and populated them with your model. You need to be aware that your page was already processed, so things like ${variables} won't be reloaded anymore. So when you do this:
$(".resulttable").show();
It's not gonna show the result you're waiting for. You have to use javascript code to reload your result table.
So if you're using ajax here, you should use the function success to alter your html table via javascript/jquery since you already have the response you wanted. Maybe this read can help you. Oh, and I think it would be better if in your ajax call, you would define a dataType (json works great in your case), like this:
$("#show").click(function () {
$.ajax({ url: '/Myproject/result/index',
type: "POST",
data: { id: id},
dataType: 'json',
success: function(result) {
alert("Success:" + result); // Can see getting object back.
}});
$(".resulttable").show();
});
Just to make clear what kind of response you're getting from the controller.
You do not need to write your ajax calls the hard way. There are some Grails intern tags you can use inside your html:
http://grails.org/doc/latest/ref/Tags/remoteFunction.html
http://grails.org/doc/latest/ref/Tags/submitToRemote.html
http://grails.org/doc/latest/ref/Tags/remoteLink.html
Following the links you will find some nice examples...
After $.ajax post request to the controllers action I would like to get info from the server and then update my partial view, for example I have a list rendered in my view I delete an item from the list using the $.ajax post request and then i would like my list to update itself asynchronously.
Here is my function that deletes the item from the list:
$(".btnDeleteCurrentFavSong").click(function () {
var songId = $(this).attr('name');
$.ajax({
type: 'POST',
url: "/Home/DeleteCurrentFav/",
data: { id: songId },
success: ShowMsg("Song deleted successfully"),
error: ShowMsg("There was an error therefore song could not be deleted, please try again"),
dataType: "json"
});
});
Should I somehow redirect to the action on ajax success that returns the list of songs to the view?
if your clicked list item looked like this:
<li name="120">Artist - Title</li>
your javascript could look something like this:
$(".btnDeleteCurrentFavSong").click(function () {
var songId = $(this).attr('name');
$.ajax({
type: 'POST',
url: "/Home/DeleteCurrentFav/",
data: { id: songId },
success: function () {
ShowMsg("Song deleted successfully");
$("li[name=" + songId + "]").remove();
},
error: ShowMsg("There was an error therefore song could not be deleted, please try again"),
dataType: "json"
});
});
It depends upon the user experience that you wish to give. Convention dictates that a user should be shown the effect of their action. From your example it appears that you are doing this via the ShowMsg function. As to whether you should redirect or not, I'm afraid there's nothing authororative out there, do whatever is consistent across your site and would feel natural to users.
option A
return deleted item id from action
on success remove deleted item with js
option B
return partial view from action
on success replace container with rendered html