I've a not working AJAX function - javascript

I'm building a time management system for the place I work for. While coding it I've created a system which the user can configure the database details (like the wordpress first run install) and once the data is saved successfully I want to show the next step.
The first part is working perfectly but I've run into some issues with the second part where the system checks the connection and start creating the database and the needed tables.
Up to now I've been using JSON to send and receive PHP response text. But now I wanted to create a AJAX function to the same as JSON. But the problem is the AJAX function is sending the data but I can't get the response text.
I went through most of the SO titles came up when I did a google search (might have missed once) but none of them worked. When I try to get the output from an alert it shows as oject[Object] on the popup.
Below is my jquery which I have the AJAX coded into.
function checkResponse(){
var res = $('#response').text();
if(res === "Saved"){
$.ajax({
url: './bin/config/createConfig.php',
type:'get',
data:{check:'check'},
dataType:'json',
complete: function (data) {
alert(data.responseText);
}
});
// $('#nextstep').show();
// $('#dbConfig-details').hide();
}
}
Above function is called by the below setTimeOut.
if(noEmpty && confirm('Are you sure all details to be true?')){
createConfig();
setTimeout('checkResponse();', 1000);
}
This is the PHP which the above AJAX send data to.
if (!empty($_REQUEST["check"])){
if(file_exists('../iConnect/node.php')){
$readFile = file_get_contents('../iConnect/node.php');
$dataTxt = unserialize($readFile);
extract($dataTxt);
try{
$dbConnect = new PDO('mysql:host='.$dbHost.';dbname='.$dbName,$dbUser,$dbPass);
$dbConnect -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected";
}catch(PDOException $ex){
echo "ERROR: ".$ex->getMessage();
exit();
}
}else{
echo "File missing";
}
}
The creatCofig() code.
function createConfig(){
var dbUser = document.getElementById("dbUser").value,
dbPass = document.getElementById("dbPass").value,
dbName = document.getElementById("dbName").value,
dbHost = document.getElementById("dbHost").value;
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("response").innerHTML=xmlhttp.responseText;
}
};
xmlhttp.open("POST","./bin/config/createConfig.php?dbUser="+dbUser+"&dbPass="+dbPass+"&dbName="+dbName+"&dbHost="+dbHost,true);
xmlhttp.send();
}
I know I'm missing something with the AJAX but my knowledge is limited on AJAX can some one please show me what am I doing wrong.

The complete callback has a signature of (jqXHR jqXHR, String textStatus).
Read about it here here.
Try the following pattern :
$.ajax({
url: ...,
type: ...,
data: ...,
dataType: ...,
}).then(function (data) {
alert(data.responseText);
});
Also, don't rely on a timeout to wait for an ajax response. That's what promises are for.
In createConfig(), use jQuery.ajax() and return a promise as follows :
function createConfig() {
return $.ajax({
'type': 'post',
'url': './bin/config/createConfig.php',
'data': {
'dbUser': $("#dbUser").val(),
'dbPass': $("#dbPass").val(),
'dbName': $("#dbName").val(),
'dbHost': $("#dbHost").val()
}
}).then(function(response) {
$("#response").html(response);
return response;
});
}
Now you can write :
if (noEmpty && confirm('Are you sure all details to be true?')) {
createConfig().then(checkResponse);
}

Related

Cannot read ob_flush() trough ajax

I have a code where I make an AJAX request at a certain file whenever I click a button, the request is as follows:
$("#syncDNS").click(function(){
$('#status').html("");
$('#status').addClass('loading');
function updateProgress(){
$.ajax({
type: 'POST',
url: 'index.php',
success: function(data){
$('#status').html(data);
}
});
}
$.ajax({
url: 'index.php?action=sync',
success: function (response) {
clearInterval(loop);
$('#status').removeClass('loading');
if(response){
$('#status').addClass('alert alert-warning').html("<h4>Aviso</h4>" + response);
}else{
$('#status').addClass('alert alert-success').html("<h4>Sucesso</h4>" + "DNS sincronizado com sucesso!");
}
}
});
updateProgress();
var loop = setInterval(function () {
updateProgress();
}, 1000);
});
In the code I make the request, and while I wait for it's success I keep running in a loop another function to update the progress of the first one.
And in my index.php file I have:
require_once(CONTROLLER_PATH . "ControleAutodns.php");
$action = isset($_GET['action']) ? $_GET['action'] : '';
switch ($action) {
...
case 'sync':
$controller = ControleAutodns::getInstance();
$return = $controller->syncDNS();
exit($return);
break;
...
}
In the index I include my control file and call the PHP function, this php function is a loop, where I add some entries to a database:
public function syncDNS(){
...
foreach($result as $row) {
$current ++;
echo($current);
...
}
...
return $string;
}
The thing is, the requests are working as intended and the PHP function is also doing it's job, I just can't listen to the echo's in the syncDNS function, why is that? I also tried using ob_start(), ob_flush(), flush(), but nothing worked.
As I understand, the control file is included in the index, so anything echoed in there should be available trough an AJAX POST request.

