get results from database based on a selectfield - javascript

I have been trying to make to make a page where i could select a customer and would get the corresponding customer details from a database.
It should look something like this:
<select id="select_customer">
<option value='1'>customer 1</option>
<option value='1'>customer 2</option>
</select>
public function getCustomerDetails($customerId) {
if(isset($customerId)) {
$customer = DB::getInstance()->query("select * from customers");
foreach($customer->results() as $customer) {
$str = "<li>{$customer->name}</li>";
$str .= "<li>{$customer->name_contactperson}</li>";
$str .= "<li>{$customer->email}</li>";
$str .= "<li>{$customer->address} {$customer->house_number}</li>";
$str .= "<li>{$customer->postalcode}</li>";
$str .= "<li>{$customer->city}</li>";
$str .= "<li>{$customer->country}</li>";
}
return $str;
}
return false;
}
What i now would like to do is to get the value from the select_customer post this with ajax to the getCustomerDetails method and get the corresponding details without a page reload.
I tried to make it work with ajax and with xAjax but i coulden't get it to work.
I tried this:
<?php include 'xajaxAIO.inc.php';
$xajax = new xajax();
$xajax->register(XAJAX_FUNCTION, 'getCustomers');
$xajax->processRequest(); ?>
<input type="button" onclick="xajax_getCustomerDetails(1);" value="Click Me" />
The other thing i tried was this:
<script>
document.getElementById('select_customer').addEventListener('change', function() {
var $userId = this.value;
$.ajax({
type: "POST",
url: "classes/invoice.php",
data: "getCustomerDetails("+$userId+")"
})
});
</script>
I dont get any error messages in my console but it seems like the requested function doesnt execute.
Anybody who could tell me how it could get this to work?
Thanks in advance!

I would recommend just sending $userId alone then call getCustomerDetails($userId) in the invoice.php page.
$.ajax({
type: "GET",
url: "classes/invoice.php",
data: $userId
})
});
OR
$.ajax({
type: "GET",
url: "classes/invoice.php&function=getCustomerDetails&userId="+$userId
dataType: "json", //Dont need this if youre returning a string
success: function(result) {
alert(result);
}
})
});
Then in the invoice page you could call the function using the $_GET variable like so:
$response = 'error;
if($_GET['function'] == 'getCustomerDetails'){
if(!empty($_GET['userId'])){
$_GET['userId'] = 0;
}
$userID = $_GET['userId'];
$response = getCustomerDetails($userID);
}
die(json_encode($response)); //for array
die($response); //for a string

If you use xajax framework... you need register the new function...
<?php include 'xajaxAIO.inc.php';
$xajax = new xajax();
$xajax->register(XAJAX_FUNCTION, 'getCustomers');
$xajax->register(XAJAX_FUNCTION, 'getCustomerDetails');
$xajax->processRequest(); ?>
<input type="button" onclick="xajax_getCustomerDetails(1);" value="Click Me" />
<?php function getCustomerDetails($id){
///////////////////////////////////////////////
///// And use framework xajax to response /////
///////////////////////////////////////////////
}?>

Related

I cannot figure out why my ajax is not sending the data to my php file

