Make $.ajax fail - php

This is rather an odd question, but, I want to make $.ajax fail to check my fail trigger in it, I have this jQuery code:
$(document).ready(function () {
$("#trigger").on("click", function () {
$.ajax({
url: "text.php",
success: function (data) {
$(".log").html(data.slice(0, 1000));
//alert("Load has been performed");
},
fail: function () {
$(".msg").html("Something went wrong...");
}
});
});
});
And am calling this PHP code:
<?php
function foo()
{
return "bar";
}
print foo();
return false;
?>
and want to make sure that the fail: ... is working. How do I do this?
EDIT
I have amended the text.php to be this:
<?php
throw new LogicException("Failed");
Also:
<?php
header("HTTP://this.does.not.exist");
But this still shows in the $(".log") area even though it has failed.
Noticed I was using the fail function wrong, now amended my jQuery to:
$(document).ready(function () {
$("#trigger").on("click", function () {
$.ajax({
url: "text.php"
}).done(function (data) {
$(".log").html(data.slice(0, 1000));
}).fail(function () {
$(".msg").html("Something went wrong...");
}).always(function () {
alert("One way or another, we did it!");
});
});
});
Also if it helps, I am using these scripts for jQuery libraries:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

You could send a header returning an error.
For example:
header("HTTP/1.0 404 Not Found");
Or of course have your script generate a fatal error ;-)

Two suggestions:
Change the .fail callback call to .error and
Try it by returning an error status code from your server like jeroen suggested,
header("not-real.php", true, 404);

Related

FUELPHP Ajax request without jquery

I have looked everywhere, I found, that FUELPHP not handle Ajax requests, native and easily, as does RubyOnRails for example.
There must be done manually through jquery, unless I'm missing something I see is this: you have to use preventDefault () for the submit event of the form to create a post, product or whatever, and use the $ function post () to send the relevant parameters, which I think is ridiculous for a framework that claims to be based on the best ideas from other frameworks.
Please tell me if I'm wrong, I like FUELPHP, and I'm thinking about choosing it as PHP framework, but I want to be clear about this.
why not you can handle ajax in fuelphp like this.
.01. create ajax request in your view or public/assets/ create javascript file,
<script> $('.login').on('click',function(){
$.ajax({
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (e) {
alert("loading");
}, false);
return xhr;
},
url: "<?php echo \Uri::create('auth/login'); ?>",
type: "POST",
dataType: 'json'
data: {'username':$('#username').val(), 'password':$('#password').val()},
success: function (data) {
alert(data.status);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error");
}
});
});
</script>
.02. after that you can handle post data in classes/controller/ create auth.php and login method like this,
<?php
class Controller_Auth extends \Controller_Template {
function action_login() {
if (\Input::is_ajax()) {
if (\Input::param('username') and \Input::param('password')) {
$username = \Input::param('username');
$password = md5(\Input::param('password'));
//check password and username or anything
$msg = 'fail';
return json_encode(array('status' => $msg));
}
}
...
}
}
?>
you can handle data like this. i think you got something. and this is helpful.

JQuery won't load clear url?

