CodeIgniter using Ajax - ajax

I cant find error when i click on a button nothing happens, i dont get any error in console, very is error maybe in data field?
I have ajax part
$(document).ready(function() {
$('#brisanje').click(function() {
$.ajax({
url: 'localhost/test2/home/ajax',
type: 'Post',
data: form_data,
success: function() {
alert("paun");
}
});
});
});
button
<button type="submit" id="brisanje" class="btn btn-danger btn-xs">ObriĊĦi sliku</button>
and controler
public function ajax(){
redirect('home/login');
}

Try doing this way in your ajax function ,
url : <?php echo base_url(). 'home/ajax' ; ?>,
type : POST,

Answer: Redirecting in the ajax() function caused the problem. I'll leave my junk here anyway, but since I got the checkmark I best provide the actual answer!
This doesn't seem to solve the problem, but I'll leave it here for now anyway
It looks like you're missing the "Action" part of your controller action. You probably are getting a 404 error, although I can't remember exactly what happens when CI cannot find the controller action. Maybe its a 403 error.
Anyway, try naming your ajax function ajaxAction and see if that works. A way to test this would be to browse directly to the url http://localhost/home/ajax (bypass the actual ajax) and you should see any errors that occur.
If you're using a browser with a debugger (most of them, push F12 and see what you get), you should also be able to see the ajax request firing in the console or network tab, and then you can inspect the response for errors.

Related

Spring-Boot: Redirect and Refresh model and page

I have a spring-boot application, with theyemleaf. I repeatedly update the page, and redirect it to the same page, so i expect that the elements of the page get updated:
#GetMapping("/suggested-events/vote/{eventId}")
public String voteForEvents(Model model,
#PathVariable("eventId") Long eventId,
#RequestParam(value = "message", required = false) String message ) {
log.info("The message is: "+message);
SuggestedEvent event = suggestedEventService.findSuggestedEventById(eventId);
ArrayList<SuggestedEvent> events = suggestedEventService.findSuggestedEventsByArea(event.getArea());
model.addAttribute("mainEvent",event);
model.addAttribute("events",events);
model.addAttribute("message",message);
return "/suggested-event/vote";
}
and when a button get pushed in the view it triggers the below post method:
#PostMapping("/suggested-events/vote")
public String voteForASuggestedEvent(RedirectAttributes redirectAttributes){
log.info("You have made a vote");
redirectAttributes.addAttribute("message", "Success");
return "redirect:/suggested-events/vote/1";
}
This second controller method, performs an operation an makes a message, and redirects it to the first method. So, it successfully redirected to the first method and it logs
log.info("The message is: "+message);
but it does not refresh my page, and i do not get the message as model?
When i redirect to the first method, i expect it adds the message to my models:
model.addAttribute("message",message);
But it does not added to my page
and when a button get pushed in the view it triggers the below post
method:
It sounds like this trigger is using AJAX, rather than a form submit. Doing so would match the symptoms you describe.
If you POST to /suggested-events/vote using AJAX, the server will return a 302, and the browser will follow it. However, the response for that 302 is still the result of an AJAX call. You have access to it in your success callback, but the browser isn't going to render it for you.
but it does not refresh my page
If a 302 doesn't cause your page to re-render, this also suggests you're using AJAX.
If you actually use a form submit instead, the browser will re-render using the markup returned by the successful redirect.
This can be verified by using the following two buttons in your vote.html:
<form action="http://localhost:8080/suggested-events/vote" method="POST">
<input type="submit" text="Submit" />
</form>
<button onclick="postmessage();" >Button</button>
<script>
function postmessage() {
$.ajax({
method: 'POST',
data: {},
url: 'http://localhost:8080/suggested-events/vote'
});
}
</script>
The first button will work as expected, and the second button matches the symptoms you describe.
If you are already using a form, please update the question with it (or better yet, the entire Thymeleaf template).
I had the same problem as OP described and Mike's explanation brought me in the right direction.
I am reading a db-table and populating it with thymeleaf using th:each. I wanted to add a javascript-confirmation before deleting an item. Sending an ajax GET without an event-listener and reloading with location.reload(true) didn't reach the #GetMapping("/delete/{id}") in the controller.
This SO-thread gave me the answer to the ajax-call.
<a class="btn btn-danger" href="#" th:onclick="|confirmDeletion('${u.id}')|"></a>
<script th:inline="javascript">
function confirmDeletion(id) {
if (confirm("Delete this id? " + id)) {
var http = new XMLHttpRequest();
http.open("GET", "/delete/" + id, true);
http.addEventListener("readystatechange", function() {
if (http.readyState === 4 && http.status === 200) {
window.location.reload(true);
}
});
http.send();
}
}
</script>
there are many ways to redirect page in Spring, but be sure if the model attribute off message its passing correctly to FrontEnd or passing like parameter to another handler , you can see this document : http://javainsimpleway.com/spring-mvc-redirecting-model-attributes-from-one-controller-to-other-controller/ , hope this is useful !!

Send form to server in jquery

