Ajax reloading page - ajax

I am not too familiar with ajax, if you could help me that would be great.
The following script sends the data to my controller in Codeigniter and refreshes the page, however I was wondering if there was a way I could do this without the page totally reloading...hope that makes sense.
'onComplete' : function (event, queueID, fileObj, response, data) {
$.post('<?=site_url('admin/news_manager/uploadify');?>',{filearray: response},function(info){
location.reload();
});

Omit the location.reload(); from your script.
But if you want some part of the page to show data from the post, you need to insert that somewhere in the page.
In other words:
$("#IdOfTheHtmlElement').html(info); instead of location.reload();
I hope this helps.

Related

Laravel: controller not teletransporting me (redirect-ing me) to the page

from Ajax the controller does get the keyword I want, as it confirms it (because I echo it), and my idea was that on getting that keyword, it should redirect to the page I want. Yet, it does not, and also, while it does change the locale, I have to reload the page, otherwise, it won't show any translation and locale changes on the page. In Firebug when I hover over the POST, I get the correct URL to where I would want to go: sort of http://myweb.com/es but the controller does not change the http URL box of my browser on my web to go there.
I am simplifying the Controller code here, but actually I will want it to go to different URLs depending on the keyword it gets, something that I would do with a switch statement or IF else if etc.
So the controller is as simple as this:
public function changelanguage()
{
$lang = \Input::get('locale');
echo "I got $lang";
Session::put('locale', $lang);
return redirect('/es');
}
If instead of using ajax I use a Form, then I dont need to reload, the Action of the form makes the controller change the locale and translate the page without reloading. But I need to use ajax and in any case, the controller does get correctly the keyword ('en', 'es', 'de' etc ) for languages, so it should take it from there and redirect me to the URL page, but it just doesnt move.
if you are curious about the Ajax, here it is, but it does send the keyword as I said.
$(document).ready(function(){
$('.choose-language').on('click', function(e){
e.preventDefault();
var selectedlanguage = $(this).data('value');
$.ajax({ // so I want to send it to the controller
type:"POST", // via post
url: 'language',
data:{'locale': selectedlanguage},
}); // HERE FINISHES THE $.POST STUFF
}); //HERE FINISHES THE CLICK FUNCTION
}); // HERE FINISHES THE CODE
ROUTES
Route::post('language', array(
'as' =>'language',
'uses' => 'LanguageController#changelanguage'
));
If you’re trying to perform the redirect in the AJAX-requested script, then it won’t work. You can’t redirect from a script request via AJAX otherwise people would be doing all kinds of nefarious redirects.
Instead, set up a “success” handler on your AJAX request that refreshes your page if the request was successful. It can be as simple as:
var url = '/language';
var data = {
locale: $(this).data('value');
};
var request = $.post(url, data)
.success(function (response) {
// Script was successful; reload page
location.reload();
});
I’m not sure how you’re allowing users to select locales, but since you need a reload any way I think AJAX is pointless here. Just have a traditional form that submits the new locale to an action, set the locale in a session/cookie/whatever, and then redirect back to the referring page.

send hyperlink query string to server and get result using jquery ajax

i am making a simple site in php. I have a product page and there is a link on product page that says add to wishlist so when a user clicks on that link the product is posted to the server and the page is redirected from the backend. but I want to do it using jquery ajax so that my page is not reloaded. can somebody please provide a snippet of code on how to do that ?
$('#anchorId').click(function(){
$.ajax({
url:"foo",
data : "the query string",
...
...
success: function(result){
// success code.
}
});
return false; // prevents the default behavior of anchor click.
});
The best way to learn jQuery, is to visit the API site. (Which seems to be down at the moment)
The ajax category
Update:
$('body').on('click', 'a.foo', function(){
// What you want here.
return false;
}
This will catch any click on anchors with the foo class under <body> no matter when they were created("runtime" or with the page load) .

codeigniter get URL after ajax

I am trying to get the URL i see on my browser after i do an ajax request but the problem is that it changes the URL with the Ajax URL.
ex.
i am on domain.com/user/username
and the ajax URL that i call is in domain.com/posts/submit
when i echo $_SERVER['REQUEST_URI'] on the posts controller in submit function it will display the second URL and not the first... how can i assure and get the first inside the ajax function that its 100% valid and not changed by the user to prevent any bad action?
Thanks
There is HTTP_REFERER but I don't know if that works for javascript requests. Another problem of this: It won't work for all browsers.
You could try the following:
1.) As the user visits domain.com/user/username the current URL is saved with a token - let's say 5299sQA332 - into the database and the token is provided through PHP to Javascript
2.) The ajax request will send this token along with the other variables needed to the controller through POST
3.) In your ajax controller you search the database for the given token 5299sQA332 and there you have your first URL and you can be damn sure, that it hasn't been manupulated
:)
If I understand you correctly, you want to make sure the ajax call is coming from the page it is supposed to be on? In that case just pass a token with the call.
In the controller function set a token variable in session;
public function username() {
$this->session->set_userdata('ajax_token', time());
}
Then in the view with the js;
$.ajax({
url: '/user/username',
type: 'post',
data: 'whatever=bob&token='+<?php echo $this->session->userdata('ajax_token'),
success: function( data ) {
},
error: function( data ) {
}
});
Then in you form validation, do a custome callback to check they are the same.
Have you looked at CodeIgniter's Input Class ?
$this->input->get('something', TRUE);
i used javascript for it and it seems to work... hope not to have any problems in the future with it...
ps: i dont get why my other answer was deleted.. thats the answer anyway.