Unable to send JSON via AJAX

I made a function which counts how much time I spent on some page and where I came from. I collect all the data and save it into a JSON but when I try to send that JSON via ajax on the success it alerts me with an empty alert box, which means that nothing is being sent. I tried to add async to false because I use the onbeforeunload function but that doesn't work. I tried numberless combinations with AJAX setting but nothing is working.
HTML / JS
(function(){
var time,timeSite,endTime,seconds,testObject,retrievedObject,text;
window.onload=function(){
time= new Date();
}
window.onbeforeunload=function(){
endTime = new Date();
timeSite= time.getTime()-endTime.getTime();
seconds =Math.abs(timeSite/1000);
window.localStorage['seconds']=seconds;
text = 'Visitor accessed site directly.';
if(document.referrer == ''){
var link = text;
} else{
var link = document.referrer;
}
var url = window.location.href;
var main = {
'From': link,
'Current was' : url,
'Time Spent': seconds
}
$.ajax({
type: "POST",
data: {'data': main},
url: "http://localhost:8080/projectFour/test.php", //i use this page only to check if i receive data
contentType:'application/json',
success: function(data) {
alert(data);
},
error: function(xhr, ajaxOptions, thrownError) {
if (xhr.status == 200) {
alert(ajaxOptions);
}
else {
alert(xhr.status);
alert(thrownError);
}
}
});
}
})();
Test.php
<?php
if(isset($_POST['main'])) {
$obj = json_decode($_POST['main']);
//some php operation
echo $obj;
}
?>
Your test.php is looking for a POST variable called main, but you're sending one called data.
You can change the data part of the ajax call from:
data: {'data': main}
to
data: {'main': main}
and that should cause it to post the variable with main as the variable name.
Secondly, when you return the data, it would be better to return it as JSON again, otherwise it might mangle the result a bit.
Replace
echo $obj;
with
echo json_encode($obj);
And in the ajax replace
alert(data);
with
alert(JSON.stringify(data));
That will give you a view of the returned data structure as a string.
You should also consider returning something from PHP when the if statement is false, whether that be an error code, or some other response. Sending no response in this case isn't very helpful to the client side, and has hindered your debugging.

Script return blank just in jQuery AJAX

