Pass an php array to another php file with ajax - javascript

I want to send an array, which I got from mysql, and send it with ajax to another php file. I can't send the data to the file. I get the data in the first PHP file. But when I set an alert with the array in JS then the output is undefined. The other PHP file didn't received any data.
PHP send to another PHP file
<?php
$id = $_GET['id'];
$items = mysqli_query($con,"SELECT * FROM COMPARISONFOLDER JOIN ITEM ON ITEM.COMPARISONFOLDER_ID LIKE COMPARISONFOLDER.COMPARISONFOLDER_ID WHERE COMPARISONFOLDER.COMPARISONFOLDER_ID LIKE $id");
while($item = mysqli_fetch_array($items)) {
$shuffledItems[] = $item;
}
shuffle($shuffledItems);
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
getItems();
});
function getItems() {
var urlActiveFillSurvey = "https://vinkovic.ch/test1/activeFillSurvey.php/";
jQuery.ajax({
type: 'GET',
url: urlActiveFillSurvey,
data: {data : '<?php echo $shuffledItems ?>'},
processData: false,
contentType: false,
success: function(data) {
jQuery('.data').html(data.responseText);
},
error: function(data) {
jQuery('.data').html(data.responseText);
}
});
}
</script>
</head>
<body>
<div class="data"></div>
</body>
</html>
PHP File which should get the array
<?php
require ('../wp-blog-header.php');
$data = $_GET['data'];
echo "<table border='1'>
<tr>
<th>Item 1</th>
<th>Item 2</th>
</tr>";
echo "<tr>";
echo '<td><img src="data:image/jpeg;base64,'.base64_encode($data[0]['ITEM']).'" width="500" height="auto"/></td>';
echo '<td><img src="data:image/jpeg;base64,'.base64_encode($data[1]['ITEM']).'" width="500" height="auto"/></td>';
echo "</tr>";
echo "</table>";

data: {data : '<?php echo $shuffledItems ?>'},
is where the error is, change to
data: {data : '<?php echo json_encode($shuffledItems) ?>'},
or base64_encode or url_encode the json out put to make it url friendly

Related

Jquery AJAX not taking in JSON from the php file

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

I am not getting response from ajax request