I'm having a problem with my Ajax. It seems to not be sending the data to my php file even though it worked properly 2 days ago. HTML:
<form id='comment' action='process.php' method="POST">
<textarea></textarea>
<button type='submit'>Comment</button>
</form>
My ajax code:
$('#comment').submit(function(event) {
var form = $(this);
var method = form.attr('method');
var url = form.attr('action');
info = {
comment: $('textarea').val()
};
console.log(method);
console.log(url);
console.log(info);
$.ajax({
type: method,
url: url,
data: info,
success: function(data){
alert(data);
}
});
event.preventDefault();
});
I'm doing this for a friend and I'm using this exact same Ajax code (slightly modified) on my website and it's working flawlessly.
I think the biggest red flag here is that in my php file I have an if-else that should send an alert in case the textarea is empty but for some reason it's not doing that here even though nothing is getting through. I used console.log on all the variables to see if their values are correct and they are. The alert(data) just returns an empty alert box.
EDIT: As requested, PHP code from process.php
<?php
session_start();
include_once 'db_connection.php';
date_default_timezone_set('Europe/Zagreb');
if(isset($_POST['comment'])){
function SQLInsert($id, $date, $komentar, $conn){
$sql = "INSERT INTO comments (user, date, comment) VALUES ('$id', '$date',
'$comment')";
$conn -> query($sql);
$conn -> close();
}
$id = $_SESSION['username'];
$date = date('Y-m-d H:i:s');
$comment = htmlspecialchars($_POST['comment']);
SQLInsert($id, $date, $komentar, $conn);
} else {
echo '<script>';
echo 'alert("Comment box is empty.");';
echo '</script>';
}
?>
EDIT: Problem solved, thanks for the help everyone.
You are no getting alert because you are no displaying anything as response in php file. Add the insert function out side the if condition too
function SQLInsert($id, $date, $komentar, $conn){
$sql = "INSERT INTO comments (user, date, comment) VALUES ('$id', '$date',
'$comment')";
if($conn -> query($sql)){
return true;
}else{
return false;
}
$conn -> close();
}
if(isset($_POST['comment'])){
$id = $_SESSION['username'];
$date = date('Y-m-d H:i:s');
$comment = htmlspecialchars($_POST['comment']);
$insert = SQLInsert($id, $date, $komentar, $conn);
//On based on insert display the response. After that you will get alert message in ajax
if($insert){
echo 'insert sucess';
die;
}else{
echo 'Error Message';
die;
}
}
<form id='comment' action='process.php' method="POST">
<textarea></textarea>
<button id="submit_button">Comment</button>
</form>
starting from this html you have to trigger your function as:
$("#submit_button").click(function(e){
I have added an id to your button for simplicity and removed the type because it is useless in this case.
If you want to catch the submit event of the form you have to change your html as:
<form id='comment' action='process.php' method="POST">
<textarea></textarea>
<input type='submit'>Comment</button>
</form>
and then you can keep the same javascript
This here is the issue. Have you tried providing a "method" ?
$.ajax({
**type: method,**
method : method,
url: url,
data: info,
success: function(data){
alert(data);
}
});
Also if this doesn't solve it. show me the console output
<form name="fileInfoForm" id='comment' method="post" enctype="multipart/form-data">
<textarea id="textarea"></textarea>
<button type="submit"></button>
</form>
<script type="text/javascript">
$('#comment').submit(function (e) {
e.preventDefault();
var textarea=$('#textarea').val();
var form=document.getElementById('comment');
var fd=new FormData(form);
fd.append('textarea',textarea);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: 'action.php',
data: fd,
dataType: "json",
processData: false,
contentType: false,
cache: false,
success: function (data) {
alert(data);
}
})
});
</script>
in action.php
$textarea= $_POST['textarea'];
echo $textarea;

Ajax Post and retrieve multiple variables

I need help on how to post and retrieve multiple variables using Ajax Post. I actually needed to retrieve the posted variables for SQL query. See below the Ajax Code where i needed to include variable names selschool, selprogram, selsession to the post
<script>
$("#session").change(function()
{
$("#loding2").show();
var id=$(this).val();
var dataString = 'id='+ id;
var selschool=document.getElementById("selectedschool").val();
var selprogram=document.getElementById("selectedprogram").val();
var selsession=document.getElementById("selectedsession").val();
$("#semester").find('option').remove();
$("#class").find('option').remove();
document.getElementById("selectedclass").value= " ";
document.getElementById("selectedsemester").value= " ";
$.ajax
({
type: "POST",
url: "get_class.php",
data: dataString,
cache: false,
success: function(html)
{
$("#loding2").hide();
$("#class").html(html);
}
});
});
</script>
Also see below PHP script where i wanted to use the posted variable for the query;
<?php
include('dbconfig.php');
if($_POST['id'])
{
$id=$_POST['id'];
// Todo: I actually needed something like where session SELECT * FROM class where session_id=$id and program_id="selprogram" and school_id="selschool"
$stmt = $DB_con->prepare("SELECT * FROM class where session_id=$id ");
$stmt->execute(array(':id' => $id));
?><option selected="selected">Select Class :</option>
<?php while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<option value="<?php echo $row['class_id']; ?>"><?php echo $row['class_name']; ?></option>
<?php
}
}
?>
Let me explain the solution
consider the ajax call to demo.php
$.ajax({
url: 'demo.php',
type: 'post',
data: {
'name': 'abc',
'phone': '1234567899'
}, //data is in json form
success: function(res) {
console.log(JSON.parse(res)); //parsing because we will pass the data from demo.php in encoded form you will get it.
}
});
now in demo.php you will access data as $_POST['name'] and $_POST['phone']. lets pass the same to ajax call. will store it in array and will pass it.
<?php
$Arr = [];
$Arr[0] = $_POST['name'];
$Arr[1] = $_POST['phone'];
echo json_encode($Arr);
?>
like this, we can pass data to ajax and can pass the data from PHP file to request.
Hope that you got the result. Thank you.

AJAX POST not working, php doesn't create session

