jquery function not redirecting url - javascript

I am working with codeigniter and jquery. I am using ajax to send some info to a codeigniter function to perform a db operation , in order to update the page. After the operation is complete I am trying to refresh the page. However the refresh works inconsistently and usually I have to reload the page manually. I see no errors in firebug:
var message = $('#send_message').val()
if ((searchIDs).length>0){
alert("searchIDs "+searchIDs );
$.ajax({
type: "POST",
url: "AjaxController/update",
data:{ i : searchIDs, m : message },
dataType: 'json',
success: function(){
alert("OK");
},
complete: function() {
location.href = "pan_controller/my_detail";
}
})
.done(function() { // echo url in "/path/to/file" url
// redirecting here if done
alert("OK");
location.href = "pan_controller/my_detail";
});
} else { alert("nothing checked") }
break;
How can I fix this?
addendum: I tried changing to ;
$.ajax({
type: "POST",
url: "AjaxController/update",
data:{ i : searchIDs, m : message },
dataType: 'json',
.done(function() { // echo url in "/path/to/file" url
// redirecting here if done
alert("REFRESHING..");
location.href = "pan_controller/my_detail";
});
}
})
This is just defaulting to the website homepage. again, no errors in firebug

Add the window object on location.href like this:
window.location.href = "pan_controller/my_detail";

Try to use full path like
$.ajax({a
type: "POST",
url: "YOURBASEPATH/AjaxController/update",
data:{ i : searchIDs, m : message },
dataType: 'json',
.done(function() { // echo url in "/path/to/file" url
// redirecting here if done
alert("REFRESHING..");
location.href = "YOURBASEPATH/pan_controller/my_detail";
});
}
})
BASEPATH should be like this "http://www.example.com"

Try disabling the csrf_enabled (config/config.php) and trying it. If that works, then re-enable the protection and, instead of compiling data yourself, serialize the form; or, at least include the csrf hidden field codeigniter automatically adds. You can also use GET to avoid the CSRF protection, but that's least advisable of of the solutions.

Related

Transfer to another page in AJAX call

Hi there is it possible to redirect to another page using ajax? I have this piece of code that I have been working on to try this.
<script type="text/javascript">
$(document.body).on('click', '#btnPrintPrev', function() {
$.ajax({
url: '/pdfdatacal',
data: {
dummydata: "This is a dummy data"
},
});
});
</script>
Now it should be able to carry data to another page and redirect there. Problem is it doesn't.
This is what I am using in my route
Route::get('/pdfdatacal', 'GenerateReportController#pdfdatacal');
Then in the controller
public function pdfdatacal(Request $request) {
return $request->data['dummydata'];
}
My expected result should be a blank page containing the value of dummydata but it doesn't do that in my code. How do I accomplish this?
first your ajax must be something like
$.ajax({
url: '/pdfdatacal',
method: 'post',
data: { dummydata: "This is a dummy data" },
dataType: "JSON",
success: function(response){
console.log(response); // just to check if the data is being passed
// do something you want if ever .
}
});
then in your routes
Route::post('/pdfdatacal', 'GenerateReportController#pdfdatacal');
in your controller
public function pdfdatacal(Request $request) {
return response()->json($request->dummydata);
}
hope it helps ..
Use
window.location.href = "http://yourwebsite.com/pdfdatacal";
In your success call
The idea is that you send data to your controller, it sends back a response, then you redirect from javascript to where you want.
$.ajax({
url: '/pdfdatacal',
type : 'GET',
data : {
dummydata: "This is a dummy data"
},
success : function(data) {
window.location.href = "http://yourwebsite.com/pdfdatacal";
}
});
But if your controller does nothing with the data you send, then you don't need to use ajax at all, simple redirect using javascript.
you could use window.location.assign('your URL here!'); in the success.
success : function(data) {
window.location.assign('your URL here!');
}

how to prevent redirect on form submit