I've got very frustrating problem. I send AJAX request to PHP file and when I see Chrome Network Tools, it donť return any JSON. But when I try post the same data via POSTMAN tool in Chrome, it return right. When I open script normally, it return right. Just when I sen request via AJAXm it return nothing.
This is my PHP file: (I know it's functionally useless at this time, i need fix this error before it can do what I need)
$stav = 2;
$ret = array();
$name = query_r("select * from users where username = 'admin'");
$ret['stav']=$stav;
$json = json_encode($ret);
echo $json;
At line 3 must be problem, because when I put it out, it works. But function is 100% exist, 'cause when i put nonsense name of function, it write an error. DB query is also right, i tried it in phpMyAdmin console.
This is my AJAX request:
$("#loginForm").submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "../admin/scripts/login.php",
data: $("#loginForm").serialize(),
dataType: "JSON",
success: function (vysledek){
if(vysledek.stav===1){
window.location.href("../index.php")
}
else if(vysledek.stav===2){
alertify.error('Špatné uživatelské jméno');
}
else if(vysledek.stav===3){
alertify.error('Špatné heslo');
}
},
error: function(vysledek){
alertify.error('Vyskytla se nějaká chyba');
}
});
});
How I wrote, if I open PHP file in browser, it echo {"stav":2}, when I try POSTman, it echo {"stav":2}. But when I run AJAX request, it makes nothing. I really don't know what is wrong.
EDIT
Firebug:
Here
can you please try with the following code
$("#loginForm").submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "../admin/scripts/login.php",
data: $("#loginForm").serialize(),
dataType: "JSON",
success: function (vysledek){
if( parseInt(vysledek.stav) == 1 ){
window.location.href("../index.php")
}
else if( parseInt(vysledek.stav) == 2 ){
alertify.error('Špatné uživatelské jméno');
}
else if( parseInt(vysledek.stav) == 3 ){
alertify.error('Špatné heslo');
}
},
error: function(vysledek){
alertify.error('Vyskytla se nějaká chyba');
}
});
});
<?php
$stav = 2;
$ret = array();
$name = query_r("select * from users where username = 'admin'");
$ret['stav']=$stav;
$json = json_encode($ret);
print_r($json);
?>
Remember to parse JSON to the response
...
success: function (vysledek){
var vysledek = (vysledek);
if(vysledek.stav === 1){
window.location.href("../index.php")
}
...

AJAX Get isn't working

I'm attempting to pull data from a mysql server with AJAX.
This is the AJAX call:
function getAllTasks()
{
alert("Getting all tasks");
$.ajax({
type: "get",
url: "ajax.php",
dataType: "json",
data: data,
async: false,
success: function(data){
alert('hi!');
//perform operation
},
error: function() {
alert('Error occurs!');
}
});
}
and this is the PHP it's supposed to run:
header('Content-Type: application/json');
$conn = new mysqli('localhost', 'projectAdmin', 'admin', 'to_do_list')
or die('Error connection to database');
getAllTasks($conn);
function getAllTasks($conn)
{
$query = "SELECT * FROM tasks WHERE ID=1";
$result = mysqli_query($conn, $query);
while($row = $result->fetch_assoc())
{
$tasks[] = $row;
}
echo json_encode($tasks);
}
It's not working. When I run the PHP alone, it works fine, and returns a JSON string in the browser (chrome).
When I run the AJAX, nothing happens. I get the "getting all tasks" alert, and then it just doesn't work. The AJAX is called from the $(document).ready() function.
I don't know where I'm going wrong, I've looked at a bunch of posts on here and my AJAX code looks next to identical. Is it an issue with json_encode? The AJAX?
Help, please.
Here:
data: data,
It looks that the data variable is undefined. Also I would recommend you removing the async: false option in order to make an asynchronous request instead of blocking the UI.
Looking at the Console in your browser might also reveal some potential problems with your code.
var xhr = new XMLHttpRequest();
xhr.open("GET", "ajax.php");
xhr.addEventListener("readystatechange", function(ev) {
var xhr = ev.target;
if (xhr.readyState < 4) { /*not finished downloading yet.*/
return;
}
/*the request is completed. do your stuff with xhr.responseText here.*/
console.log(xhr);
});
xhr.send();

AJAX take data from POST with PHP

i have a little problem with my script.
I want to give data to a php file with AJAX (POST).
I dont get any errors, but the php file doesn't show a change after AJAX "runs" it.
Here is my jquery / js code:
(#changeRank is a select box, I want to pass the value of the selected )
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success') },
error: function (err)
{ alert(err.responseText)}
});
});
});
PHP:
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
header('Location:/user/'.$user);
die();
When i run the script, javascript comes up with an alert "success" which means to me, that there aren't any problems.
I know, the post request for my data is missing, but this is only a test, so im planning to add this later...
I hope, you can help me,
Greets :)
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success: ' + JSON.stringify(msg)) },
error: function (err)
{ alert(err.responseText)}
});
});
});
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
echo json_encode($user);
This sample code will let echo the username back to the page. The alert should show this.
well your js is fine, but because you're not actually echoing out anything to your php script, you wont see any changes except your success alert. maybe var_dump your post variable to check if your data was passed from your js file correctly...
Just return 0 or 1 from your php like this
Your PHP :
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
{
$_SESSION["user"] = $user;
echo '1'; // success case
}
else
{
echo '0'; // failure case
}
Then in your script
success: function (msg)
if(msg==1)
{
window.location = "home.php"; // or your success action
}
else
{
alert('error);
}
So that you can get what you expect
If you want to see a result, in the current page, using data from your PHP then you need to do two things:
Actually send some from the PHP. Your current PHP redirects to another URL which might send data. You could use that or remove the Location header and echo some content out instead.
Write some JavaScript that does something with that data. The data will be put into the first argument of the success function (which you have named msg). If you want that data to appear in the page, then you have to put it somewhere in the page (e.g. with $('body').text(msg).

Categories

Resources