I am getting no response from ajax request . i am posting a ajax call to processor.php file and the processor.php file is processing the file and sending the processed file back to javascript i am gerring my result in my console log but it is not showing in the html.
My javascript code is :
function add_to_cart(item_name,item_price){
$('.user-info').slideUp('1200');
$('.cart-status').slideDown('1200');
var dataString = "item_name=" + item_name + "&item_price=" + item_price + "&page=add_to_cart";
$.ajax({
type: "POST",
url: "php/processor/processor.php",
data:dataString,
beforeSend:function(){
$(".cart-show-product").html('<h3>Your Cart Status</h3><img src="images/loading.gif" align="absmiddle" alt="Loading...." class="center" /><br><p class="center">Please Wait...</p>');
},
success: function(response){
console.log(response);
$(".cart-show-products").html(response);
}
});
}
and my php is :
if(isset($_POST['item_name']) && !empty($_POST['item_name']) && isset($_POST['item_price']) && !empty($_POST['item_price']))
{
$sql = mysqli_query($conn,
'SELECT * FROM
products_added
where
username = "'.mysqli_real_escape_string($conn, $_SERVER['REMOTE_ADDR']).'"
and
item_added="'.mysqli_real_escape_string($conn, $_POST['item_name']).'"'
);
if(mysqli_num_rows($sql) < 1)
{
mysqli_query($conn,
"INSERT INTO products_added values(
'',
'".mysqli_real_escape_string($conn, $_SERVER['REMOTE_ADDR'])."',
'".mysqli_real_escape_string($conn, $_POST['item_name'])."',
'".mysqli_real_escape_string($conn, $_POST['item_price'])."',
'".mysqli_real_escape_string($conn, '1')."',
'".mysqli_real_escape_string($conn, $_POST['item_price'])."'
'".mysqli_real_escape_string($conn, date("d-m-Y"))."')"
);
?>
<table class="cart-show-products">
<thead>
<tr>
<td>Sl.No</td>
<td>Item</td>
<td>Qty</td>
<td>Price</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<?php
$sl_no = 1;
$sql = mysqli_query(
$conn,
'SELECT sum(amount) as grandtotal
FROM products_added
WHERE username = "'.mysqli_real_escape_string($conn, $_SERVER['REMOTE_ADDR']).'"
ORDER BY id'
);
$row = mysqli_fetch_array($sql);
$grandtotal = strip_tags($row['grandtotal']);
$sql = mysqli_query(
$conn,
'SELECT
id,
item_added,
price,
quantity
FROM products_added
WHERE username = "'.mysqli_real_escape_string($conn, $_SERVER['REMOTE_ADDR']).'"
ORDER BY id'
);
$row = mysqli_fetch_array($sql);
$item_id = strip_tags($row['item_id']);
$item_name = strip_tags($row['item_added']);
$item_price = strip_tags($row['price']);
$quantity = strip_tags($row['price']);
?>
<tr class="items_wrap items_wrap<?php echo $item_id; ?>">
<td><?php echo $sl_no++; ?></td>
<td><?php echo $item_name ?></td>
<td><?php echo $quantity ?></td>
<td><?php echo $item_price ?></td>
<td><i class="fa fa-times"></i></td>
</tr>
</tbody>
</table>
<?php
}
If you're getting a response in the console, then the issue must be with your HTML. I think part of the problem is you've created a section on the HTML page wiht a class that is the same as the table the AJAX call is bringing into the page. I would suggest changing the HTML element to us an ID instead. Something like
<div id="products-table"></div>
And then change your JavaScript to
function add_to_cart(item_name,item_price){
$('.user-info').slideUp('1200');
$('.cart-status').slideDown('1200');
var dataString = "item_name=" + item_name + "&item_price=" + item_price + "&page=add_to_cart";
$.ajax({
type: "POST",
url: "php/processor/processor.php",
data:dataString,
beforeSend:function(){
$("#products-table").html('<h3>Your Cart Status</h3><img src="images/loading.gif" align="absmiddle" alt="Loading...." class="center" /><br><p class="center">Please Wait...</p>');
},
success: function(response){
console.log(response);
$("#products-table").html(response);
}
});
}
If you stay with the class names you've used, subsequent updates are going to have problems because you'll have 2 elements on the page with the same class. Your script could potentially be confused about which one to change.
If this is your actual code, then you have a syntax error in your PHP file. There are a missing close bracket for:
if(isset($_POST['item_name']) && !empty($_POST['item_name']) && isset($_POST['item_price']) && !empty($_POST['item_price']))
The second problem is, you are not print anything, if this condition has failed.
Note
You do not need to use isset, if you are checking empty. empty will return false, if the variable not set.
You can debug your respons by check NET tab in your web developer tools, or see, what is the response of the AJAX.

Update database with onClick (NewB)

