Php ajax fetching same file html again and again - php

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.

Related

return json from php to Ajax call

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>

Ajax query, php file is getting read but can't enter success function

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?

ajax post values is empty

I wanted to get the data from the ajax post which are the student name and student religion(abdullah and muslim) values in the passwrapper.php and post those values on the console.log. However, i cant find the posted values on the console.log. i want to show those posted values on the console.log.
Here is my code below....
orignially my code is about performing ajax post to the passwrapper.php
and then the passwrapper.php include another script, student.php to show all the data on the html file.
HTML FIle
<html>
<head>
<script type="text/javascript" src="/Cesium-1.34/ThirdParty/jquery-1.11.3.min.js"></script>
</head>
<div id="resulte"</div>
<script type="text/javascript">
showData();
function showData()
{
$.ajax({
type: "post",
url: "passwrapper.php",
contentType: "application/json",
dataType: "json",
data: {
lastName: 'Abdullah',
lastReligion: 'Muslim',
},
success: function(data){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('An error occurred... Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information!');
$('#resulte').html('<p>Status Code: '+jqXHR.status+'</p><p>ErrorThrown: ' + errorThrown + '</p><p>jqXHR.responseText:</p><div>'+jqXHR.responseText + '</div>');
console.log('jqXHR:');
console.log(jqXHR);
console.log('textStatus:');
console.log(textStatus);
console.log('errorThrown:');
console.log(errorThrown);
},
});
};
</script>
</body>
</html>
Passwrapper.php
<?php
include 'student.php';
executePass();
receivePost();
function receivePost()
{
if ((!isset($_POST["lastName"])) and (!isset($_POST["lastReligion"])))
{
//do nothing
}
else
{
echo '<script>console.log("Firstname='.$_POST["lastName"].' lastReligion='.$_POST["lastReligion"].'");</script>';
}
}
?>
student.php
<?php
function executePass()
{
$conn = mysqli_connect('localhost','root','netwitness') or die ("Could not connect database");
$db = mysqli_select_db($conn,'abdpractice') or die ('Could not select database');
$result = mysqli_query($conn,"select * from student");
$json_array = array();
while ($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
echo json_encode($json_array);
}
?>
my question is how to post those values abdullah and muslim on the console.
try this,
<?php
include 'student.php';
executePass();
if ((!isset($_POST["lastName"])) and (!isset($_POST["lastReligion"])))
{
//do nothing
}
else
{
//post the values(Abdullah and Muslim) on the console.log on the passwrapper.php
//i do not want to disrupt the executepass()
echo '<script>console.log("Firstname='.$_POST["lastName"].' lastReligion='.$_POST["lastReligion"].'");</script>';
}
?>

how to show error message if result in json is fail?

In Ajax, the success part always executes. But if there is an error , I don't want to execute the normal; instead I want to show an error message.If the discount code is present then show/hide some div along with code and then redirect, else display the error message which we get in json response in the error div. How can i achieve this ?
Here is json response :
{result: "fail", msg: "Code is not valid", redirect: 0}
controller :
if($result == 'exp'){
$discount_arr ['result'] = 'fail';
$discount_arr['msg'] = 'Promotion code expired';
$discount_arr['redirect'] = 0;
}else{
$discount_arr ['result'] = 'success';
$discount_arr['msg'] = 'Valid Code';
$discount_arr['url'] = base_url('cart');
$discount_arr['redirect'] = 1;
}
echo json_encode($discount_arr);
HTML :
<div class="cart-secondary cart-discount-code">
<label for="cart_Code">
Discount Code </label>
<input type="text" class="discount-code" name="cart_discountCode" id="cart_discountCode">
<span class="error coupon-error"></span>
<div class="confirm-coupon"></div>
<button type="submit" value="addCoupon" name="addCoupon" id="add-coupon" onclick="checkStatus()">
Apply </button>
Ajax:
function checkStatus(){
var discount_code = $(".cart-secondary .cart-discount-code .discount-code").val();
$.ajax(
{
url : "<?php echo base_url('cart/validate/'); ?>",
type : "POST",
data : {discount_code: discount_code} ,
cache : false,
dataType:'json',
statusCode: {
404: function() {
alert( "page not found" );
}
},
success:function(data, textStatus, jqXHR)
{
if(textStatus == 'success'){
$('input[name=cart_discountCode]').val(discount_code);
$('.cart-secondary .cart-discount-code-show span').html(discount_code);
$(".cart-discount-code").fadeOut();
$(".cart-discount-code-show").fadeIn();
if(data.redirect){
window.location.reload();
}
}
},
error: function(jqXHR, textStatus, errorThrown) {
//if fails
console.log(errorThrown);
}
});
}
Please help
just use an else for your if comparison.
update: you are accessing the wrong variable of your success-callback. you are not interested in the textStatus, you want to read the data you are returning by yourself. the returned json object is saved in the data variable:
if(data.result == 'success'){
/* ... */
}else{
$(".error").text(data.msg);
}
You can access those information in data variable of success callback of the AJAX function.
Use it like this,
success:function(data, textStatus, jqXHR)
{
if(data.result != 'fail'){
$('input[name=cart_discountCode]').val(discount_code);
$('.cart-secondary .cart-discount-code-show span').html(discount_code);
$(".cart-discount-code").fadeOut();
$(".cart-discount-code-show").fadeIn();
if(data.redirect){
window.location.reload();
}
} else {
alert(redirect.message);
if(data.redirect==1) {
// redirect here..
}
}
}
So access those data using,
data.message
data.redirect
data.result
It's normally as you access property of any JavaScript object.
If you are getting
{result: "fail", msg: "Code is not valid", redirect: 0} in success block,
then do this
success:function(data, textStatus, jqXHR)
{
if(data.result !== 'fail' && textStatus == 'success'){
$('input[name=cart_discountCode]').val(discount_code);
$('.cart-secondary .cart-discount-code-show span').html(discount_code);
$(".cart-discount-code").fadeOut();
$(".cart-discount-code-show").fadeIn();
if(data.redirect){
window.location.reload();
}
}
},

ajax how to return an error message from a PHP file

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

Categories