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

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

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

Wordpress: Use AJAX to get the next post

After looking through the jQuery documentation and many stackexchange community forums, I am still faced with this problem. Taking little bits from here and there have helped me get this far, but I am stuck where I am now.
Im using an ajax request to try and load the next post after the one that is currently displayed. The only issue I run into is when I try to execute the method included in my php file:
<?php
echo getnext();
function getnext(){
$post = get_post($_POST['id']);
$prevPost = get_previous_post();
return $prevPost->post_content;
}
?>
I can echo the POST variable that is being passed in fine, but once I try to actually call the method I get a 500 internal Server Error.
My AJAX request looks like this:
setTimeout(function (){
$currid = $('#post_id').val();
$.post("wp-content/themes/stargazer/populate.php",
{
"id":$currid
},
function(data){
//$("#academiccontent").html(data);
alert (data);
});
$('#academiccontent').animate({ 'opacity': 1 });
}, 1000);
Any help would be greatly appreciated, Ive been stuck on this for a long while now.
Thanks!!
Why don't you use AJAX directly in WordPress?
The best way is add to function.php file in your theme something like this:
add_action( 'wp_ajax_getnext', 'getnext' );
function getnext() {
$post = get_post($_POST['id']);
$prevPost = get_previous_post();
return $prevPost->post_content;
die(); // this is required to return a proper result
}
And your javascript change to this:
setTimeout(function (){
$currid = $('#post_id').val();
var data = {
"action": "getnext",
"id":$currid
};
$.post(ajaxurl, data,
function(data){
alert (data);
});
$('#academiccontent').animate({ 'opacity': 1 });
}, 1000);
More info about AJAX in WordPress you can find here: http://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)

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!

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