Thanks for the help mighty Johan. but I cant get get my db to update. If you do have time please look over my two files and tell me what the F is wrong
my hire_staff.php
<?php
session_start();
include("header.php");
?>
<?php
$chief_aerodynamicist = $staff['chief_aerodynamicist'];
$chief_designer = $staff['chief_designer'];
$commercial_director = $staff['commercial_director'];
$pit_crew = $staff['pit_crew'];
$technical_director = $staff['technical_director'];
?>
<head>
<script>
function bye(){
alert('bye');
}
$(document).ready(function(){
function hire(){
$.ajax({
url: "update.php",
type: "POST",
data: {uid: 12341234}, //this sends the user-id to php as a post variable, in php it can be accessed as $_POST['uid']
success: function(data){
data = JSON.parse(data);
//update some fields with the updated data
//you can access the data like 'data["driver"]'
}
});
}
});
</script>
</head>
<center><h2>You can hire new staff here</h2></center>
<table cellpadding="3" cellspacing="5">
<tr>
<td>Chief Aerodynamicist:</td>
<td><i><?php echo "Level $chief_aerodynamicist"; ?></i></td>
<td><form><input type="button" value="Hire!" onClick="hire();"</form></td>
</tr>
<tr>
<td>Chief Designer:</td>
<td><i><?php echo "Level $chief_designer"; ?></i></td>
</tr>
<tr>
<td>Commercial Director:</td>
<td><i><?php echo "Level $commercial_director"; ?></i></td>
</tr>
<tr>
<td>Pit Crew:</td>
<td><i><?php echo "Level $pit_crew"; ?></i></td>
</tr>
<tr>
<td>Technical Director:</td>
<td><i><?php echo "Level $technical_director"; ?></i></td>
</tr>
</table>
<?php
include("footer.php");
?>
My test1.php file
<?php
include("functions.php");
connect();
if(isset($_POST['uid'])){
connect();
mysql_query("UPDATE `staff` SET `driver` = '3' WHERE `id`='".$_SESSION['uid']."'") or die(mysql_error());
$query = mysql_query("SELECT FROM `staff` WHERE `id`='".$_POST['uid']."'")or die(mysql_error());
$results = mysql_fetch_assoc($query);
echo json_encode($results);
}
?>
its actually the staff in the 's that I want to update but driver is also in the same table
Use jQuery and Ajax:
$(document).ready(function(){
$("#button").click(function(){
$.ajax({
url: "update.php",
type: "POST",
data: {uid: 12341234}, //this sends the user-id to php as a post variable, in php it can be accessed as $_POST['uid']
success: function(data){
data = JSON.parse(data);
//update some fields with the updated data
//you can access the data like 'data["driver"]'
}
});
});
});
//the button
<input type="button" id="button" value="Hire!"/>
//update.php
if(isset($_POST['uid'])){
//connect to the db etc...
mysql_query("UPDATE `staff` SET `driver` = '3' WHERE `id`='".$_POST['uid']."'") or die(mysql_error());
//this'll send the new statistics to the jquery code
$query = mysql_query("SELECT FROM `staff` WHERE `id`='".$_POST['uid']."'")or die(mysql_error());
$results = mysql_fetch_assoc($query);
echo json_encode($results);
}
with "update some fields" in the success function of the ajax call, I mean that you can update the statistics on the page which you just changed in the database, so that the statistics on the webpage automatically change in both the database and on the page itself
Edit
Put this in the header:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
function bye(){
alert('bye');
}
$(document).ready(function(){
$("#button").click(function(){
$.ajax({
url: "test1.php",
type: "POST",
data: {uid: 12341234}, //this sends the user-id to php as a post variable, in php it can be accessed as $_POST['uid']
success: function(data){
data = JSON.parse(data);
//update some fields with the updated data
//you can access the data like 'data["driver"]'
}
});
});
});
</script>
Then give your button the id 'button' like this:
<form><input type="button" id="button" value="Hire!"/></form>
Make sure that the url parameter of the ajax request (url: "test1.php",) is pointing to the right php page.
I hope this helped!
Edit
This is the code if you want to select a driver:
<form><input type="button" class="button" id="3" value="Hire!"/></form> //the id is different for every guy
The javascript code:
$(document).ready(function(){
$(".button").click(function(e){
$.ajax({
url: "test1.php",
type: "POST",
data: {colID: e.target.id}, //this sends the user-id to php as a post variable, in php it can be accessed as $_POST['uid']
success: function(data){
data = JSON.parse(data);
//update some fields with the updated data
//you can access the data like 'data["driver"]'
}
});
});
});
As you can see, I changed the # into a ., I added the argument e to the callback function and I added the colID to the data object.
This'll be the new PHP code:
if(isset($_POST['colID'])){
//connect to the db etc...
$colID = mysql_real_escape($_POST['colID']); //for security
$userID = mysql_real_escape($_SESSION['uid']);
mysql_query("UPDATE `staff` SET `$colID` = 'newValue' WHERE `id`='$userID'") or die(mysql_error());
//this'll send the new statistics to the jquery code
$query = mysql_query("SELECT FROM `staff` WHERE `id`='$userID'")or die(mysql_error());
$results = mysql_fetch_assoc($query);
echo json_encode($results);
}
I hope this is what you meant :)

load a php query file in an html index page using ajax or jquery