I am learning ASP.NET MVC. I have to submit a to controller side after validation in client-side(in jquery). How this can be done? Should i use <form action="#" method="post"> instead of <form action="Controller/Method" method="post"> and add an event handler in click event of submit button of , to send via ajax etc? What should i do? pls help
You are on the right track, and what you suggested will work.
A better method would be to leave the original action intact, providing backwards compatibility to older browsers. You would then create the event handler as normal, and include code to prevent the default submit behavior, and use ajax instead.
$('#submitbutton').live('click', function(e){ e.preventDefault(); });
The easiest way to do this is to use the jQuery forms plugin.
This is my go-to plugin for this type of thing. Basically it will take your existing form, action url etc and convert the submission to an ajax call automatically. From the website:
The jQuery Form Plugin allows you to easily and unobtrusively upgrade
HTML forms to use AJAX. The main methods, ajaxForm and ajaxSubmit,
gather information from the form element to determine how to manage
the submit process. Both of these methods support numerous options
which allows you to have full control over how the data is submitted.
It is extremely useful for sites hosted in low cost web hosting
providers with limited features and functionality. Submitting a form
with AJAX doesn't get any easier than this!
It will also degrade gracefully if, for some reason, javascript is disabled. Take a look at the website, there are a bunch of clear examples and demos.
This is how I do:
In jQuery:
$('document').ready(function() {
$('input[name=submit]').click(function(e) {
url = 'the link';
var dataToBeSent = $("form#myForm").serialize();
$.ajax({
url : url,
data : dataToBeSent,
success : function(response) {
alert('Success');
},
error : function(request, textStatus, errorThrown) {
alert('Something bad happened');
}
});
e.preventDefault();
});
In the other page I get the variables and process them. My form is
<form name = "myForm" method = "post">//AJAX does the calling part so action is not needed.
<input type = "text" name = "fname"/>
<input type= "submit" name = "submit"/>
<FORM>
In the action page have something like this
name = Request.QueryString("fname")
UPDATE: As one of your comment in David's post, you are not sure how to send values of the form. Try the below function you will get a clear idea how this code works. serialize() method does the trick.
$('input[name=submit]').click(function(e){
var dataToBeSent = $("form#myForm").serialize();
alert(dataToBeSent);
e.preventDefault();
})

yii controller action won't fire from form

I'm trying get a simple ajax call working with yii, not using the native yii means. My goal is to populate state and city fields on input from a zip code field, using a db look up in the create action. I have a separate javascript file,
$('#Accounts_zip').bind('focusout',function(){
$.ajax({
type: 'POST',
url:'/gatesadmin/index.php?r=Accounts/Ziplookup',
data: {zip:$('#Accounts_zip').val()},
success: function(datain, textStatus, jqXHR) {alert(datain.statecode);} ,
error: function(jqxhr, textStatus, errorthrown){alert(errorthrown);},
dataType:JSON
});
alert($('#Accounts_zip').val());
});
and in my AccountsController I have:
public function actionZiplookup()
{
$z = new ZipDao();
$row = $z->GetCityStateByZip($_REQUEST['data']);
header('Content-Type: application/json; charset="UTF-8"');
echo CJSON::encode(array('output'=>$row));
}
and my form is out of the box generated CRUD:
...
<div class="row">
<?php echo $form->labelEx($model,'zip'); ?>
<?php echo $form->textField($model,'zip',array('size'=>10,'maxlength'=>10)); ?>
<?php echo $form->error($model,'zip'); ?>
</div>
...
I know the javascript is working because I get my alert, and if I call the URL directly yii fires the actionZiplookup event because I'm getting the returned json. I just can't seem to be able to get the form to invoke the ajax successfully because I get External Server error in the jquery ajax failure event. I've combed through the net and the closest examples I can find embed the javascript in the form itself and use the Yii::app()-createUrl() method to define the url, but there has to be a way getting the controller action to fire while keeping javascript code in a separate file.
Any help would be greatly appreciated.
It turns out what I was missing can be found here:
How to get response as json format(application/json) in yii? It all has to do with telling the controller to ignore the layout, etc.

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.

Disable AJAX Caching

I am in a bit of a pickle right now. I am building a web page that will get data from a CGI backend. I have no control over the CGI backend, nor the server (so no mod_headers or mod_expires). Also, because of the parameters to the script, I cannot append a unique value (like '&089u0af0d98) to each request. The requests are AJAX using the XmlHttpRequest object. I have tried to set the 'If-Modified-Since' and 'Cache-Control' request headers unsuccessfully. Does anybody have any other ideas for how I can prevent the AJAX response from being cached by the browser?
You can send random parameters using POST, while sending the important vars using GET if you need to.
If you have problems with IE, I know that sending something with POST makes it to stop caching server responses
I use this javascript function ( which in turn uses jquery.ajax function )
the cache: false would do the trick.
This works perfectly for me , may be you can give it a try
function ajax_call(urlString)
{
ret_val="";
$.ajax
(
{
type: "GET",
url: urlString,
async:false,
cache:false,
dataType: 'html',
success: function(msg)
{
ret_val=msg;
},
error:function (xhr, textStatus, thrownError)
{
ret_val=xhr.readyState;
alert("status=" +xhr.status);
}
}
);
return ret_val;
}
I used $.ajaxSetup({ cache: false }); somewhere in my base html-page (default.aspx) in a non-frequent web-system and it worked fine. No pain-in-the-neck caching problems anymore.
I ran into this today, and found that if you want to keep to using get, you can add a hidden form element to the page and have JS set it's value to the current timestamp before submitting the query to ajax.
I add a form element something like this:
<input type="hidden" name="ie_sucks" id="ie_sucks", value="1" />
Then, in the function to submit the form via AJAX I set this hidden input to the current timestamp with something like this:
$('#ie_sucks').val(new Date().getTime());
The above code uses JQuery, so in pure JS it would be something like:
document.getElementById('ie_sucks').value = new Date().getTime();
This is not a pretty solution, but it does work.
I know jQuery's .ajax() call has a parameter called 'cache' which, if set to false, will force requested pages not to be cached by the browser. It's probably worth checking the jQuery source to see how they do it.
(I'm checking it now and will update if I find anything, but posting this answer early in case you or anybody else has better luck finding it.)

Resources