I want to send id of element to php and create session for this.
This is piece from php file:
<?php
$sql = "SELECT id FROM products";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
?>
<tr class="table-manufacture-tr">
<td class="table-manufacture-td-statys">
<div class="warehouse-window-content-dropdown-plus2 plus">
<a class="open_item" data-id=<?php echo "\"".$row['p_id']."\"";?>
style="text-decoration: none; color: #D3D3D3;">Click</a>
</div>
</td>
</tr>
<?php
}
?>
And in this file javascript code:
$(document).on('click', '.open_item', function(event){
var data_item = this.getAttribute("data-id");
$.ajax({
url: 'get_id.php',
type: 'POST',
data-type: 'json',
data: { id: data_item },
contentType: 'application/x-www-form-urlencoded',
success: function(data){
console.log(data);
},
error: function(){
console.log("not working");
}
});
});
This is get_id.php:
<?php
session_start();
$_SESSION['item_id'] = json_encode($_POST);
header("Content-Type: application/json", true);
?>
I have tried also without content types and without json. "var data_item" prints id correct, but php doesn't create session and in console also clear(nothing).
The reason that you are not getting data in session is, you are not assigning proper value to session. Also it should be json_decode not json_encode.
replace
$_SESSION['item_id'] = json_encode($_POST);
with
if (!empty($_POST['id'])) {
$_SESSION['item_id'] = json_decode($_POST['id']); // use json_decode
}
It seems to me that you are making some small mistake in your code like you are echoing $row['p_id'] while your query should return id instead p_id also you are making mistake in ajax you are sending data-type JavaScript assuming your code is subtracting so try to use this code i code below.
// modify your php code
<?php
$sql = "SELECT id FROM products";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($result)) { ?>
<tr class="table-manufacture-tr">
<td class="table-manufacture-td-statys">
<div class="warehouse-window-content-dropdown-plus2 plus">
<a class="open_item" data-id=<?php echo "\"".$row['id']."\"";?>
style="text-decoration: none; color: #D3D3D3;">Click</a>
</div>
</td>
</tr>
<?php } ?>
// modify your jQuery
$(document).on('click', '.open_item', function(event){
var data_item = $(this).data("id");
$.ajax({
url: 'get_id.php',
type: 'POST',
dataType: 'json',
data: { id: data_item },
success: function(data){
console.log(data);
},
error: function(){
console.log("not working");
}
});
});
<?php
session_start();
header("Content-Type: application/json", true);
$_SESSION['item_id'] = json_encode($_POST["id"]);
echo json_encode(['data_id' => $_SESSION['item_id']]);
?>
You can use
$_SESSION['item_id'] = json_encode($_POST['id']);
instead of
$_SESSION['item_id'] = json_encode($_POST);
this will work fine.
I don't know what you are trying to do, but from your JS, it looks like that you are expecting that the PHP script --which you post some data to it-- to return a json with the data you have just posted in it. In that case, try this, change your get_id.php to be like:
<?php
session_start();
$_SESSION['item_id'] = json_encode($_POST);
header("Content-Type: application/json", true);
echo $_SESSION['item_id'];
?>
I'd troubleshoot this by making sure the click handler is actually going off. Put alert("clicked"); as the first thing in the in the click handler to make sure.
For the meantime, remove the contentType in the json call. Also remove the dataType (data-type) entirely. On the php side, replace the header() line so (as mentioned) the php is just:
session_start();
$_SESSION['item_id'] = $_POST["id"];
echo $_SESSION['item_id'];
Do not use json_encode/decode right now. From your code, it is not needed.

Accessing JSON returned by php script using jquery ajax

