Jquery AJAX not taking in JSON from the php file - javascript

I have been trying to fetch data from the server using jquery .ajax function.
However it's not working whenever I give data Type as JSON.
It works fine when I don't define dataType, but I need dataType to be JSON..
Below are the codes.
Practice.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Practice</title>
<?php
require("db.php");
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div>Why doesn't it work..</div>
<div id="demo"></div>
<button type="button" id="button" name="button">button</button>
</body>
<script>
//Load table
$('#button').on('click', function(){
// var please = 1;
$.ajax({
type: 'POST',
url: 'AJAX.php',
// data: {id: please},
dataType: 'json',
success: function(data) {
$('#demo').text('Worked!');
console.log(data);
},
error: function(error) {
$('#demo').text('Error : ' + error);
console.log(error);
}
});
});
</script>
</html>
AJAX.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Ajax Practice</title>
<?php
require("db.php");
?>
</head>
<body>
<?php
if (isset($_POST["id"])) {
$id = $_POST["id"];
} else {
$id = 1;
}
$stmt = $conn->prepare("SELECT * FROM projects WHERE id=$id");
$stmt->execute();
$all = $stmt->fetchAll(PDO::FETCH_ASSOC);
$all = json_encode($all);
echo $all;
?>
</body>
</html>
And here is the result of the echo..
[
{
"Project":"BPM",
"Date":"2018-03-02 00:00:00",
"Manager":"Someone",
"Status":"2",
"ID":"1",
"Counter":null
}
]
I'm pretty new to Jquery and web programming generally..
Please advise, your help is greatly appreciated.

Remove all HTML from your AJAX.php then add the code below to the top of your AJAX.php
header('Content-Type: application/json');

<?php
require("db.php");
if (isset($_POST["id"])) {
$id = $_POST["id"];
} else {
$id = 1;
}
$stmt = $conn->prepare("SELECT * FROM projects WHERE id=$id");
$stmt->execute();
$all = $stmt->fetchAll(PDO::FETCH_ASSOC);
$all = json_encode($all);
echo $all;
?>
Change Your Ajax code to This. Because here there is no need of html Content
You can use mysqli_real_escape_string

since you specified dataType: 'json' your js is expecting json format. Right now, you are returning including the <head>, <beody> html tags.
On your AJAX.php
<?php
require("db.php");
if (isset($_POST["id"])) {
$id = $_POST["id"];
} else {
$id = 1;
}
$stmt = $conn->prepare("SELECT * FROM projects WHERE id=$id");
$stmt->execute();
$all = $stmt->fetchAll(PDO::FETCH_ASSOC);
$all = json_encode($all);
echo $all;
?>

You need to parse it in your AJAX. Try this...
$('#button').on('click', function(){
// var please = 1;
$.ajax({
type: 'POST',
url: 'AJAX.php',
// data: {id: please},
dataType: 'json',
success: function(data) {
var response = JSON.parse(data);
$('#demo').text('Worked!');
console.log(response);
},
error: function(error) {
$('#demo').text('Error : ' + error);
console.log(error);
}
});
});

Related

Refresh page if there is change in database

I am trying to refresh my a page if there is a change in orderStatus from database using Ajax and PHP. I set the current orderStatus as predefined data and then use Ajax to get the current orderStatus from database and finally compare if they are not the same. I want to refresh the page if they are not the same.
PHP (autorefresh.php)
<?php
$orderId = $_POST["orderId"];
$query = "SELECT * FROM orderinhomeonlinecall WHERE orderId='$orderId'";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_array($result))
{
$orderStatus = $row['orderStatus'];
$data = array(
'orderStatus' => $orderStatus
);
echo json_encode($data);
}
?>
Javascript
<script type="text/javascript" >
var predefined_val = '<?php echo $orderStatus; ?>';// your predefined value.
$.document(ready(function(){
setInterval(function(){
$.ajax({
type:"POST",
url:"autorefresh.php", //put relative url here, script which will return php
data:{orderId: <?php echo $orderId; ?>}, // if any you would like to post any data
success:function(response){
var data = response; // response data from your php script
if(predefined_val !== data){
window.location.href=window.location.href;
}
}
});
},5000);// function will run every 5 seconds
}));
The below code should work, Need to mention dataType:"json" else use JSON.stringify(data) to parse response
<script type="text/javascript">
var predefined_val = '<?php echo $orderStatus; ?>';// your predefined value.
$(document).ready(function () {
setInterval(function () {
$.ajax({
type: "POST",
url: "autorefresh.php", //put relative url here, script which will return php
data: {orderId: <?php echo $orderId; ?>}, // if any you would like to post any data
dataType: "json",
success: function (response) {
var data = response; // response data from your php script
if (predefined_val !== data.orderStatus) {
window.location.href = window.location.href;
}
}
});
}, 5000);// function will run every 5 seconds
});
</script>
I have tested this by creating two files(autorefresh.php,index.php) and test db with table and it is working for me. I think the below code would be helpful, If not please share you code, i will check and fix it.
autorefresh.php
// Create connection
$db = new mysqli("localhost", "root", "","test");
$orderId = $_POST["orderId"];
$query = "SELECT * FROM orderinhomeonlinecall WHERE orderId='$orderId'";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_array($result))
{
$orderStatus = $row['orderStatus'];
$data = array(
'orderStatus' => $orderStatus
);
echo json_encode($data);
}
?>
index.php
<?php
$orderStatus ='pending';
$orderId =1;
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
var predefined_val = '<?php echo $orderStatus; ?>';// your predefined value.
$(document).ready(function () {
setInterval(function () {
$.ajax({
type: "POST",
url: "autorefresh.php", //put relative url here, script which will return php
data: {orderId: <?php echo $orderId; ?>}, // if any you would like to post any data
dataType: "json",
success: function (response) {
var data = response; // response data from your php script
if (predefined_val !== data.orderStatus) {
window.location.href = window.location.href;
}
}
});
}, 5000);// function will run every 5 seconds
});
</script>