I want to load simple codeignitier controller, but no success i get 404 error.
It looks like jquery load does not support pretty/clear urls? Is it possible and how?
When i try to load some file using this same code it works perfectly, but when i try to load codeignitier controller function nope, i get 404 in Console.
<script type="text/javascript">
$(document).ready(function () {
$("#season").load('https://www.example.co/index.php/system/example');
//i already tried without 'index.php'
});
</script>
when i check does load function works using some simple file, it works perfectly:
<script type="text/javascript">
$(document).ready(function () {
$("#season").load('https://www.example.co/test.php');
});
</script>
and controller:
public function example(){
echo "EXAMPLE";
}
This link exists and is not 404 (of course without example):
https://www.example.co/index.php/system/example
Try by pass it as
window.location.href = '<?php echo base_url('controller/method'); ?>'
I solve it by adding '?' before index.php.
So this is result:
<script type="text/javascript">
var PI = {
onReady: function() {
$.ajax({
type: 'GET',
url: '/index.php?/system/getseasons/SC0',
success: function (response) {
alert('success');
$("#season").html(response);
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
})
},
};
$( document ).ready( PI.onReady );
</script>

Control Not going to the Controller

i am using codeigniter. I have set a form validation via jquery and after validation the data /control is not moving on to the Controller.
Here is my jquery code
var data1 = {
username:$("#username").val(),
password:$("#password").val()
}
$.ajax({
type:'POST',
url:base_url+"site/chk_info",
data:data1,
success: function (response){
alert (response);
},
error:function (){
alert ("Sorry we are getting problems plz try again latter");
}
}); // end ajax
Here is my controller method.
public function chk_info(){
return true;
}
The problem is in jquery the controll in not entering into the success function it always getting into the error function.
chk_info() is only returning true IF PHP was listening and acting upon it.
You should be echo-ing true like this instead:
public function chk_info(){
echo 'true';
}
try this i think its url problem
$.ajax({
type:'POST',
url:'<?php echo base_url() ?>site/chk_info',
data:data1,
success: function (response){
alert (response);
},
error:function (){
alert ("Sorry we are getting problems plz try again latter");
}
});

Not able to retrieve $_POST values through ajax call

I am having little problem with ajax. Here is my code what I have done so far:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
getLocation();
});
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else{
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position)
{
latitude =position.coords.latitude;
longitude= position.coords.longitude;
$.post({ url: 'test.php',
data : ({lat :latitude,long:longitude}),
success: function(data){
alert('done');
}});
}
What I am trying to do is call the function on document ready and trying to retrieve the value of ajax call on the same file where I did call this script. Whenever I reload the page, I don't get any value of :
print_r($_POST['lat']);
I don't know what is the actual problem,I already checked in console and didn't get any error. Please help.
To get the value you need to print it in success callback
$.post({ url: 'test.php',
data : ({lat :latitude,long:longitude}),
success: function(data){
alert(data);
}
});
and if you put
if (isset($_POST['lat']) {
print_r($_POST['lat']);
}
you will get the value in alert box.
EDIT: You can check in php if the reqest came from Ajax using this:
if ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
if (isset($_POST['lat']) {
print_r($_POST['lat']);
}
exit();
}
if you put this at the begining you will see only that print_r from ajax call.
The value you are printing is not an array. So you have to print it like,
print $_POST['lat'];
(OR)
echo $_POST['lat'];
AND NOT
print_r($_POST['lat']);
If you want to print all post values mean then you can print it as,
print_r($_POST);
I have solved my problem by own. Here what I have done. I made one more file called test2.php and put my php script over there and call that file in my ajax call. Here the code.
Test.php
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
getLocation();
});
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else{
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position)
{
latitude =position.coords.latitude;
longitude= position.coords.longitude;
$.ajax({ url: 'test2.php',
data : ({lat :latitude,long:longitude}),
type: 'post',
success: function(data){
if(data=='true'){
window.location = "http://example.com";
}
}
});
}
</script>
Test2.php
//just for example
<?php
echo 'true';
?>
Hope this will help someone in future.

call php file from javascript

Hi I have searched the web but can't get this to work. I'm trying to call the file databaseUpdated.php (placed in the same folder as the index.php file) from a function that is called every 10 seconds.
If I place the following in the index.php
<script type='text/javascript'>updateboolean();</script>;
the function is runned so thats not the problem, the problem is that the php file is not read.
the file databaseUpdated.php
<body>
<?php
echo ("<script type='text/javascript'>updateboolean();</script>;");
?>
</body>
And here is my functions in the javascript
$(document).ready(function(){
setInterval(function() {
$.get("databaseUpdated.php");//Can't get this to work any obvious reason for this (And yes I have jquery working)?
return false;
}, 10000);
});
function updateboolean(){
alert("Database updated");
document.location.reload(true);
}
Thanks in advance =)
Edit
_________________________________________________________________________________________
When I do
alert(data); in the below function I get the result as the image will show
$(document).ready(function(){
setInterval(function() {
$.get('databaseUpdated.php', function(data) {
alert('Load was performed.');
alert(data);
eval(data);
});
}, 5000);
});
But the "eval(data)"
doesn't seem to work
$.get("databaseUpdated.php"); // This will only return contents of that file The scripts in that file are not executed. To execute them you need to do eval(). So Try This
$.get('databaseUpdated.php', function(data) {
eval(data);
});
Also, may be you will require to change your php file as following:
echo ("updateboolean();");
where is your callback function for ajax
this is how it should be
$(document).ready(function(){
setInterval(function() {
$.get('databaseUpdated.php', function(data) {
alert('Load was performed.');
});
}, 10000);
});
Try this:
$(document).ready(function(){
setInterval(function() {
$.get('databaseUpdated.php', function(data) {
alert("Database updated");
// or alert(data); //in case you return data from php
document.location.reload(true);
});
}, 10000);
});
By doing $.get("databaseUpdated.php"), you request the PHP page, but ignore the return results.
Try this:
PHP
echo "updateboolean();";
JavaScript:
$.getScript("databaseUpdated.php");
try this in place of your echo
echo "<script>updateboolean();</script>";

Categories