JSON display response - javascript

I have a script which grabs another JavaScript which is made using PHP, it all works fine, but im trying to build in some error handling incase there is an issue. At the moment the error works if it cannot find the file, but I would like it to display a message from the PHP code if there is an error. I thought using JSON would work, but im very new to it, and admit to not knowing what im doing.
If someone could help me get this working, as at the moment I am not getting the message response message appear in the alert.
I have the following JQuery code:
graphURL = 'functions/ICP_summary_graph.php';
graphData = '?ICP=' + ICPSet;
$.ajaxSetup({
type: 'get',
URL: graphURL,
data: graphData,
success: function (data) {
var reponse = jQuery.parseJSON(data.response);
alert("response : "+reponse);
//$('#expconchart').html(data.response);
},
error: function(data) {
$('#meterloader').hide();
$('#meterbox').html("<div><p class='textcentre bold red'>There was an error loading the chart.</p>");
}
});
$.getScript(graphURL + graphData);
and this PHP:
//GENERATE GRAPH
//SET RESULT ARRAY
$result = array();
//CONNECT TO DATABASE
if(!require('../../connect.php')){
$result['response'] = "Unable to aquire connection";
header("content-type: application/json");
exit(json_encode($result));
} else {
...
Any help greatly appreciated. :)

Related

How do I return a variable from Javascript to PHP for using it for a query "onchange"?

JAVASCRIPT
$(document).ready(function() {
$("#p").change(function () {
var p_id = $(this).val();
console.log(p_id);
$.ajax({
url: "m/a/a.class.php",
method: "POST",
data: {pId: p_id},
success: function (data)
{
console.log(data); //<------ this gives me an empty output
alert("success!");
}
});
});
});
I am trying to get a the id of a selected value out of the selectpicker, when i change the selectpicker, i get the alert "success!" and in the console it shows the result, which is correct. When i want to use this result in PHP, which i am using ajax for, it gives me an odd output so i can't use the variable for the following sql statement.
What am i doing wrong? For you to understand i want to get the post input for product, so i can filter the next selectpicker by the id of "product", so i want to get dependant selectpicker "onchange". I already read many other questions, and it works in other examples when i use something like this in the success function:
success: function (data)
{
$('#state').html(data);
}
But this isn't working for my example here, because when i use the "$_POST['produkt_id']" it either gives me an empty query or it has a mistake in it, since it passes the data from my screenshot. Thanks in advance and feel free to ask questions.
UPDATE:
This is where I am trying to get the previous input.
case 'linie':
if(isset($_POST['pId'])) {
$t = $_POST['pId'];
$sql = 'SELECT id, bezeichnung '
. 'FROM l "
. 'LEFT JOIN ' .produkte p ON p.id=l.p_id '
. 'WHERE l.p_id =' . "$t" . 'AND l.deleted=0 AND p.deleted=0 '
. 'ORDER BY l.bezeichnung ';
break;
}
the error says it. PHP you're using is calling "include_once" and the file which you're trying to include, doesn't exist.
that makes the PHP to return a response with error in it, and the response - because of that error text - is not a valid JSON anymore.
In your ajax code you should put your url route path for file request it hink you put the file path of your project system that's why your ajax file could not find and include your file for ajax request execution
$.ajax({
url: "modules/ausschuss/ausschuss.class.php", //remove this
url: "full url for your file execution"
method: "POST",
data: {produkt_id: produkt_id},
success: function (data)
{
alert("success!");
}
});

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.

Get data from PHP file using AJAX