How to solve this "Uncaught ReferenceError: $ is not defined"

I have some code where I need to update a column of a table (MySQL) calling another php file without leaving the page where some tables might allow inline editing.
I have a point in the php echoing of the page, where an icon can be clicked to save input. The code at that point is:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<?php
$sql = "SELECT * FROM table WHERE a_column='certain_value'";
if (mysqli_query($conn, $sql)) {
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$note = $row["note"];
$code = $row["code"];
}
}
}
// some tabled elements not relevant for the issue
echo "<input type='text' id='note_1' name='note_1' value=$note readonly>";
echo "<input type='text' id='new_note' name='new_note'>";
echo "<img src='icon_to_click.png' id='icon_to_click' name='icon_to_click' >";
?>
<script type="text/javascript">
$(document).ready(function() {
$('#icon_to_click').click(function() {
var note_orig = document.getElementById('note_1').value;
var code_val = '<?php echo "$code" ?>';
var note_new = document.getElementById('new_note').value;
if (note_new != note_orig) {
$.ajax({
type: 'POST',
url: 'update_notes.php',
data: {'code': code_val, 'note': note_new},
success: function(response){
document.getElementById('note_1').value = note_new;
}
});
}
});
});
The relevant code of update_notes.php is:
<?php
// connection
$unsafe_note = $_POST["note"];
$code = $_POST["code"];
require "safetize.php"; // the user input is made safe
$note = $safetized_note; // get the output of safetize.php
$sqlupdate = "UPDATE table SET note='$note' WHERE code='$code'";
if (mysqli_query($conn, $sqlupdate)) {
echo "Note updated";
} else {
echo "Problem in updating";
}
// close connection
?>
Now when I run the code and look at the tool, it gives me the error: Uncaught ReferenceError: $ is not defined, linking the error to this line of the previous js code:
$(document).ready(function() {
So, how can I fix that?
It means that you tried to use Jquery in your Javascript Code without calling Jquery Library or the code is called without the library was fully loaded.
I notice :
That you haven't closed your script tag
You use Jquery so you can use $('#id_name') to select element by Id instead of document.getElementById('note_1')
Get element value by using Element.val() instead of Element.value
Try to edit your code like this
<?php
$sql = "SELECT * FROM table WHERE a_column='certain_value'";
if (mysqli_query($conn, $sql)) {
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$note = $row["note"];
$code = $row["code"];
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Some title</title>
</head>
<body>
<form method="post" accept-charset="UTF-8">
<input type='text' id='note_1' name='note_1' value=<?= $code ?> readonly>";
<input type='text' id='new_note' name='new_note'>";
<img src='icon_to_click.png' id='icon_to_click' name='icon_to_click' >";
</form>
<script>
$(document).ready(function() {
$('#icon_to_click').click(function() {
var note_orig = $('#note_1').val();
var code_val = '<?= $code ?>';
var note_new = $('#new_note').val();
if (note_new != note_orig) {
$.ajax({
type: 'POST',
url: 'update_notes.php',
data: {'code': code_val, 'note': note_new},
success: function(response){
$('#note_1').val() = note_new;
}
});
}
});
});
</script>
</body>
</html>
Hey I have faced same error a day before,this is because you have missed using a jquery library script that is needed. please try using some Updated Jquery CDN . :) It will definitely help
OR
include the jquery.js file before any jquery plugin files.

how to retrieve a javascript variable in php and add it to the database

I need a help please,i am beginner with ajax. I'm trying to create a chronometer, I want when he clicks on the button he gets the value that went through ajax and the insert in the database. When I execute the code it does not have errors but also it does not insert into the database.
<?php
$pdo = new PDO('mysql:host=localhost;dbname=jeu', 'root', '', array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES cp1256'
));
?>
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body >
<span id="mySpan" style="font-size: 80px;">20</span>
<input id="arret" type="button" value="Arret">
<script type="text/javascript">
function decrementer() {
if ( mySpan.innerHTML > 0 ) {
mySpan.innerHTML-- ;
setTimeout(decrementer, 1000);
}
}
setTimeout(decrementer, 1000) ;
var element = document.getElementById('arret');
element.onclick = function() {
var chrono=mySpan.innerHTML;
$.ajax({
type: "GET",
data: {chrono : chrono},
success: function(data)
{
console.log(chrono);
}
});
};
</script>
<?php
if(isset($_GET['chrono']))
{
$uid = $_GET['chrono'];
echo($uid );
$resultat = $pdo -> prepare("INSERT INTO ajaxtest (name) VALUES (:name)");
$resultat -> bindParam(':rep', $uid, PDO::PARAM_STR);
if($resultat -> execute()){
$id_insere = $pdo -> lastInsertId();
}
}
?>
</body>
</html>
I would suggest that you separate your php and html, then send data to the php using ajax.
On your php you are binding :rep but you placeholder is :name therefore you need to bind :name
$resultat -> bindParam(':name', $uid, PDO::PARAM_STR);
html side.
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body >
<span id="mySpan" style="font-size: 80px;">20</span>
<input id="arret" type="button" value="Arret">
<script type="text/javascript">
function decrementer() {
if ( mySpan.innerHTML > 0 ) {
mySpan.innerHTML-- ;
setTimeout(decrementer, 1000);
}
}
setTimeout(decrementer, 1000) ;
var element = document.getElementById('arret');
element.onclick = function() {
var chrono=mySpan.innerHTML;
$.ajax({
type : "POST",
url : "somefile.php", //url to send data to
data: {chrono : chrono},
success: function(data)
{
console.log(data); //log data back
}
});
};
</script>
</body>
</html>
somefile.php
<?php
$pdo = new PDO('mysql:host=localhost;dbname=jeu', 'root', '', array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES cp1256'
));
$uid = isset($_POST['chrono']) ? $_POST['chrono'] : null;
$resultat = $pdo->prepare("INSERT INTO ajaxtest (name) VALUES (:name)");
$resultat->bindParam(':name', $uid, PDO::PARAM_STR);
if ($resultat->execute()) {
$id_insere = $pdo->lastInsertId();
echo json_encode("data inserted success");
}
?>