Basically my program is a web page with 5 radio buttons to select from. I want my web app to be able to change the picture below the buttons every time a different button is selected.
My problem is coming in the JSON decoding stage after receiving the JSON back from my php scrip that accesses the data in mysql.
Here is my code for my ajax.js file:
$('#selection').change(function() {
var selected_value = $("input[name='kobegreat']:checked").val();
$.ajax( {
url: "kobegreat.php",
data: {"name": selected_value},
type: "GET",
dataType: "json",
success: function(json) {
var $imgEl = $("img");
if( $imgEl.length === 0) {
$imgEl = $(document.createElement("img"));
$imgEl.insertAfter('h3');
$imgEl.attr("width", "300px");
$imgEl.attr("alt", "kobepic");
}
var link = json.link + ".jpg";
$imgEl.attr('src', link);
alert("AJAX was a success");
},
cache: false
});
});
And my php file:
<?php
$db_user = 'test';
$db_pass = 'test1';
if($_SERVER['REQUEST_METHOD'] == "GET") {
$value = filter_input(INPUT_GET, "name");
}
try {
$conn = new PDO('mysql: host=localhost; dbname=kobe', $db_user, $db_pass);
$conn->setAttribute(PDO:: ATTR_ERRMODE, PDO:: ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT * FROM greatshots WHERE name = :name');
do_search($stmt, $value);
} catch (PDOException $e) {
echo 'ERROR', $e->getMessage();
}
function do_search ($stmt, $name) {
$stmt->execute(['name'=>$name]);
if($row = $stmt->fetch()) {
$return = $row;
echo json_encode($return);
} else {
echo '<p>No match found</p>;
}
}
?>
Here's my HTML code where I am trying to post the image to.
<h2>Select a Great Kobe Moment.</h2>
<form id="selection" method="get">
<input type="radio" name="kobegreat" value="kobe1" checked/>Kobe1
<input type="radio" name="kobegreat" value="kobe2"/>Kobe2
<input type="radio" name="kobegreat" value="kobe3"/>Kobe3
</form>
<div id="target">
<h3>Great Kobe Moment!</h3>
</div>
And here's is what my database looks like:
greatshots(name, link)
name link
------ --------
kobe1 images/kobe1
kobe2 images/kobe2
kobe3 images/kobe3
Whenever I run the web app right now, the rest of the images on the page disappear and the image I am trying to display won't show up. I get the alert that "AJAX was a success" though, but nothing comes of it other than the alert. Not sure where I am going wrong with this and any help would be awesome.
As mentioned you should parse the JSON response using JSON.parse(json);.
Also, you should specifically target the div element with a simpler setup:
$("#target").append('<img width="300px" src="' + link + '.png"/>');

PHP Ajax not creating post variable

A while ago i made a search function with ajax and php. You could fill in a textbox with text and it would try to find a match among all countries stored in the database.
Now i am refining the code and making it PDO, but i broke something and i cant find out what.
this is my plain HTML
<head>
<title>Ajax</title>
<link href="style/style.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="scripts/Javascript.js"></script>
</head>
<body>
<div id="main">
<h1 class="title">Enter your country please</h1>
<input type="text" id="search" autocomplete="off" onchange="">
<h4 id="results-text">Showing results for: <b id="search-string">Array</b></h4>
<ul id="results"></ul>
</div>
</body>
here is my Jquery and javascript. note i have not changed anything to the HTML nor javascript so it can not by a type error.
$(document).ready(function() {
alert('asdf');
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}
return false;
}
$("input#search").live("keyup", function(e) {
clearTimeout($.data(this, 'timer'));
var search_string = $(this).val();
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}
else {
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
});
And here is my Search.PHP
<?php
class SearchEngine{
private $html;
public function __construct($conn){
$this->html = '<li class="result">
<h3>NameReplace</h3>
<a target="_blank" href="ULRReplace"></a>
</li>';
if (isset($_POST["query"])) {
$search_string = $_POST['query'];
}
else{
$search_string = '';
echo('Something went wrong, post query not set');
}
//$search_string = mysql_real_escape_string($search_string);
if (strlen($search_string) >= 1 && $search_string !== ' ') {
$query = 'SELECT * FROM country WHERE name LIKE "%' . $search_string . '%"';
$result = $conn->prepare($query);
$result->execute();
$result_array = $result->fetchAll();
foreach ($result_array as $result) {
$display_name = preg_replace("/" . $search_string . "/i", "<b>" . $search_string . "</b>", $result['name']);
$display_url = 'sadf';
$output = str_replace('NameReplace', $display_name, $this->html);
$output = str_replace('ULRReplace', $display_url, $output);
echo($output);
}
}
}
}
?>
The problem:
the Post query is never created, for this i made a isset so for now when there is no Post Query created. It will create a Post Query with value "B".
Any help will be much appreciated. Please be gentle i am new to Ajax and i rather want to understand than have the solution. Thank you
You're not point the right URL! Look:
You have pointed your ajax request to search.php :
$.ajax({
type: "POST",
url: "search.php",
But you have just a class in search.php. A class don't do anything by itself. You have to Instantiate and call its methods/functions. Please compare these 2 pieces of code:
<?php
//server.php
//Doing nothing
class SearchEngine{
private $html;
public function __construct($conn){
echo "I'm executing";
}
}
?>
let's say you have this in server.php
<?php
//server.php
//It will print "I'm executing" in the screen
class SearchEngine{
private $html;
public function __construct($conn){
echo "I'm executing";
}
}
$search = new SearchEngine($conn);
?>
To solve your original problem You have to to point your ajax to the page having the INSTANTIATION code, not the class, like this:
//index.php
//Let's suppose you have this code in your index.php
$SearchEngine = new SearchEngine($conn);
So your JQuery ajax code should looks like that:
$.ajax({
type: "POST",
url: "index.php",
As Mentioned by Sean, in the comments, the $.live jquery method is deprecated in your version of jQuery.
Try utilizing $.keyup instead
$("input#search").keyup(function() {
// stuff
});

Categories

Resources