How to use Html Anchor <a> to send AJAX Post Request - javascript

I am using the following tag to let the users like the post
Like
I get the id of the <a> through Javascript which is actually the post_id and send the data to like.php using the following GET method.
post_id = 22;
xrequest.open("GET","like.php?post_id="+post_id+",true);
xrequest.send();
I have two questions
How can I send this request using POST Method?
(Note that there is not any <form>...</form> around the tag.)
If I use the above mentioned GET Method, Is it secure?

Since you've tagged jQuery, I assume you are using it. If so, you can do it like:
// attach a click handler for all links with class "like"
$('a.like').click(function() {
// use jQuery's $.post, to send the request
// the second argument is the request data
$.post('like.php', {post_id: this.id}, function(data) {
// data is what your server returns
});
// prevent the link's default behavior
return false;
});
Regarding your second question: No, it does not really make it safer unless you are doing it within SSL (https). a middle-man can still intercept your message mid-way and read the contents. POST makes it more indirect (to intercept and read the payload) than GET, but not safer.

To use POST to send the like link id you can do the following:
$(document).ready(function() {
$("a.like").click(function(event) {
var data = event.target.id;
$.ajax({
type: "POST",
url: "like.php",
data: data
});
});
});
updated, there was a typo in my code.

If i understand your question correctly, something like this should work for you:
$('#link_22').click(function(){
var link = $(this).attr('id');
$.post('/like.php/', {post_id: link});
return false;
})
Then you can reach this from PHP with something like:
$_POST['post_id'];

Related

How to execute a php file into jquery without post and get method?

I'm trying to program a custom contact content manager in HTML/CSS with PHP/mySQL/Jquery to make it dynamic.
I have my login form which send the $_REQUEST to my connection.php, when the auth is correct, I return json to my Jquery and when it is good, I use window.location.replace to redirect the user to the control panel.
When I'm on the index.php of the control panel, I want to check if the user's session_id is into my sql database and if it exceeded the expiration time.
I have my functions which check this and return the good value but I want to execute it and send the result to my jquery without using GET or POST method.
If I remember, you have
$.ajax({
type: "POST", //or GET method
dataType: "json",
url: $(this).attr('action'),
data: $(this).serialize(),
success: function({
}),
error: function({
})
});
But you must specify the element "data" no? can I use it without data and put "file.php" as url without POST or GET method?
I want to get into my success method the result of my php functions :
if the json return false, the user can access the page.
if the json return true, I will logout the user and redirect him to the login.php
I'm doing this system because I don't want anybody can access the control panel by writing the correct url or after 4 days.. I put an expiration time to one hour (for the moment) for anybody who login into the control panel and I check on all page that the expiration time isn't exceeded.
I saw that using 'window.location.replace' doesn't allow to return to the previous page.. has anyone a solution? I don't want to have an event to redirect the user, only redirect him to another url (my file.php) after a condition.
Currently, I use it to execute php without POST, GET method with $.ajax..
$(document).ready(function(){
$(function(){
var ticket = '<? echo $tickets; ?>';
console.log(ticket);
if ( ticket === '' )
$(".new_ticket h2").after('<p>Aucun nouveau ticket.</p>');
else
{
console.log('else');
$(".new_ticket h2").after('<p>Il y a un ticket.</p>');
}
});
});
I have a last question, when I write :
$(document).ready(function(){
$(function(){
}
Is it directly executed by jquery when the DOM is ready? can I write mutliple '$(function(){}' in a file ?
Thanks for the help!
What is the problem with using POST or GET? It works perfectly fine.
Here foobar.php returns a json object with status in it. Change it to whatever your script return.
$.post('foobar.php', function(data) {
if( data.status === false) {
//All good
}else {
//Redirect
window.location.href = "http://newpagehere.com/file.php";
}
});
With window.location.href you will be able to use the back and forward buttons.
And yes, when using $(document).ready(function() { }); it runs when the DOM is ready.
http://api.jquery.com/ready/
One last thing is that I would not rely on Javascript here, I would do all checking with PHP instead when the user changes page. I would also handle the redirection there.

JQuery Ajax POST throwing an empty error without making the request

I have a function that makes an Ajax request for any anchor. The request method can be GET or POST. In this case, I want to make a POST without using a form but the Ajax request throws an error before even sending the request. The error has the value "error" and all error/failure description variables are "".
function loadPage(url,elem_id,method,data) {
ajaxLoading(elem_id);
$.ajax({
type: method,
url: url,
data: data,
success:function(data){
$("#"+elem_id).html(data);;
},
error:function(request,textStatus,error){
alert(error);
}
});
}
When the function is called the params are these (copied from the js console):
data: "partial=yes"
elem_id: "page"
method: "post"
url: "/projects/2/follow"
As asked, here is the code that calls the loadPage function.
$("body").on("click","a.ajax",function(event) {
var _elem = getDataElem($(this));
var _method = getRequestMethod($(this));
var _partial = getRequestPartial($(this));
handlers.do_request(event,$(this).attr("href"),_elem, _method, _partial);
});
var handlers = (function() {
var obj = {};
obj.do_request = function(event,url,elem_id,method,data) {
event.preventDefault();
loadPage(url,elem_id,method,data);
history.pushState({selector:elem_id,method:method,data:data},null,url);
};
}());
After the failure of the Ajax request, the request is made by default and it responds sucesss. In all I have read, this seems to be a valid way to make a POST request (that doesn't need a form).
Am I doing something wrong in the function? Why is the error information empty?
Thanks
EDIT:
I have been thinking, for a POST from a "form" that function works, when the variable "data" is made with the serialize function (e.g. "var data = $(this).serialize();"). Could it be that the format of the "data" when I make a POST without a "form" is wrong in someway? Maybe the JQuery Ajax function doesn't accept a simple string like "partial=yes" as data when a POST is made. Any thoughts on this?
I just experienced this problem and after an hour or two, thought to try setting cache to false. That fixed it for me.
$.ajax({
url: url,
cache: false,
type: method
});
Unfortunately, when I removed cache again, my request was working as if it had never had a problem. It seems as if setting cache:false made something 'click'.
Oh well.
Just a guess, but in the docs the type parameter is in all caps, i.e. 'POST' and not 'post'.
Try:
function loadPage(url,elem_id,method,dat) {
ajaxLoading(elem_id);
$.ajax({
type: method,
url: url,
data: dat,
success:function(data){
$("#"+elem_id).html(data);;
},
error:function(request,textStatus,error){
alert(error);
}
});
}
I'm wondering if you are running into a problem using a variable named after a keyword. If this doesn't work, try calling loadPage with no arguments and hard coding all of your ajax parameters, just to see if that works.
Could not solve the problem, neither could find the reason why it was happening. Although, I found a way around, by using a hidden empty form instead of an anchor with the method 'POST'. For a form, the function worked nicely.
Thanks for the answers

Force Backbone fetch to always use POST

I have a Collection that needs to POST some data to its url to get the data it needs. The answer to these two questions, Fetch a collection using a POST request? and Overriding fetch() method in backbone model, make it seem like I should be able to get it to work like this:
fetch: function( options ) {
this.constructor.__super__.fetch.apply(this, _.extend(options,{data: {whatever: 42}, type: 'POST'}));
}
, but Firebug still shows me a 404 error that is happening because a GET is being executed against the url in question (and the underlying Rails route only allows POST). Should this be working? If so, what else might I try? If not, what have I done wrong?
After reading the question again, here's a way to force the fetch to use POST per fetch call. (Thanks for the comments)
yourCollection.fetch({
data: $.param({id: 1234}),
type: 'POST',
success: function(d){
console.log('success');
}
});
Another approach is to override the AJAX implementation itself to use POST for all calls.
Backbone.ajax = function() {
var args = Array.prototype.slice.call(arguments, 0);
_.extend(args[0], { type: 'POST' });
return Backbone.$.ajax.apply(Backbone.$, args);
};

use javascript variable into python Block

I want to use JavaScript variable into python Block.
<script>
$(document).ready(function() {
$("#WO_cpp_id").change(function() {
id = this.selectedIndex;
ajax('{{=URL(r=request,f='get_CIs',vars={'CPP_Id':'#here I want to use id variable')}}', ['WO_cpp_id'], 'WO_ci_id');
})
.change(); }); </script>
Thanks in Advance
Your python code is running on the server. Your JavaScript code (as quoted) is running on the client. So you can't directly use a JavaScript variable in your Python code. What you do is send the data you want to send from the client to the server in any of several ways.
One of those ways is "ajax". This client-side code will send the contents of the variable foo to the server as a "fooParameter" parameter on a POST:
var foo = "This is some information";
$.ajax({
url: "myscript.py",
method: "POST",
data: {fooParameter: foo},
success: function(responseData) {
// Successful POST; do something with the response if you want
},
error: function(jxhr, statusText, err) {
// Error, handle it
}
});
More in the jQuery docs and the Wikipedia article on ajax.
That won't work. Python runs on the server before the page is ever rendered on the client; Javascript runs in the browser after the page is rendered. The id variable isn't even set when the Python code runs.
Instead, you should have your javascript code add the extra data you want to set to an existing query string (or by using the data attribute of jQuery's ajax options).

jQuery - can I "append" an additional parameter to every get/post request made

I would like to extend jQuery such that every post/get request made on the client side will have an additional parameter sent (always the same key : value). I need this to detect on the client side if the request was made through jQuery, since I have several js libs at work. The additional param is simply jquery : true. A typical request will normally look like this:
jQuery.post('/users/save', { name : 'john', age : 24 }, ....)
Is there a way to append this addition parameter by extending jQuery or some other way such that it'll look like so when it reaches the server:
{ name : 'john', age : 24, jquery : true }
Basically I want to intercept the request and edit it's parameters before they reach the server side. thanks.
Look at beforeSend(XMLHttpRequest)
A pre-callback to modify the
XMLHttpRequest object before it is
sent. Use this to set custom headers
etc. The XMLHttpRequest is passed as
the only argument. This is an Ajax
Event. You may return false in
function to cancel the request
You should be able to use it with ajaxSetup
Try putting the following somewhere in your code before any AJAX request would be executed:
$.ajaxSetup({
beforeSend: function(xhr) {
var newUrl = this.url;
if (newUrl.indexOf("?") != -1) {
newUrl = newUrl + '&jquery=true';
} else {
newUrl = newUrl + '?jquery=true';
}
xhr.open(this.type, newUrl, this.async);
}
});
This will trigger a function before the sending of any AJAX request. The function determines what the new URL should be (based on whether or not any query string has already been attached), then reopens the XMLHttpRequest with the 'jquery=true' attached at the end.
Here's a working demo of this: http://jsfiddle.net/uz9zg/

Categories