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>
Related
I am working on notifications in php.
In header file, I have written this function:
$(document).ready(function() {
setInterval(getNotifys, 10000);
function getNotifys(){
$.ajax ({
method: "POST",
url : 'get_notification.php',
success : function(data){
console.log(data);
$('.notifications').html(data);
}
});
}
});
And here is get_notification.php;
<?php
include("global.php");
if($logged==0){
header("location:".$baseurl."login.html");
exit();
}
$data=mysqli_query($con,"select * from notifications where admin=1 and resolved=0") or die (mysqli_error());
$count = mysqli_num_rows($data);
?>
<span class="badge badge-danger" style="margin-bottom:25px"><?php echo $count; ?></span>
It works perfectly over most of the pages, but in some pages, it occurs that instead of displaying count to notification icon, it shows whole page HTML. Even when I console in success function, It consoles whole page HTML. I am so confused why is it happening. Any ideas?
use json and create that span stuff in your javascript code.
<?php
include("global.php");
if(!$logged) {
http_response_code(401); // catch this error in ajax
exit();
}
$data = mysqli_query($con,"select * from notifications where admin=1 and resolved=0");
if(!$data) {
http_response_code(500); // catch this error in ajax
exit();
}
$count = mysqli_num_rows($data);
echo json_encode(['count' => $count]);
JS:
$(document).ready(function() {
setInterval(getNotifys, 10000);
function getNotifys(){
$.ajax ({
method: "POST",
url : 'get_notification.php',
success : function(data){
let data = JSON.parse(data);
console.log(data);
$('#notifications_count').html(data.count);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
}
});
HTML:
<span class="badge badge-danger" style="margin-bottom:25px" id="notifications_count"></span>
Did not test this, but this shows you how you could do it.
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.'
so I have the following code that is calling a CheckEmail2.php. I know what I want to do in CheckEmail2.php but because my Ajax success is not working, I have minded the scope to just return a Json. below is my java script. When I launch my console, I see my string coming through that I am echoing in my CheckEmail2.php. so I know my php file is getting read but why won't my success function hit if my string is getting read? I can't get my success function to get called. It always goes to error.
<script type="text/javascript">
function validateForm(){
var email = document.forms["signupform"]["email"].value;
var result = false;
if (email != ""){
$.ajax({
type: "POST",
url: "/CheckEmail2.php",
data: { "User_Email": email },
dataType: "json",
success: function(resp){
console.log(resp);
if(resp == "Not Found"){
result = true;
}
else
{
result = false;
}
},
error: function(data, status){
console.log(data, status);
}
}); //end Ajax
}
return result;
}
</script>
here is my PHP
<?php
header("Content-type:application/json");
echo json_encode("Not Found");
?>
why is error always getting called?
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
Code:
query = "http://localhost:8080/working_login.php?name=" + name + "&password=" + pass;
console.log(query);
$.ajax({
type: "GET",
url: query,
dataType: "script",
success: function(data){
console.log(data);
console.log("success");
},
error:function (msg) {
console.log("error on page");
}
});
I am getting undefined in data and as I am returning 'valid_user' from the server side made in php, getting error.
Uncaught ReferenceError: valid_user is not defined
(anonymous function)
Php server side code:
$sql = "SELECT id FROM users WHERE name ='$name' AND password = '$password';";
$result = mysql_query($sql) or die('Can not Register user' . $sql );
$rows = mysql_num_rows($result);
if($rows > 0)
{
echo("valid_user");
exit();
}
else
{exit("not valid user");}
when using the script dataType in the jquery ajax reqeust, the returned result is interpreted as javascript code, but you return plain text
simply change dataType: "script" to dataType: "text".
You probably didn't mean to tell jQuery that you were expecting a script in return. What's being returned isn't a properly formatted script, so it's giving you an error when the browser parses as a script.
You could just do the following:
$.get("http://localhost:8080/working_login.php?name=" + name + "&password=" + pass, function(data) {
if(data == 'success')
{
alert("Success");
}
else
{
alert("Failed");
}
});