I want to load some data from sql table into my page. This is the php script that I am using:
PHP:
<?php
include_once "conectar.php";
header('Content-Type: text/txt; charset=utf-8');
public class Calendario{
public function cargarCalendarios() {
$conexion = new PDO("mysql:host=localhost;dbname=practica_db;charset=utf8","root","");
$sql = "SELECT nombre, descripcion, likes FROM calendarios";
$pdo = $conexion->prepare($sql);
$pdo->execute();
$json = array();
while ($row=$pdo->fetch(PDO::FETCH_ASSOC)) {
$json[] = array('nombre' =>$row['nombre'], 'descripcion'=>$row['descripcion'], 'likes'=>$row['likes']);
}
echo json_encode($json);
}
}
($calendario = new Calendario())->cargarCalendarios();
?>
I am calling that script here:
JS:
function cargarCalendarios() {
$.ajax({
url: '../php/menuCalendarios.php',
type: 'GET',
dataType: 'json',
})
.done(function(data) {
$.each(data, function(id,value){
//code
}
});
})
.fail( function( jqXHR, textStatus, errorThrown ) {
//...More error handling
} else if (textStatus === 'parsererror') {
alert('Requested JSON parse failed.');
});
}
I get an error in the request, and I don't know what I am doing wrong. The error must be in the PHP code I asume, but I just can't find anything.
If it helps, I am working in a local server with XAMPP.
I always get failure and the alert:
'Requested JSON parse failed.'
Related
If I set dataType to 'json' and inside my PHP file I print whatever I want (event a letter), success function works, but if I don't print anything else besides the JSON I need, stops working. I can't handle my data with something else printed, because it turns the answer into HTML, instead of JSON. I'm able to see in Network -> Answer the JSON file (only when I don't print anything else beside the JSON), but I don't know why I can't even do an alert in success function when that is the case.
This is my ajax, which only works because I'm printing 'true' on the server:
$(document).on("click", "#btnEditarInstructor", function(event) {
event.preventDefault();
let rfc = $(this).attr("value");
$.ajax({
type: "POST",
url: "../utils/ajax/ajax_consulta_instructor.php",
data: {
rfc: rfc,
},
dataType: "json",
succes: function(response) {
if (response == true) {
// alert(response);
}
},
error: function(request, status, error) {
var val = request.responseText;
alert("error" + val);
alert(status);
alert(error);
},
});
})
This is my PHP code:
$rfc = $_POST['rfc'];
$sql = "SELECT * FROM instructores WHERE rfc = '$rfc'";
$sql_run = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($sql_run)) {
echo "true";
$datos['status'] = 'OK';
$datos['nombre'] = $row['nombre'];
$datos['apellidos'] = $row['apellidos'];
$datos['email'] = $row['email'];
$datos['tipo_promotor'] = $row['tipo_promotor'];
echo json_encode($datos);
}
By the way, with that code, I get this error on the alert:
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 5 of the JSON data
I'm using jQuery 3.6.0 (https://code.jquery.com/jquery-3.6.0.js)
If you're returning JSON, you can only echo the JSON once, not each time through the loop.
If there can only be one row, you don't need the while loop. Just fetch the row and create the JSON.
You also can't echo anything else, so the echo "true"; lines are breaking it.
And your code is wide open to SQL-injection. You should use a prepared statement with a parameter, which I've shown how to do.
$rfc = $_POST['rfc'];
$stmt = $con->prepare("SELECT * FROM instructores WHERE rfc = ?");
$stmt->bind_param("s", $rfc);
$stmt->execute();
$sql_run = $stmt->get_result();
$datos = [];
if($row = mysqli_fetch_array($sql_run)){
$datos['status'] = 'OK';
$datos['nombre'] = $row['nombre'];
$datos['apellidos'] = $row['apellidos'];
$datos['email'] = $row['email'];
$datos['tipo_promotor'] = $row['tipo_promotor'];
}
echo json_encode($datos);
$(document).on("click", "#btnEditarInstructor", function (event) {
event.preventDefault();
let rfc = $(this).attr("value");
$.ajax({
type: "POST",
url: "../utils/ajax/ajax_consulta_instructor.php",
data: {
rfc: rfc,
},
dataType: "json",
success: function (response) {
if (response == true) {
// alert(response);
}
},
error: function (request, status, error) {
var val = request.responseText;
alert("error" + val);
alert(status);
alert(error);
},
});
Using PHP script I am able get JSON. I am trying to return the JSON back using PHP script but I'm getting a 404 error when I try to receive it via AJAX. I am using this with Flask. Can someone explain what I am doing wrong?
PHP query
<?php
$db = new SQLite3('example.db');
$results = $db->query('SELECT * FROM things');
while ($row = $results->fetchArray(SQLITE3_ASSOC)) {
$jsonArray[] = $row;
}
json_encode($jsonArray)
?>
AJAX
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$.ajax({
url: 'query.php',
dataType: "json", //if it returns a xml file
success: function (data) {
// everything is ok
alert(data)
},
error: function (xhr, status, error) {
// Something went wrong
if (xhr.status > 0) alert('Error: ' + status)
console.log("error something went wrong");
}
});
</script>
At the moment when I hover over any word a black box is always showing. If the PHP code returns text it is displayed in the black box (which it should). However I want it to return an error function if the text is not returned so I can then later change the CSS for the black box so that it has a width of 0px instead of 400px.
var x = ($(this).text());
$.ajax({
type: 'POST',
url: 'process.php',
data: { text1: x },
success: function(response){
$('#tooltip').text(response);
}
});
try
{
$db = new PDO('sqlite:ordbas.db');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $err)
{
echo "PDO fel $err";
}
if (isset($_POST['text1'])) {
$text1 = $_POST['text1'];
$results = $db->prepare("SELECT forord FROM words WHERE sokord='$text1'");
$results->execute();
$row = $results->fetch();
echo $row[0];
}
As you might have figured out there is some non-important code that I left out. I hope someone can understand and help me! Thanks!
Here is exactly how you can do it :
The Very Easy Way :
IN YOUR PHP FILE :
if ($query) {
echo "success"; //anything on success
} else {
die(header("HTTP/1.0 404 Not Found")); //Throw an error on failure
}
AT YOUR jQuery AJAX SIDE :
var x = $(this).text();
$.ajax({
type: 'POST',
url: 'process.php',
data: { text1: x },
success:function(data) {
alert(data); //=== Show Success Message==
},
error:function(data){
alert("error occured"); //===Show Error Message====
}
});
First, you need to let know javascript there was an error on server side
try
{
$db = new PDO('sqlite:ordbas.db');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $err)
{
// Set http header error
header('HTTP/1.0 500 Internal Server Error');
// Return error message
die(json_encode(array('error' => 'PDO fel '.$err->getMessage())));
}
Second, you need to handle error while loading json
var x = ($(this).text());
$.ajax({
type: 'POST',
url: 'process.php',
data: { text1: x }
})
// This will be called on success
.done(function(response){
$('#tooltip').text(response);
})
// This will be called on error
.fail(function(response){
// Error catched, do stuff
alert(response);
});
The fail callback within $.ajax is used for capturing any failing results.
show/hide the error div based on success/failure returned from server script.
HTML CODE:
<div class="error"><div>
CSS:
.error {
color: red;
}
JS CODE:
//hide error before ajax call
$('.error').hide();
$.ajax(...)
.done:function(){
...
}
.fail: function(jqXHR, textStatus, errorThrown){
$('.error').text(errorThrown);
$('.error').show();
}
Note: .success() & .error() methods are deprecated from jquery 1.8 so avoid using them.
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
In your catch you could put
header('Content-type: application/json');
echo json_encode(array('Error' => 'PDO fel "$err"'));
$.ajax({
url: "file_name.php",
method: "POST",
data: $("#form_id").serialize(),
success: function () {
alert("success"); //do something
},
error: function () {
alert("doh!"); // do something else
}
});
This is an example for POST requests dealing with sensitive form data (or data that you'll bind to a UPDATE or INSERT query, for example). I included the serialize() function in order to handle the name fields from the form on your back end. I also removed passing the data through the success function. You don't want to do that when dealing with sensitive data or data you don't plan on displaying. Figured I would post this here since this thread came up when I searched how to do a POST with AJAX that returns an error.
Speaking of returning an error, you'll want to do this instead now that PHP has updated again. I also recommend reading through 5.4+ docs.
http_response_code(404);
die();
I threw in a die() function to make sure nothing else happens after you request your 404.
Try with the following snippet instead:
var x = ($(this).text());
$.ajax({
type: 'POST',
url: 'process.php',
data: { text1: x },
success: function(response){
$('#tooltip').text(response);
},
error: function(error) {
console.log(error);
}
});
Use the PHP function json_encode on an array. The array will then be presented to javascript as a JSON object (the 'response' argument/parameter).
In other words:
PHP:
// important to tell your browser what we will be sending
header('Content-type: application/json; charset=utf-8');
... bla bla code ...
// Check if this has gone right
$success = $results->execute();
$row = $results->fetch();
$html = $row[0];
$result = [
'success' => $success,
'html' => $html,
];
print json_encode($result);
JavaScript:
// You may now use the shorthand
$.post('process.php', { text1: x }, function(response) {
if (response.success) {
$('#tooltip').text(response.html);
} else {
... show error ...
}
});
I'm trying to use slim framework and when I do a POST to enter a record does absolutely nothing. I'm afraid I pass the parameter identified as null because if I allow it in the database, enter a null record.
this is mi Slim PHP.
$app-> post("/banda/", function() use($app){
$nombre=$app->request->post("nombre");
try{
$connection = getConnection();
$dbh = $connection->prepare("INSERT INTO banda VALUES(null, ?)");
$dbh->bindParam(1, $nombre);
$dbh->execute();
$banda = $connection->lastInsertId();
$connection= null;
$app->response->headers->set("Content-type","application/json");
$app->response->status(200);
$app->response->body(json_encode($banda));
}catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
});
And this is my JS
var API_URI = "http://localhost/banda/";
function limpiar() {
$("#form-band input:first-child").val("");
}
function nombreBandaEsVacia() {
return ($("#form-band input:first-child").val().length == 0);
}
function getBandaJSON() {
return JSON.stringify({
nombre: getBandaNombre()
});
}
function getBandaNombre() {
return $("#form-band input:first-child").val();
}
$("#form-band input:last-child").on("click", function createBanda() {
if (nombreBandaEsVacia()){
alert("Oops! Completa el formulario!");
}else{
// 1.2 JSON.Stringify
var banda = getBandaJSON();
};
$.ajax({
type:'POST',
crossDomain: true,
url:API_URI,
data:banda,
dataType:"json",
beforeSend: function() {
console.log(banda);
},
success:function(response, banda) {
limpiar();
},
error:function(jqXHR, data, textStatus, errorThrown) {
console.log(data);
console.log(errorThrown);
console.log(jqXHR);
console.log(textStatus);
}
});
});
My navigator say this:
http://s2.subirimagenes.com/imagen/previo/thump_91447311.png
By the look of it, you are sending a string to your php script instead of key-value pairs.
You can either use something like:
data: {'my_banda_json': banda},
and parse it at the server-side before you try to insert it.
Or you can just send what you need in a way that the back-end is now expecting it:
data: {'nombre': value_of_the_banda_name_field},
I am trying to create a simple AJAX call using JSON, but I keep getting a parse error on the result and when I check the resultText it shows the source code of the entire page, with the JSON response showing a success above the page headers.
Here is my AJAX call, where #class is a select box with values.
$("#class").change( function () {
if($('#class').val().length > 0){
$.ajax({
type: "GET",
url: "http://192.168.0.9/ajax",
data: 'class_id=' + $("#class").val(),
datatype: 'json',
async: 'true',
beforeSend: function() {
alert("Before send!");
},
success: function(result){
if (result.status){
$('#result').html(result);
} else {
alert('request unsuccessful!');
}
},
complete: function() {
alert("Complete!");
},
error: function (request,error) {
alert('A jQuery error has occurred. Status: ' + error +':'+ request.responseText);
$("#result").html(request.responseText);
}
});
} else {
alert('Please make a selection');
}
return false;
});
This is my PHP function that returns the result
$result = array();
$result['status'] = "success";
$result['message'] = "Types";
header("Content-Type: application/json; charset=utf-8", true);
echo json_encode($result);
Finally, this is the response I am getting in my error alert:
A jQuery error has occurred status:parseerror
{"status":"success", "message":"Types"}<!DOCTYPE html>
<html>
...rest of my page from where the request was sent
I am hoping this is a simple error and someone can tell me what I am doing wrong?
Perhaps your parameter should be pass in JSON format:
data: "{'class_id':'" + $("#class").val() + "'}",
Try to remove datatype:'json' from the Javascript and header("Content-Type: application/json; charset=utf-8", true); it should be recognize itself