I'm trying to get some data from a PHP file using AJAX but I get only an error:
Uncaught TypeError: Cannot read property 'protocole' of null
protocoleGenerator.php
<?php
$array = array(
'protocole' => '1029384756',
);
echo json_encode($array);
?>
script.js
function getDemoProtocol() {
$.ajax({
url: 'protocoleGenerator.php',
data: "",
dataType: 'json', //data format
success: function (data) {
var protocole = data['protocole'];
console.log("Prot: " + protocole);
}
});
}
What is wrong here?
I can't comment for now :( and write my suggestions as an answer. It seems like you have mistype in protocoleGenerator.php. May be end line looks like echo json_encode($aray);, in this case json_encode() returns pure null (if you have disable php notices). The success function receives null and can't get a property from this object. It's only my subjective suggestion. It may be wrong.
P.S: You can get value / call function as Object.my_fun(), or Object['my_func']() - for this particular case it doesn't matter how did you access to the variable. For example:
var o = {};
o.test = 'my test value';
o.fff = function() {return 'fff called.';};
console.log('dot-style:' + o.test);
console.log('arr-style:' + o['test']);
console.log('dot-style:' + o.fff());
console.log('arr-style:' + o['fff']());
Ok, I've got a minus. If assumed, that topic starter show us hard copy-paste of his code, here is no issues. My suggestion based on the error message - the "success function" gets HTTP/200 answer from the server with text "null". With empty or non-valid json response jquery-ajax calls an "error handler". I'm sure that it can't be caused by json_encode() behaviour - my example above prove it.
Another suggestion is specific server config, rewrites, redirects or something else. But I've exclude this suggestion.
Oh...
<?php
$array = array(1,2);
$аrray = array(3,4);
var_dump($array);
var_dump($аrray);
result looks like that:
array(2) {
[0] =>
int(1)
[1] =>
int(2)
}
array(2) {
[0] =>
int(3)
[1] =>
int(4)
}
Did you see the difference? I don't, but the second $array begins from cyrillic character.
I run your code in my localhost, it's working fine please check below code in your system, if you still get any error then post your whole code so I can check in my system.
index.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Json</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">
function getDemoProtocol() {
$.ajax({
url: 'protocoleGenerator.php',
data: "",
dataType: 'json', //data format
success: function (data) {
var protocole = data['protocole'];
console.log(protocole);
alert(protocole);
console.log("Prot: " + protocole);
}
});
}
getDemoProtocol(); // Javascript method
// Jquery Method
$(function (){
$.ajax({
url: 'protocoleGenerator.php',
data: "",
dataType: 'json', //data format
success: function (data) {
console.log(data);
var protocole = data.protocole;
console.log("Prot: " + protocole);
}
});
});
</script>
</head>
<body>
</body>
</html>
protocoleGenerator.php
<?php
header('Content-Type: application/json');
$array = array(
'protocole' => '1029384756',
);
echo json_encode($array);
?>
This is because you are getting Error 404: not found. Check console (tick the log XHR requests checkbox).
The solution would be, changing this:
url: 'protocoleGenerator.php',
to this:
url: './protocoleGenerator.php',
Working example:
http://neolink.dyndns.org:81/stackoverflow/1.php
PS. This is weird that jQuery runs success function even when response was 404.
PS 2. If it won't work (it should!), give the full path instead (like http://blabla.com/1/3/45345/protocoleGenerator.php, as that may be server dependable)

jquery ajax posting failed not returning an error

