AJAX Get isn't working - javascript

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

Related

ajax call fails when i try to create a new table php

Want to send a ajax request to php to create a new table dynamically. I have the following code:
Javascript:
var file = $('#'+option_file_name.id).prop('files')[0];
var form_data = new FormData();
form_data.append('file', file);
form_data.append('column_name', option_file_name.id.slice(12));
send_ajax_request(form_data);
function send_ajax_request(pdata){
console.log(pdata);
$.ajax({
url: "set_points_data.php",
data: pdata,
contentType: false,
processData: false,
dataType: "json",
type: 'post',
success: function (data) {
console.log(data);
},
error: function(a,b,c){
alert("something went wrong");
}
});
}
php script:
in the data.php file i connect to the database and have all the supporting functions.
<?php
include 'data.php';
$data = null;
if(isset($_FILES)){
$data = $_FILES;
$type = (string)$_POST["column_name"];
create_table($conn, $type);
return_ajax("succes");
}else{
return_ajax("error");
}
function create_table($conn, $name){
send_sql($conn, "CREATE TABLE `".$name."` (
options varchar(255));"
);
}
?>
UPDATE:
it turns out that if i change the following code to this the error disappears. see the new code below:
send_sql($conn, "CREATE TABLE testTable (
options varchar(255)
);");
but this is not what i want i need to create tables dynamically.
when ever i run run the ajax request i get the error something went wrong.
But when i run the php script without the ajax call it works fine.
and when i run the php script from the ajax call but without the create table function it also works fine. So i am not sure what is happening here.
Hope this is clear if not let me know.
After doing some testing i figured out that ajax is trying to return some data after doing the create table statement. Resulting in a error. if you change it to the following.
if(isset($_POST)){
$data = $_FILES;
$db_name = $_POST["tblname"];
return_ajax(create_table($conn, $db_name));
}else{
return_ajax("error");
}
function create_table($conn, $name){
send_sql($conn, "CREATE TABLE `".$name."` (
options varchar(255)
);");
return "database created";
}
This wil work. not sure what exactly happens but this fixes the ajax error.

I've a not working AJAX function

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

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

Check all possible AJAX responses

I have an AJAX function which POST data to a PHP handler. I echo back either "success" or "failure" from PHP to determine if it was completed as intended. Unfortunately I am not used to JS/AJAX and have trouble finding documentation that answers my questions.
Do I need to JSON encode the response? I only check for .done() in my AJAX function, should I also check success and failed? My code inside of .done() which is just an alert box isn't working, despite the functionality in the PHP handler running without issue.
JS/AJAX:
<script type="text/javascript">
function powerSignal(device, signal)
{
var cfm = confirm("Do you wish to ___ the server?");
if (cfm==true)
{
$.ajax({ type: "POST", url: "https://domain.net/modules/power_functions.php", data: { device: device, 'power_signal': signal }}).done(function(result)
{
alert("success!");
});
}
}
</script>
PHP:
if ( isset($_POST["device"]) && isset($_POST["power_signal"]) )
{
$deviceid = $_POST["device"];
$signal = $_POST["power_signal"];
//API: Get Device Inventory
$url = 'http://domain.net/dp/api/set_device_power_status';
$fields = array('deviceid' => urlencode($deviceid), 'power_signal' => urlencode($signal));
$result = curl_get($url, $fields);
$json = json_decode($result);
$status = $json->{'status'};
if ($status == "success")
{
echo "success";
}
echo "failed";
}
the content of the result variable will be what the server sends back, you'll have to test it :
$.ajax({ type: "POST", url: "https://domain.net/modules/power_functions.php", data: { device: device, 'power_signal': signal }}).done(function(result)
{
if(result=='success'){
alert("success!");
}else{
alert("failure!");
});
To answer the comment below, here is how I do in my current project with a simple get request :
$.get( "/getResult/"+data, function( results ) {
$('.popin_content').html('<p>Vos documents ont bien été créés :</p><br/><ul><li>Plan PDF</li><li>Devis PDF</li></ul>');
});

Header wont redirect when passedthrough ajax

Not sure if this is possible but I have a page that submits a form with AJAX and if it meets certain conditions it should automatically take the user to another page. NOTHING is outputted before the header tag its just a bunch of conditions.
Problem: Header redirect not working...
AJAX
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '_ajax/add.php',
data: $('form').serialize(),
success: function (data) {
$("input").val('Company Name');
$("form").hide();
getInfo();
}
});
});
add.php
$row = mysqli_fetch_array($result);
$id = $row['id'];
header("Location: http://localhost/manage/card.php?id=$id");
Headers can only be modified before any body is sent to the browser (hence the names header/body). Since you have AJAX sent to the browser, you can't modify the headers any more. However, you can have the add.php script called via AJAX return the $id parameter. Then that parameter can be used in JavaScript to redirect the page: window.location = 'http://localhost/manage/card.php?id=' + id.
More info on PHP header(): http://www.php.net/manual/en/function.header.php
AJAX
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '_ajax/add.php',
data: $('form').serialize(),
success: function (data) {
window.location = 'http://localhost/manage/card.php?id=' + data;
}
});
});
add.php
$row = mysqli_fetch_array($result);
$id = $row['id'];
echo $id;
exit;
You indicate in the question that under certain conditions, you want a redirect.
To do that, you would want to alter your javascript to contain an if condition, and to watch for certain responses.
I would recommend modifying your responses to be json, so that you can pass back different information (such as a success status, as well as a redirect url, or other information you might want).
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '_ajax/add.php',
data: $('form').serialize(),
success: function (data) {
var response = $.parseJSON(data);
if (response.redirect) {
window.location = response.redirect_url;
} else {
$("input").val('Company Name');
$("form").hide();
getInfo();
}
}
});
});
As for your add.php file, you'll want to change this to be something more like so:
$json = array(
'redirect' => 0,
'url' => '',
}
if (...condition for redirect...) {
$row = mysqli_fetch_array($result);
$id = $row['id'];
$json['redirect'] = 1;
$json['redirect_url'] = "Location: http://localhost/manage/card.php?id=$id";
}
echo json_encode($json);
die();
You seem to have a miss understanding of how AJAX works. Introduction to Ajax.
The reason why your redirect appears not to working is because an Ajax call doesn't directly affect your browser. It's a behind the scenes call.
To get the data out from the AJAX call you need to do something with the returned data.
success: function (data) {
$("input").val('Company Name');
$("form").hide();
//You need to do something with data here.
$("#myDiv").html(data); //This would update a div with the id myDiv with the response from the ajax call.
getInfo();
}

Categories

Resources