i am getting a form with user parameters when i make an AJAX call to a page which later on is submiited to a url so that i can create a session for the same user in advance and when
that person goes to that site he sees his name there.
i created one div tag with id "abc_session", assign that form (whose id is fm1) to it,and submitted the form.
now as per the requirement session is created but page automatically gets redirected to that site url to which form is submitted.i just don't wan't that to happen.
can anyone please suggest something..or some workaround
the form that AJAX returns looks something like this:
<html>
<body onload="document.fm1.submit();return false">
<form name = "fm1" method="post" action = "https://abcd.com/abc ">
<input type=hidden name ="name" value="xyz">
<input type=hidden name ="login_parameters" value="CDF5D71C5BDB942EE2FB6C285B8DEBFE4C5675137B615CD2276571813AAC872AC8942E26B71026414BED1FEA09427D0B20A50FE2F70032D2E5B382598EC3C71D73EAB4ECBF7273A73BEB98ACEA4A0B775E7772BDC7C6746C355">
</form></body>
</html>
and the script goes like this
$(document).ready(function() {
function callwebsite()
{
$.ajax({
url: "/NASApp/benemain/website",
data: {},
type:"POST",
dataType: 'text',
cache: false,
success: function (data) {
alert("Call made to website.. ");
console.log(data);
document.getElementById("abc_session").innerHTML=data;
document.fm1.submit();
},
error : function(response){
console.log('ERROR');
},
statusCode : {
500 : function() {
console.log('500 error');
window.location.reload(true);
},
401 : function() {
console.log('401 error');
window.location.reload(true);
},
404 : function(){
console.log('400 error');
}
}
});
}
callwebsite();
tried extracting the data and maiking another ajax call as suggested by quentin but getting this error "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource.This can be fixed by moving the resource to the same domain or enabling CORS."
$.ajax({
url: lcAction,
data: {partner_id:lcPartner,login_parameters:lcLP },
type:"POST",
headers:{'Access-Control-Allow-Origin': '*'},
dataType: 'text',
//crossDomain: true,
//cache: false,
success: function(data)
{
alert("success");
},
error:function(response)
{
//alert("error");
console.log(response);
}
});
You are submitting the form:
document.getElementById("abc_session").innerHTML=data;
document.fm1.submit(); // Here
Don't do that.
Extract the data from it and make another Ajax request.
You should use e.preventDefault() as soon as you submit the form.

AJAX showing error message

I have one form ,when i click submit button am saving those values and on button click am calling "SaveData() " method.
So when i try to add data and click on submit button and nothing is happening am getting following errors in my browser log.
My onclick function code
function requestReferral() {
var nameperson = $("#namefield").val();
var contact1 = $("#contact").val();
//Till this part working i mean alert is printing .
$.ajax({
url: '/mycontroller/myfunction',
data: 'name='+nameperson+'&contact='+contact1,
type: 'post',
success: function(result){
data = jQuery.parseJSON(result);
if(data.result == "SUCCESS"){
clearMyFormData();
} else {
showMessage();
}
}
});
}
my error is
Failed to load resource: the server responded with a status of 500 (Internal Server Error) with my controller url www.example.com/mycontroller/myfunction
First of all, check if your url is ok, for example, if you are using php with codeigniter your url need to be like this:
url: <?php echo base_url()?>mycontroller/myfunction
and second, when I used ajax, I send data like this
postData = {
name: nameperson,
contact: contact1
}
$.ajax({
url: '/mycontroller/myfunction',
data: postData
type: 'post',
success: function(result){
data = jQuery.parseJSON(result);
if(data.result == "SUCCESS"){
clearMyFormData();
} else {
showMessage();
}
}

not going through the django view through ajax post data

I am doing the login throgh ajax. jquery function is working fine but its not going to the ajax url. So django view is not getting executed.
Ajax.html
$(function()
{
localStorage['domain'] = "http://122.172.64.142";
var domain = localStorage['domain'];
$('#fac1').on('click', function () {
var username = $("#username").val();
var password = $("#pwd").val();
data = {
name: username,
password: password
};
alert(domain);
$.ajax({
url: domain + "/login/login_android_here/",
type: "POST",
data: data,
success: function (response) {
alert("success");
window.location = 'file:///android_asset/www/posts.html';
},
error: function () {
alert('some error in login');
}
});
return false;
});
});
My django views.py
#csrf_exempt
def login_android(request):
print "i am in view"
if request.method == "POST":
print "you are in method"
username = request.POST['name']
password = request.POST['password']
login_api(request,username,password)
#return HttpResponseRedirect('/home/')
messages.success(request, 'You Loged In Successfully')
response = json.dumps(username)
return HttpResponse(response, mimetype="application/json")
When i click on login button i am getting alert but its not getting entered to view. Url is correct.
I would first recommend using Chrome with the developer tools console open.
You could change you alerts for console.log().
When your trying window.location = 'file:///android_asset/www/posts.html';
You are trying to access a local resource. If I post that in my Chrome developer tools I get back
Not allowed to load local resource: file:///android_asset/www/posts.html
If you would use window.location.replace("a url to your view"); this will work like a HTTP redirect.
for more information redirect page
and you should be able to see your view.
I was made a silly mistake. I provided a wrong domain address on this page. Now it worked.
localStorage['domain'] = "http://122.172.64.142";
This address was wrong. Thats why it was not able to enter in to the view.
You forgot dataType ajax param
$.ajax({
url: domain + "/login/login_android_here/",
type: "POST",
data: data,
dataType : 'json', //dataType param IS MISSING
success: function (response) {
alert("success");
window.location = 'file:///android_asset/www/posts.html';
},
error: function () {
alert('some error in login');
}
});

passing variable back from the server to ajax success

User fills input texts, presses the button Submit. The data sends to the server to be stored and result returned back. Fancybox window with result appears. My question is: how to display the result $res1 in the fancybox?
$.ajax({
type:"POST",
url:"index/success",
async:false,
data:{ name:name, password:password},
success:function ()
{
var html='$res1 from the server should be here instead of this string';//var html=$res1.
$.fancybox(
{
content: html,//fancybox with content will be displayed on success resul of ajax
padding:15,
}
);
}
});
=========================
OK, still doesn't work (returns in the fancybox the whole page+ the word "hello" on top instead of the message "hello"). Below is my update regarding the answers below, that doesn't work properly:
PHP:
<?php
$res1="hello";... // handle logic here
echo $res1; // print $res1 value. I want to display "hello" in the fancybox.
?>
AJAX
$.ajax({
type: "POST",
url: "index/success",
async: false,
data: {
name: name,
password: password
},
success: function (html) {
$.fancybox(
{
content: html,//returns hello+page in the fancybox
//if I use the string below instead of the upper one, the fancybox shows "The requested content cannot be loaded. Please try again later."
// content: console.log(html)
padding:15,
}
});
=============
New update:
Fixed!!! The problem was the data ( "hello" in the example above) was sent to the template in the framework, and template was displayed.
That's why.
Fixed.
Thank you.
Everybody.
Assuming you're using PHP:
PHP:
<?php
... // handle logic here
echo $res1; // print $res1 value
?>
AJAX:
$.ajax({
type: "POST",
url: "index/success",
async: false,
data: {
name: name,
password: password
},
success: function (html) {
// given that you print $res1 in the backend file,
// html will contain $res1, so use var html to handle
// your fancybox operation
console.log(html);
}
});
Enjoy and good luck!
$.ajax({
type:"POST",
url:"index/success",
async:false,
data:{ name:name, password:password},
success:function(html){ // <------- you need an argument for this function
// html will contain all data returned from your backend.
console.log(html);
}
});

Categories

Resources