ajax post values is empty - php

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>';
}
?>

Related

Php ajax fetching same file html again and again

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.

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 in jquery, php isset cannot detect the value posted

I am asking for help with my code. I am trying to get values then send it to php script through ajax by jquery. I can get the values but I don't know what's wrong with it. Your help is appreciated :)
Ajax:
$(".Qty").submit(function(e){
data_form = parseInt($(this).find(".buyQty").val());
id = parseInt($(this).attr('name'));
console.log("id :", id, "Quantity: ", data_form);
$(this).find(".addCart").val('Adding...');
$.ajax({
url: "php/cart_process.php",
type: "POST",
data: {'id': id, 'qty': data_form},
success: function(data){
$("#cart-info").html(data.items);
$(".Qty").find(".addCart").val('Add to Cart');
alert("Item added to Cart!");
if($(".shopping-cart-box").css("display") == "block"){
$(".cart-box").trigger( "click" );
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("some error");
}
});
e.preventDefault();
});
php:
<?php
if(isset($_POST['id'])){
$id = $_POST['id'];
echo "<script>console.log('id received: " .$id. "' );</script>";
}
?>
Your php script isn't returning a JSON object like your JS expects.
Your JS expects data to be a JSON object and you are trying to get the value in the index items. E.G data.items
Try this.
PHP
<?php
if(isset($_POST['id'])){
$output = array();
$id = $_POST['id'];
$output['items'] = "<p>id received: {$id} </p>";
echo json_encode($output);
}
?>
JQuery
$(".Qty").submit(function(e){
data_form = parseInt($(this).find(".buyQty").val());
id = parseInt($(this).attr('name'));
console.log("id :", id, "Quantity: ", data_form);
$(this).find(".addCart").val('Adding...');
$.ajax({
url: "php/cart_process.php",
type: "POST",
data: {'id': id, 'qty': data_form},
success: function(data){
console.log('raw data:');
console.log(data);
$("#cart-info").html(data.items);
$(".Qty").find(".addCart").val('Add to Cart');
alert("Item added to Cart!");
if($(".shopping-cart-box").css("display") == "block"){
$(".cart-box").trigger( "click" );
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("some error");
}
});
e.preventDefault();
});

ajax not sendind data to php

I have a function that is supossed to send data to a php file..although i get an alert that shows the correct ID and a success message, when trying to echo it out in my process.php, nothing is showed..the function is in adopt.php, the file that refers to process.php:
<script type="text/javascript">
$(function(){
$('#loginform').submit(function(e){
return false;
});
<?php
$q = pg_query($conn, "SELECT * FROM caini_donati");
while($res = pg_fetch_assoc($q)){ ?>
$('#<?php echo $res['id_caine']; ?>').leanModal({ top: 110, overlay: 0.45, closeButton: ".hidemodal" });
$("#<?php echo $res['id_caine']?>").click(function(event) {
var id_caine = event.currentTarget.id;
alert(id_caine);
$.ajax({
type: 'POST',
url: 'process.php',
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: { id_caine : id_caine},
success: function(data){
alert("succes"),
console.log(data);
}, error: function(xhr, ajaxOptions, thrownError) {alert ("Error:" + xhr.responseText + " - " + thrownError );}
});
});
<?php } ?>
});
</script>
in process.php i have:
<?php
$var = $_POST['id_caine'];
echo "tr1: ".$_POST['id_caine'];
echo "try: ".$var;
?>
Does anyone know what I'm doing wrong? In process.php i want to run an update query based on the 'id_caine' variable..Any ideea is apreciated..Not important but I have altmost no knowledge about ajax.
RiggsFolly is correct, you are missing the javascript html tags, i have tweaked your code to show you where they should be. Also i corrected the success method so that you actually had a variable to work with. You defined rs as the parameter but then tried to use "data" instead.
<?php
$q = pg_query($conn, "SELECT * FROM caini_donati");
while($res = pg_fetch_assoc($q)){ ?>
<script type="text/javascript">
$('#<?php echo $res['id_caine']; ?>').leanModal({ top: 110, overlay: 0.45, closeButton: ".hidemodal" });
$("#<?php echo $res['id_caine']?>").click(function(event) {
var id_caine = event.currentTarget.id;
alert(id_caine);
$.ajax({
url: 'process.php',
type: 'POST',
data: { id_caine : id_caine},
dataType: 'html',
success: function(data){
alert("succes"),
console.log(data);
}, error: function(xhr, ajaxOptions, thrownError) {alert ("Error:" + xhr.responseText + " - " + thrownError );}
});
});
</script>
<?php } ?>

Post simple form with ajax and Json

I'm trying to get a form to work with Ajax and json but can't seem to work it out:(
If anyone can help out I'd really appreciate it! Been reading so many different tutorials but not getting it right.
In my index.php I have a form with only a image that works as a button.
Then in another file (allFunctions.php) I have a class. Within that class I have a function called
giveCandy() which is connected to the button.
Then I have a js file that I'm now trying to get working with this. But When I click the button the page still refreshes and I get the value true printed out.
UPDATE: Still problem with the page refreshing...
The index.php file:
<form action="index.php" method="POST">
<input type="hidden" name="candy" />
<input type="image" id="button_candy" class="four columns" src="views/img/candy.png"/>
</form>
Then in my functions file:
function giveCandy ()
{
if ( isset($_POST['candy']))
{
$db = Database::getInstance();
$classUser = new user();
$userId = $classUser->getUserData($_SESSION['id']);
$user = $userId['id'];
$candyPiece = 10;
$query = $db->prepare("SELECT fullness, lastfed FROM userdata WHERE id = ?");
$query->bindValue(1, $user);
$query->execute();
$data = $query->fetch();
$newFullness = $candyPiece + $data['fullness'];
try
{
$query = $db->prepare("UPDATE userdata SET fullness = $newFullness, lastfed = CURRENT_TIMESTAMP WHERE id = ?");
$query->bindValue(1, $user);
$query->execute();
//$this->calculateFullness();
echo json_encode($query);
}
catch (PDOException $e)
{
echo 'Sorry iti could not eat at this time';
}
}
}
Then the js file:
$(document).ready(function () {
$('#button_candy').click(function (event) {
event.preventDefault();
$.ajax({
url: 'index.php',
method: 'POST',
data: $(this).serialize(), // your formdata (this refers to the form element)
dataType: 'json',
success: function (data) { // data is what your allFunctions.php php echos
$('#query').fadeOut(function () {
$('#query').html(data).fadeIn();
});
console.log('Ajax request returned successfully.');
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('Ajax request failed: ' + textStatus + ', ' + errorThrown);
},
});
});
});
allFunctions.php:
if ($_POST['candy']) {
allFunctions::giveCandy();
}
class allFunctions {
static function giveCandy ()
{
$db = Database::getInstance();
// ....
Js:
$(document).ready(function () {
$('#button_candy').submit(function (event) {
event.preventDefault();
$.ajax({
url: '../model/allFunctions.php',
method: 'POST',
data: $(this).serialize(), // your formdata (this refers to the form element)
dataType: 'json',
success: function (data) { // data is what your allFunctions.php php echos
$('#result').fadeOut(function () {
$('#result').html(data).fadeIn();
});
console.log('Ajax request returned successfully.');
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('Ajax request failed: ' + textStatus + ', ' + errorThrown);
},
});
});
});

Categories