ive read some questions related to my question but i can't find a solution
in some part of my website. posting a single value to a php page works
so i searched passing multiple values using ajax and applied it to my website
but i says posting failed
this is the php code. i tried running it to my server by passing directly a data to the php and it works like this $temp1 = "0001"
this is the inserdocument.php file
$temp1 = $_POST['dtnum'];
$temp2 = $_POST['ddoctitle'];
$temp3 = $_POST['ddoctype'];
$temp4 = $_POST['ddoccontent'];
$temp5 = $_POST['ddocdatefilled'];
$stmt = $conn->prepare("CALL sp_insertdocument (?,?,?,?,?)");
$stmt->bindParam(1, $temp1, PDO::PARAM_STR, 30);
$stmt->bindParam(2, $temp2, PDO::PARAM_STR, 50);
$stmt->bindParam(3, $temp3, PDO::PARAM_STR, 50);
$stmt->bindParam(4, $temp4, PDO::PARAM_STR, 10);
$stmt->bindParam(5, $temp5, PDO::PARAM_STR, 10);
$stmt->execute();
and this is my ajax code. i even tried adding try and catch but the catch returns nothing.
$.ajax({
type: "POST",
url: "inserdocument.php",
data: ({dtnum: tnum, ddoctitle: doctitle, ddoctype: doctype, ddoccontent: doccontent, ddocdatefilled: docdatefilled})
})
.done(function (msg) {
alert("Data Saved: " + msg);
//$('#response').html(msg);
})
.fail(function() {
alert( "Posting failed." );
});
im sorry for posting i found out that the problem is here
url: "inserdocument.php"
it should be
url: "insertdocument.php"
typographical error. im concentrating at the passing of data, i didn't notice the php filename is incorrect. sorry

Using Ajax, JavaScript and HTML to post some data

Hello I´m very frustated because I can´t connect to my database to retrieve some files.
I have my normal html code (index.html) which adds a javascript:
<script src="js/connection.js"></script>
The javascript (connection.js) looks something like this, which detects from a grid of elements the selected element and gets it´s text:
var texto="";
function getData($dia){
//Variable $dia is set up correctly, no problem
var dia=$dia;
/* Send the data using post*/
$.ajax({
url: "php/setup.php",
type: "post",
data: {'fecha':dia},
contentType: "application/json",
datatype: "json",
success: function(){
alert("Exito");
},
error:function(){
alert("failure");
}
});
}
//Get the desired text upon click on the grid item
$(document).ready(function(){
$(".grid__item").click(function(){
$texto=$(this).html().substring(($(this).html().indexOf(">"),($(this).html().indexOf(">")+1)),$(this).html().indexOf("</h2>"));
getData($texto);
});
});
Finally using Ajax I pass the variable 'fecha', the problem is that I think it´s not making a proper connection with my php file since nothing is printing (I have a method which prints to console)
I set the post method like this (PHP file starts here):
debug_to_console("Print Something");
$fecha = mysql_real_escape_string($_POST['fecha']);
getPageData($fecha);
Which calls this method:
function getPageData($dia){
$sql = ("SELECT * FROM Comentarios WHERE dia='$dia'");
$result = mysqli_query(connectToDb(),$sql);
$num_rows = mysqli_num_rows($result);
$html="";
$boolean=true;
if($num_rows>0) {
while($row = $result->fetch_assoc()) {
if($boolean==true){
$html.='<div class="gray"><div class="comentario">'.$row["comment"].'</div><div class="timestamp">'.$row["dia"].'</div></div>';
$boolean=false;
}else{
$html.='<div class="white"><div class="comentario">'.$row["comment"].'</div><div class="timestamp">'.$row["dia"].'</div></div>';
$boolean=true;
}
}
echo json_encode(array('html'=>($html.'<br>'.'<div class="fondo_gen"> div></div></div>'),'texto'=>$dia));
} else {
echo json_encode(array('html'=>'<div class="transparent"><div class="nada">No hay comentarios aun :(</div></div>','texto'=>$dia));
}
}
PHP file ends here
I know that it's connecting to the database since a made a "dummy.php" file which connects to the same database and table and adds a record, without problem. I´m not really sure which is the problem, I could really appreciate it if you could help me.
PS:
My folders are setup like this:
index.html
js (folder)
a. connection.js
php (folder)
a. setup.php
.
Thanks and sorry for my crappy english
Never mind, I got it fixed, I replaced the Ajax part with:
$.post("php/setup.php",
{
fecha: dia
},
function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
and received the variable using
if (isset($_POST["fecha"])){
$fecha = $_POST["fecha"];
getPageData($fecha);
}else{
echo "Got nothing";
}
Thanks anyway, I appreciate the help

Categories

Resources