Why does Ajax never return a value even with callbacks - ajax

Ajax never returns a value. I have tried setting the async:false option and also tried to setup a callback function it still never returns a value. When i browse to the url using firefox i see the expected response but when i make the request via ajax, there is no reponse. Firebug also confirms it.
I have tried lots of code samples i found but they never return a value. I have also tried using a different version jquery and other browsers.
Does anyone know what could be wrong?
Thanks
Below is the code that gets called when a user clicks a button on the form.
function login() {
var username = $("#uname").val();
var password = $("#password").val();
$.ajax({
type: 'POST',
url: 'http://localhost/mConnect/login.php',
data: { username: username, password: password },
async: false,
success: function(html) {
slim(html);
}
});
}
function slim(html) {
// var data = $(xml).find("Status").text();
alert(html.responseText);
}
Below is the login.php it just prints static xml
<?php
$array = array('stat' => '1.0',
'mode' => 'whatever',
'content' => 'All');
$new ='<?xml version="1.0" encoding="iso-8859-1"?><response>';
foreach($array as $key => $values) {
$new .= "<$key>$values</$key>";
}
echo $new.'</response>';
?>

You have a success callback, but no failure callback. Probably something along the way is failing and there are about 100 possibilities. Run it in Firebug (or equivalent) and see what happens to the request. (My money: your local webserver isn't responding at all.)

If you sent an AJAX request you will get a response. Even if it is a timeout. So if you don't have a response at all then you more than likely never sent the request.

Related

Ajax post is working in localhost but not in godaddy server

This ajax post is working in localhost but not in godaddy server. I dont know how to solve this kind of issues. Please let me know how rectify this issue.
Ajax is not working in many places. Locally all of files are working very fine.
I am new to php. Anyone can help me to fix this bug?
Thanks in Advance
function advanced_addTopic(cid) {
$.ajax({
url: "assets/php/checkSubtopicStatus.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: {'cid':cid}, // Data sent to server, a set of key/value pairs (i.e. form fields
success: function(data) // A function to be called if request succeeds
{
if(data==="True"){
$("#subtopicDiv").html($("#subtopicDiv"+cid).html());
$("#advanced_testid").val(cid);
var hiddenCourse=$("#createTest").attr('class');
$("#courseHidden").val(hiddenCourse);
$("#advanced_addquestionModal").modal('show');
$("#subtopic").focus();
$("#question").focus();
var tempVal=$("#getID").text();
$("#advanced_courseHidden").val(cid);
} else {
alert("Create subtopics to insert questions!");
}
}
});
My PHP CODE IS:
<?php
class loginValidation {
function validate()
{
ob_start();
session_start();
include "../../connection.php";
$id=$_POST['cid'];
$query = mysql_query("select * from advanced_subtopic where testid='$id'");
if(mysql_num_rows($query)>0){
echo "True";
} else {
echo "False";
}
}}$loginValidation=new loginValidation;
$loginValidation->validate();
?>
Using Ajax URLs like
url: "http://domainname.com/assets/php/checkSubtopicStatus.php";
If you use your domain name HTTPS enter the same as an Ajax URL.

ajax call to php to return json doesn't work

So, i was search here for answer and this is really becoming weird thing, i allready worked with this and allways worked without any troubles, but now im having this trouble and i don't know whats problem. So, i hava ajax call like this :
$.ajax({
type: 'POST',
url: 'admin/update/update.php',
dataType: 'json',
success: function( data ) {
console.log( data );
}
});
and im calling this file:
<?php
header("Content-type: application/json");
include "../system/functions.php";
$users = database::query("SELECT * FROM users WHERE updated = 0 LIMIT 1");
$user = mysqli_fetch_assoc($users);
print json_encode($user);
As you see im trying to put DATA into console log and see what im getting from response, but nothing is happening, also, when i check network on Chrome file is appearing with status 200 and application/json.
I have no clue what is problem.
SOLVED:
For some reason json_encode($user) doesn't want to return anything. On other side this one works good:
$users = database::query("SELECT * FROM users WHERE updated = 0 LIMIT 1");
$user = mysqli_fetch_assoc($users);
$user = array(
"id" => $users['id']
);
echo json_encode($user);

not getting response from ajax call in codeigniter

I am trying to check if the user name is available for use using ajax and codeigniter. I have problem to get the response from the codeingniter controller in my js. file but without success.
Here is the controller function, relevant to the question:
if ($username == 0) {
$this->output->set_output(json_encode(array("r" => true)));
} else {
$this->output->set_output(json_encode(array("r" => false, "error" => "Username already exits")));
}
Rest assured that I do get 1 if username already exists in thedatabase and 0 if it does not exist.
I have the following js.file
// list all variables used here...
var
regform = $('#reg-form'),
memberusername = $('#memberusername'),
memberpassword = $('#memberpassword'),
memberemail = $('#memberemail'),
memberconfirmpassword = $('#memberconfirmpassword');
regform.submit(function(e) {
e.preventDefault();
console.log("I am on the beggining here"); // this is displayed in console
var memberusername = $(this).find("#memberusername").val();
var memberemail = $(this).find("#memberemail").val();
var memberpassword = $(this).find("#memberpassword").val();
var url = $(this).attr("action");
$.ajax({
type: "POST",
url: $(this).attr("action"),
dataType: "json",
data: {memberusername: memberusername, memberemail: memberemail, memberpassword: memberpassword},
cache: false,
success: function(output) {
console.log('I am inside...'); // this is never displayed in console...
console.log(r); // is never shonw in console
console.log(output); is also never displayed in console
$.each(output, function(index, value) {
//process your data by index, in example
});
}
});
return false;
})
Can anyone help me to get the username value of r in the ajax, so I can take appropriate action?
Cheers
Basically, you're saying that the success handler is never called - meaning that the request had an error in some way. You should add an error handler and maybe even a complete handler. This will at least show you what's going on with the request. (someone else mentioned about using Chrome Dev Tools -- YES, do that!)
As far as the parse error. Your request is expecting json data, but your data must not be returned as json (it's formatted as json, but without a content type header, the browser just treats it as text). Try changing your php code to this:
if ($username == 0) {
$this->output->set_content_type('application/json')->set_output(json_encode(array("r" => true)));
} else {
$this->output->set_content_type('application/json')->set_output(json_encode(array("r" => false, "error" => "Username already exits")));
}

jQuery AJAX request error status 0

I've been developing an application locally and am running into trouble on the actual server.
Whenever I submit an AJAX request with jQuery it gives me an error with error status:0 and and statusText: 'error'.
The Chrome inspector doesn't even show a response code for the request, it just says failed.
When I inspect it closer, I notice that all of the data was sent and the PHP file actually processed it. For example, in the request below, the user was indeed created. The bad response code is preventing other requests from executing (since they depend on a 'successful' response).
Here is a sample request:
var cct = $.cookie('ttc_csrf_cookie'); // csrf protection
var sUrl = "<?= base_url(); ?>user/create/";
var serialized = {
name: me.name,
email: me.email,
oauth_provider: 'facebook',
oauth_uid: me.id,
ttc_csrf_token: cct
};
$.ajax({
url: sUrl,
type: "POST",
data: serialized,
error: function(someStuffHere) {
//* THIS CODE RUNS. SHOWS ERROR STATUS: 0 */
},
success: function(user_id) {
//******** THIS HERE NEVER RUNS ***********///
}
});
And here is the corresponding PHP code:
public function create() {
if($this->input->post()) {
$user['name'] = $this->input->post('name');
$user['email'] = $this->input->post('email');
$user['oauth_provider'] = $this->input->post('oauth_provider');
$user['oauth_uid'] = $this->input->post('oauth_uid');
$user['last_activity'] = date('Y-m-d H:i:s');
$user_id = $this->Users->create_user($user);
$this->session->set_userdata('user_id', $user_id);
echo $user_id;
}
}
These two snippets are only an example. All AJAX requests won't work on the live sever.
What could it possibly be? Thanks!
UPDATE: I've narrowed it down and the issue occurs when echo'ing a result. When I comment out the echo, no error is thrown (but, of course, no result is sent).
Turns out that the issue was caused by the compress_output option in CodeIgniter. When it's set to true, the echo's don't work. Thanks for everyone that tried to help!

.ajax posts and gets response on local server, no response on web host

I'm using an ajax call to do a minor calculation then return the value and display it in the page same page where the form is submitted. In Firebug it says it calls the function, however doesn't get a response. (I have a similar form that writes to a database that works fine, seemingly because it doesn't need a response - firebug says it fails to get a response on that script as well.) The odd thing is that I wrote this on my local server before implementing it on the site and everything worked as planned. I'm using Code Igniter on both the local server and the web server, but I don't know if that has something to do with it. Anyways, any help would be great. I'm marginally new so this is kinda outta my realm at this moment.
Thanks
EDIT: .js
$(document).ready(function() {
$('#submit').click(function(){
var formdata = {
years: $('#years').val(),
rate: $('#rate').val(),
principle: $('#principle').val(),
periods: $('#periods').val(),
continuous: $('#continuous').val()
}
$.ajax({
url: "http://localhost:8888/CodeIgniter_1.7.2/index.php/timevalueshow/submit",
type: 'POST',
data: formdata,
success: function(data){
$('#replace').replaceWith('<p>'+data+'</p>');
}
});
return false;
});
});
php submit function
function submit(){
$years = $this->input->post('years');
$rate = $this->input->post('rate');
$principle = $this->input->post('principle');
$periods = $this->input->post('periods');
$isCont = $this->input->post('continuous');
$params = array(
'years' => $years,
'rate' => $rate,
'principle' => $principle,
'periods' => $periods,
'isCont' => $isCont
);
$this->load->library('timevalue', $params);
return $this->timevalue->FVFactor();
}
Could it be that the request is being made cross-domain? Remember that mydomain.com is considered a different domain to www.mydomain.com.
I ran into a similar situation recently. I requested a page from mydomain.com which made an AJAX request to a script on www.mydomain.com. The request was not made because it was considered cross-domain. It had the same symptoms that you describe. In Firebug and Chrome Developer Console I saw an empty response and no error message.
The problem is that CodeIgniter generates absolute URLs based on the $config['base_url'] setting. If you access the site using a different domain name to what is configured in $config['base_url'] you can run into this type of problem.
This works on the dev and not on the server because you are calling localhost!
// this will have the client call itself on this particular page (wont work)
url: "http://localhost:8888/CodeIgniter_1.7.2/index.php/timevalueshow/submit",
The above code should be just:
// this is relative to the document ROOT, will work on server but not on dev!
// you can set it relative to the calling page using ../ as needed
url: "/index.php/timevalueshow/submit",

Resources