index.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title></title>
<link rel="stylesheet" type="text/css" href="my.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".search_button").click(function() {
// getting the value that user typed
var searchString = $("#search_box").val();
// forming the queryString
var data = 'search='+ searchString;
// if searchString is not empty
if(searchString) {
// ajax call
$.ajax({
type: "POST",
url: "query.php",
data: data,
beforeSend: function(html) { // this happens before actual
$("#results").html('');
$("#searchresults").show();
$(".word").html(searchString);
},
success: function(html)
{ // this happens after we get results
$("#results").show();
$("#results").append(html);
}
});
}
return false;
});
$(document).ready(function{
$.ajax({
url: "query.php"
}).done(function(data) {
$('body').html(data);
});
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
url: "query.php",
dataType: "text",
data: dataString,
success: function (response)
{
alert(response); //alert responce from query.php
},
error:function (xhr, ajaxOptions, thrownError)
{
alert(xhr);
}
});
});
</script>
</head>
<body >
<div id="container">
<div style="margin:20px auto; text-align: center;">
<form method="post" action="query.php" >
<input type="text" name="search" id="search_box" class='search_box'/>
<input type="submit" value="Search" class="search_button" /><br />
</form>
</div>
<div>
<div id="searchresults"></div>
<ul id="results" class="update">
</ul>
</div>
</div>
</body>
</html>
query.php
<?php
$user_name = "root";
$password = "";
$database = "my_db2";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
$SQL = "SELECT * FROM user WHERE Hometown = 'Quahog'";
//searching for what was entered into the search box
if (isset($_POST['search']))
{
$search_term = mysql_real_escape_string($_POST['search']);
//concatenating the $SQL variable above
$SQL .= "AND id = '{$search_term}'";
$SQL .= "OR Hometown = 'Quahog' AND FirstName = '{$search_term}'";
$SQL .= "OR Hometown = 'Quahog' AND LastName = '{$search_term}'";
$SQL .= "OR Hometown = 'Quahog' AND Age = '{$search_term}'";
$SQL .= "OR Hometown = 'Quahog' AND Job = '{$search_term}'";
}
$result = mysql_query($SQL) or die(mysql_error());
?>
<html>
</head>
<body>
<h1> Persons</h1>
<table border = "1" width = "100%" cellpadding = "5" cellspacing = "2">
<tr>
<td><strong>ID</strong></td>
<td><strong>First Name</strong></td>
<td><strong>Last Name</strong></td>
<td><strong>Age</strong></td>
<td><strong>Hometown</strong></td>
<td><strong>Job</strong></td>
</tr>
<?php
while ($row = mysql_fetch_array($result)) {
?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['FirstName']; ?></td>
<td><?php echo $row['LastName']; ?></td>
<td><?php echo $row['Age']; ?></td>
<td><?php echo $row['Hometown']; ?></td>
<td><?php echo $row['Job']; ?></td>
</tr>
<?php } ?>
</table>
</body>
</html>
I am new to javascript, jquery and ajax and I would like some help on modifying the above code so that when the page loads, I can view the results of a php/mysql query named 'query.php' into the index file of my html page.
Any help will be greatly appreciated.
$(document).ready(function() {
jQuery.ajax({
type: "POST", // this is post request u can also do get request
url: "query.php",
dataType: "text",
success: function (response) // this is the response from url: "query.php",
{
alert(response); //alert responce from query.php and here you can do
// whatever u like with response.
},
error:function (xhr, ajaxOptions, thrownError)
{
alert(xhr); // if any error function.
}
});
});
Use AJAX in yout index.html like this:
$(document).ready(function{
$.ajax({
url: "query.php"
}).done(function(data) {
$('body').html(data);
});
});
More info on AJAX.
Make sure that you have included jQuery in your code.

Ajax call with javascript not working

I want to try to get some value from page cart.php from and ajax call, but its not working.
Ajax code is below:
function temp_sell(id) {
//var p_id=document.getElementById('temp').value;
alert(p_id);
$.ajax({
type: "POST",
url: "temp_sell.php",
data: "value=" + p_id,
success: function (message) {
alert(message);
$("#your_cart").html(message);
}
});
}
temp_sell.php is below where I want to show some products details
<?php
include("connection.php");
echo $p_id = $_POST['value'];
$qty=1;
$query="SELECT * FROM product WHERE id='$p_id'";
$result=mysql_query($query);
while($data=mysql_fetch_array($result))
{
?>
<form>
<table>
<tr>
<img src="<?php echo "img/".$data['image'];?>"/>
<strong><?php echo $data['pro_name'];?></strong>
<strong><?php echo $data['price'];?></strong>
<input type="text" value="<?php echo $qty;?>"/>
</tr>
</table>
</form>
<?php
}
?>
p_id is undefined, you have commented the p_id value or change temp_sell(p_id).
function temp_sell(p_id)
instead of
function temp_sell(id)
Reference comments : Ajax call with javascript not working
Do this :
function temp_sell(id){
var p_id=document.getElementById('temp').value; // <--- uncomment this line
alert(p_id);
$.ajax({
type: "POST",
url: "temp_sell.php",
data: {value:p_id}, // <--- change this
success: function(message){
alert(message);
$("#your_cart").html(message);
}
});
}

Categories