PHP variable not being passed to AJAX call?

Im trying to get my PHP script called from AJAX (that is in my main php file).
Here's an example of what it is supposed to do: http://jsfiddle.net/xfuddzen/
The HTML source code shows only desk_box DIV being created (which is in my main.php). station_info DIV (being created in the display_station.php) is not there. How can I fix this? thanks in advance
Problem: DIVs from my display_stationinfo.php are not being created by using the AJAX call.
main.php with JQuery/AJAX part:
<div id="map_size" align="center">
<?php
//didsplay Desk stations in the map
while($row = mysqli_fetch_assoc($desk_coord_result)){
//naming X,Y values
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
//draw a box with a DIV at its X,Y coord
echo "<div class='desk_box' data='".$id."' style='position:absolute;left:".$x_pos."px;top:".$y_pos."px;'>id:".$id."</div>";
} //end while loop for desk_coord_result
?>
<script type="text/javascript">
//Display station information in a hidden DIV that is toggled
//And call the php script that queries and returns the results LIVE
$(document).ready(function() {
$('.desk_box').each((function(){(this).click(function() {
var id = $(this).attr("data")
$("#station_info_"+id).toggle();
$.ajax({
url: 'station_info.php',
data: { 'id': id },
type: 'POST',
dataType: 'json',
success: function(json) {
$("#station_info_"+id).css({'left':json.x_pos ,'top': json.y_pos}).append('<p>Hello the id is:'+ json.id +'</br>Section:'+ json.sec_name +'</p>');
}//end success
});//end ajax
});//end click
});//end ready
</script>
</div> <!-- end map_size -->
display_station.php (script that I want to call):
<?php
include 'db_conn.php';
//query to show workstation/desks information from DB for the DESKS
$station_sql = "SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates";
$station_result = mysqli_query($conn,$station_sql);
//see if query is good
if ($station_result === false) {
die(mysqli_error());
}
//Display workstations information in a hidden DIV that is toggled
$html = '';
if($station_result->num_rows > 0){
while($row = $station_result->fetch_object()) {
$id = $row->coordinate_id;
$html .= "<div class='station_info_' id='station_info_$id' style='position:absolute;left:{$row->x_coord}px;top:{$row->y_coord}px;'>Hello the id is:$id</br>Section:{$row->section_name}</br></div>";
}
}
else{
// no results - may want to do something with $html
$html = "no result given";
}
$station_result->free();
$conn->close();
echo $html;
?>
Why dont you filter the coordinate in the query? Like this:
$station_sql = "SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates WHERE coordinate_id = " . $_GET['coordinate_id'];
And in jquery code:
url: 'display_stationinfo.php?coordinate_id=' + id,
Let's start with your database connection, which should be on a separate secure page.
connect.php:
<?php
function db(){
return new mysqli('host', 'username', 'password', 'database');
}
?>
Obviously, your host will not be 'host'.
Now main.php:
<?php
// only use for PHP on this page for initial page load - target other pages with AJAX
?>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>This is Where Your Title Goes</title>
<script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>
<script type='text/javascript' src='main.js'></script>
<link rel='stylesheet' type='text/css' href='main.css' />
</head>
<body>
<div id='map_container'>
<div id='map_size'>
</div>
</div>
</body>
</html>
Now for main.js:
//<![CDATA[
$(function(){
var ms = $('#map_size');
$.post('main_init.php', {init:'1'}, function(d){
for(var i in d){
var di = d[i], x = di.x, y = di.y;
var sti = $("<div class='station_info_' id='station_info_"+i+"'></div>").css({
left:x,
top:y
});
// HTML id, class, and name attributes cannot start with a number
$("<div class='desk_box' data='"+i+"'>id:"+i+'</div>').css({
left:x,
top:y
}).appendTo(ms).append(sti).click(function(){
var info = $(this).next();
$.post('live_info.php', {station_id:info.attr('id').replace(/^station_info_/, '')}, function(r){
// do stuff with r
info.html('love:'+r.love+'<br />hate:'+r.hate).toggle();
}, 'json');
});
}
}, 'json');
});
// use CSS to do `.desk_box,.station_info_{position:absolute;}`
//]]>
Now for main_init.php:
<?php
if(isset($_POST['init']) && $_POST['init'] === '1'){
include_once 'connect.php'; $db = db(); $json = array();
$q = $db->query("SELECT * FROM table WHERE"); // example only
if($q->num_rows > 0){
while($r = $q->fetch_object()){
$json[strval($r->coordinate_id)] = array('x' => $r->x_coord, 'y' => $r->y_coord);
}
}
else{
// no results
}
$q->free(); $db->close();
echo json_encode($json);
}
else{
// could be a hack
}
?>
Here's what live_info.php might look like:
<?php
if(isset($_POST['station_id'])){
include_once 'connect.php'; $db = db(); $json = array();
// example only - you will only get one `$row` if query is done specific, so while loop is not needed
$q = $db->query("SELECT love,hate FROM some_table WHERE id='{$_POST['station_id']}'");
if($q->num_rows > 0){
$row = $q->fetch_object();
// it's okay to overwrite array in this case
$json = array('love' => $row->love, 'hate' => $row->hate);
}
else{
// no results
}
$q->free(); $db->close();
echo json_encode($json);
}
else{
// may be a hack
}
?>

jquery ajax => Undefined index php

i have problem with php.
AJAX
$(document).ready(function(){
$.ajax({
type: "POST", // i test post, get...
url:'TESTING.php',
data: {name: "alfred"},
success: function(){
alert("success"); // it show "success" !... :/
}
});
});
And php
<?php
//var_dump($_POST); array is empty
$name = $_POST['name']; // error line
echo $name;
?>
I test it on Localhost (if it is the problem). And i dont know, where is mistake.
Thanks for any help
Along with what the comments say about $_GET not grabbing $_POST data you sent, you are not using the return data.
success: function(data){ //response param
alert(data);
}
var weightd = $("#weight").val();
var user_id = <?php echo $current_user->ID; ?>;
$.ajax({
type: "POST",
url:"<?php bloginfo('template_directory')?>/ajax/index.php",
data: { weight:weightd,user_ids:user_id},
success:function(result){
$("#result1").html(result);
setInterval(function() {
$('#result1').hide('slow');
}, 5000);
}});
<div id="result1"></div>
try to user like this
You are sending the data via POST, not GET .
Change
$name = $_GET['name'];
To
$name = $_POST['name'];
Your callback function must have argument,
Change
success: function(){
alert("success");
}
To
success: function(data){
alert("success"); // or whatever you wanna do
}
Here is all code
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="//code.jquery.com/jquery.js"></script>
</head>
<body>
</body>
<script>
$(document).ready(function(){
$.ajax({
type: "POST",
url:'TESTING.php',
data: {name: "Alfred"},
success: function(data){ //response param
alert(data);
}
});
});
</script>
<?php
echo "Hi ";
//var_dump($_POST);
$nick = $_POST['name'];
echo $nick;
?>
</body>
</html>

Categories