jQuery AJAX request error status 0 - ajax

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!

Related

How can I print_r an array from controller while an ajax process?

I am trying to debug my AJAX call to database.
But there is no way to see the data i am using. I have tried to do it inserting some Javascript:
I also tried to use print_r, but nothing happens.
Is there any way to see my variables? A developer tool for example, or any command i could use.
Thanks for your help.
function console_log( $data ){
echo '<script>';
echo 'console.log('. json_encode( $data ) .')';
echo '</script>';
}
This is my controller code:
public function searchEvents(){
$request = Request::createFromGlobals();
if($request->getMethod()=='POST') {
$value = $request->request->get('searchBox');
$em=$this->getDoctrine()->getManager();
$searchFor = $request->request->get('value');
$qb = $em->createQueryBuilder();
//$eventos = $em->getRepository('App:Evento')->findBy(array('title'=>'Invi Chuwi'));
$query = $em->createQuery('SELECT e FROM App:Evento e WHERE e.title LIKE :value');
$query->setParameter('value', '%'.$searchFor.'%');
$eventos = $query->getResult();
/*$qb->select('u')
->from('App:Evento','u')
->where(('u.title = '.$searchFor));
$query = $qb->getQuery();
$eventos = $query->getResult();*/
$response = [];
foreach($eventos as $evento){
array_unshift($response,[
$evento->getTitle(),
$evento->getFecha()
]);
print_r($response);
}
$respuesta = new JsonResponse();
$respuesta->setData(
array('response'=>'success',
'eventos'=>$response)
);
}
return $respuesta;
}
And my js code:
function searchForEvents(value){
$.ajax({
method:"POST",
data: value=2,
url:"{{ path('searchEvents') }}",
dataType:'json',
success: function(data){
//var results = JSON.parse(data.events);
alert(JSON.stringify(data, null, 4));
//putEvents(results);
}
})
}
I assume you use Symfony 4+ If this case you need to install Symfony Profiler and Var Dumper packages (https://symfony.com/doc/current/profiler.html - https://symfony.com/doc/current/components/var_dumper.html). When install that two bundle you need change print_r functions to dump function. After you do that profiler package record all your request. You can access profiler data to "_profiler" route (example: http://localhost:8000/_profiler/ or something like that).
Please notice that the browser will show you the direct link to profiler inside the headers of the request, here is an example:
The way you send your AJAX request is invalid. Change it to:
function searchForEvents(value){
$.ajax({
method:"POST",
data: {value: 2},
url:"{{ path('searchEvents') }}",
dataType:'json',
success: function(data){
//var results = JSON.parse(data.events);
alert(JSON.stringify(data, null, 4));
//putEvents(results);
}
})
}
This will still not pass searchbox, but hopefully this is enough to figure that out as well. If not, then please add more details.
As about debugging the data, you can always use the good old echo var_dump and see what it puts into your request response in the network tab of dev tools or you can do it the Symfony way, logging it into a file.
Not sure if I understand you question correctly, but AJAX requests have to be debugged separately using symfony developer toolbar or by peeking request in browsers dev tools → Network tab. You can also check var/log/dev.log

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")));
}

Why does Ajax never return a value even with callbacks

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.

Resources