Post or Get, which is more appropriate to call a simple asp page via jQuery Ajax

I have a html page that I need to call another asp page to get the date/hour via an ajax call. Which method would be better or best, Post or Get?
Since I am only retrieving a few bits of data and not sending any data to the page info is one method better or proper than the other?
This is the simple ASP page.
<%#LANGUAGE="VBSCRIPT"%>
<% Option Explicit %>
<%=Weekday(Date)%>
<%=Hour(Now)%>
And this is the Ajax call to the asp page above.
jQuery.ajax({
url: '/v/timecheck.asp',
type: 'GET',
cache: false,
success: function(data){
// do something with the data
},
error: function() {
//do something on error
return false;
}
})
The reason I have to make the Ajax call to this ASP page is I cannot query the server direct from this page.
My rule of thumb when deciding either one is:
The interaction involve database, POST
The interaction involve sensitive information, POST
Requesting simple data, GET
Sending user input, POST
Sending/requesting large data, POST
Clean URL, POST
As you can see, most cases involve POST for many reason. Such as in your case, you could use GET or POST. Either way, jQuery make calling both function easy.
A simpler $.POST
$.post("/v/timecheck.asp", function (data) {
if (data.time != "") {
//retrieve success
{
else
{
//retrieve fail
};
});
or simpler $.GET
$.get("/v/timecheck.asp", function(data) {
if (data.time != "") {
//retrieve success
{
else
{
//retrieve fail
};
});
I would use POST, I think there is a secirity reason in ASP.NET to use POST, but not sure if this relates to IIS (and possibly ASP)
The W3C have a paper with guidelines on when to use GET or POST at: http://www.w3.org/2001/tag/doc/whenToUseGet-20040321#checklist
Using a GET request allows the result to be cached by the browser whereas a POST request won't be cached and the page will be re-retrieved every time.
In your code example you are not changing any data as a result of the request and are only providing the day and hour, so using a GET and setting the cache HTTP headers to 1 hour would give you the best performance and reduce load on your server.

jquery ajax post callback - manipulation stops after the "third" call

EDIT: The problem is not related to Boxy, I've run into the same issue when I've used JQuery 's load method.
EDIT 2: When I take out link.remove() from inside the ajax callback and place it before ajax load, the problem is no more. Are there restrictions for manipulating elements inside an ajax callback function.
I am using JQuery with Boxy plugin.
When the 'Flag' link on the page is clicked, a Boxy modal pops-up and loads a form via ajax. When the user submits the form, the link (<a> tag) is removed and a new one is created from the ajax response. This mechanism works for, well, 3 times! After the 3rd, the callback function just does not remove/replace/append (tested several variations of manipulation) the element.
The only hint I have is that after the 3rd call, the parent of the link becomes non-selectable. However I can't make anything of this.
Sorry if this is a very trivial issue, I have no experience in client-side programming.
The relevant html is below:
<div class="flag-link">
<img class="flag-img" style="width: 16px; visibility: hidden;" src="/static/images/flag.png" alt=""/>
<a class="unflagged" href="/i/flag/showform/9/1/?next=/users/1/ozgurisil">Flag</a>
</div>
Here is the relevant js code:
$(document).ready(function() {
$('div.flag-link a.unflagged').live('click', function(e){
doFlag(e);
return false;
});
...
});
function doFlag(e) {
var link = $(e.target);
var url = link.attr('href');
Boxy.load(url, {title:'Inappropriate Content', unloadOnHide:true, cache:false, behaviours: function(r) {
$("#flag-form").live("submit", function(){
var post_url = $("#flag-form").attr('action');
boxy = Boxy.get(this);
boxy.hideAndUnload();
$.post(post_url, $("#flag-form").serialize(), function(data){
par = link.parent();
par.append(data);
alert (par.attr('class')); //BECOMES UNDEFINED AT THE 3RD CALL!!
par.children('img.flag-img').css('visibility', 'visible');
link.remove();
});
return false;
});
}});
}
Old and late reply, but.. I found this while googling for my answer, so.. :)
I think this is a problem with the "notmodified" error being thrown, because you return the same Ajax data.
It seems that this is happening even if the "ifModified" option is set to false (which is also the default).
Returning the same Ajax data three times will cause issues for me (jQuery 1.4). Making the data unique (just adding time/random number in the response) removes the problem.
I don't know if this is a browser (Firefox), jQuery or server (Apache) issue though..
I have had the same problem, I could not run javascript after I call boxy. So I put all my javascript code in afterShow:function one of boxy attributes. I can run almost except submit my form. My be my way can give you something.

Resources