My goal is to perform an AJAX request when clicking on a button to retrieve "name" and "story" stored in my database. Each button will get info of another hero.
I'm working on multiple files.
With my current code (which is the closer to what seems to be correct in my mind) the switchHeroInfo will always change the text to "TestName" and "StoryName" instead of "Gertrude" "An old lady"(stored in database).
Can you enlight me on what may be the cause of my struggles?
the php file for connecting to database : connect_database.php
<?php
try
{
$bdd = new PDO('mysql:host=localhost;dbname=biomass;charset=utf8', 'root', '', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}
catch(Exception $e)
{
die('Error : '.$e->getMessage());
}
?>
The Javascript part :
$(document).ready(function()
{
$(".hero_portrait").click(function()
{
var index = $(this).data("id");
$.ajax(
{
type: "POST",
url: "../php/get_data.php",
data: {newIndex:index},
success: function(data)
{
// Display {"nick":"Gertrude","0":"Gertrude","story":"Vieille folle senile","1":"Vieille folle senile"}
alert(data);
//Display : undefined
alert(data.story);
$("#hero_name").html(data.nick);
$("#hero_story").html(data.story);
},
error: function()
{
alert("Request failure");
}
});
});
});
The php file : get_data.php
<?php
$tempValue = $_POST['newIndex'];
$sql = $bdd->prepare('SELECT * FROM heroes WHERE ID = :indexValue');
$sql->bindParam(":indexValue", $tempValue, PDO::PARAM_STR);
$sql->execute();
while($data = $sql->fetch())
{
?>
<script>
$heroNameTemp = <?php echo json_encode($data["name"]); ?>;
$heroStoryTemp = <?php echo json_encode($data["story"]); ?>;
</script>
<?php
}
$sql->closeCursor();
?>
Finally the HTML relative to the current problem:
<div id="squad_portraits">
<div class="hero_portrait" id="1"></div>
<div class="hero_portrait" id="2"></div>
<div class="hero_portrait" id="3"></div>
<div class="hero_portrait" id="4"></div>
</div>
<div id="hero_info">
<h2 id="hero_name">Hero_Name</h2>
<p id="hero_story"> Hero_Description</p>
</div>
If i switch my sql request :
$tempValue = $_POST['newIndex'];
$sql = $bdd->prepare('SELECT * FROM heroes WHERE ID = :indexValue');
to this
$tempValue = 4;
$sql = $bdd->prepare('SELECT * FROM heroes WHERE ID = 4');
AND add the following to my HTML file
<?php include("../php/get_data.php"); ?>
everything works but my index will always be "4".
There are several issues and missunderstandings in your code.
first, in ajax change data to this:
data: {newIndex:index}, // remove the (), simple syntax misstake
This should solve the sql problem.
Now the get_data.php:
<?php
// including db connection is missing here for $bdd
// You should add a test here, wether you've received any and correct data in 'newIndex'
if(empty($_POST['newIndex']) {
// throw an error, send that back to ajax (with a fitting http response code) and exit script
http_response_code(400);
$error = new stdClass();
$error->msg = "Parameter newIndex was missing";
header('Content-Type: application/json'); // tell the browser that there is some json coming!
echo json_encode($error);
exit;
}
$tempValue = $_POST['newIndex'];
// only select the values you need (name, story)
$sql = $bdd->prepare('SELECT name, story FROM heroes WHERE ID = :indexValue');
$sql->bindParam(":indexValue", $tempValue, PDO::PARAM_STR);
$sql->execute();
$data = $sql->fetch(); // if you only expect/need one row, no while is needed
// echo ONE json string as plain string:
header('Content-Type: application/json'); // tell the browser that there is some json coming!
echo json_encode($data);
Now you receive content of $data as a json as param (data) in the success-callback of your ajax, which you can use like this:
success: function(data){
$("#hero_name").html(data.name);
$("#hero_story").html(data.story);
}
Finally let's change storing the item's id from the id attribute to the data-attribute:
In html:
<div class="hero_portrait" data-id="1"></div>
<div class="hero_portrait" data-id="2"></div>
and in javascript change
var index = $(this).attr("id");
to
var index = $(this).data("id"); // $(this).attr("data-id"); will also work
Related
I have a list of divs with unique IDs (they are inserted from my database). When I click on one of them I want to display content from my database in another div. For example, I have a div with class pizza. The query should look like this: SELECT * FROM product WHERE name = 'pizza'. So depending on what div you click you get different content. The code below doesn't work and is incomplete. I was trying to do some research myself, but I couldn't find anything useful.
//head
<script>
$(function () {
$('.product').on('click', function (e) {
e.preventDefault();
$.ajax({
type: "post",
url: 'php/recipe-container.php',
data: new FormData(this),
processData: false,
contentType: false,
success: function(response) {
$(".display_recipe").html(response);
},
error: function () {
}
});
});
});
</script>
//HTML
<div class="product" id="pizza">pizza</div>
<div class="product" id="lasagna">lasagna</div>
<div class="product" id="sushi">sushi</div>
<div class="display_recipe"></div>
// PHP (recipe-container.php)
<?php
function display_recipe(){
$con = mysqli_connect("localhost", "root", "", "cookbook");
$product = "'pizza'"; //just a placeholder
$sql = "SELECT * FROM product WHERE name = $product";
$res = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($res)) {
$name = $row['name'];
$description = $row['description'];
$date = $row['date'];
echo $name;
echo "<br>";
echo $description;
echo "<br>";
echo $date;
echo "<br>";
}
mysqli_close($con);
}
display_recipe();
?>
Right now when I click the button nothing happens, even "pizza" placeholder doesn't work. Is there a simple way to do it?
JS file (AJAX code)
You can get the id attribute on click of the div with the class 'product' as coded below:
jQuery(function () {
jQuery('.product').on('click', function (e) {
var product = jQuery(this).attr('id');
$.ajax({
type: "post",
url: 'php/recipe-container.php',
data: {data:product},
processData: false,
contentType: false,
success: function(response) {
$(".display_recipe").html(response);
}
});
});
});
PHP file: get the posted data in this file use it in a query to fetch the result and return the result to the AJAX success handler as a response.
To fetch the data posted from the ajax in this php file you can use $_POST['data'] as stated below:
$product = $_POST['data'];
Use that variable in your sql query to fetch the result and then change the structure of your response as stated below:
//saving the html response in a variable named "response"
$response = $name.'<br>';
$response .= $description.'<br>';
$response .= $date.'<br>';
//echo response will send the response variable back to the AJAX success handler.
echo $response;
I ideally want the Ajax result to be converted from Jsonstring to OBJ Thank You in advance.
I know the AJAX GET script is working becuase when I alert the Ajax Post result I see the Contents in json string format as below.
alert(JSON.stringify(data));
[{"id":"1","username":"jiten","name":"Jitensingh\t","email":"jiten93mail”},{“id":"2","username":"kuldeep","name":"Kuldeep","email":"kuldeemail”}]
I want the AJAX GET result data converted to look like this in OBJ format like below.
{id:31,name:"Mary",username:"R8344",email:"wemail}];
PHP/SQL CODE with the Json encoded Array
<?php
include "../mytest/config.php";
$return_arr = array();
$sql = "SELECT * FROM users ORDER BY NAME";
$result = $conn->query($sql);
//Check database connection first
if ($conn->query($sql) === FALSE) {
echo 'database connection failed';
die();
} else {
while($row = $result->fetch_array()) {
$id = $row['id'];
$username = $row['username'];
$name = $row['name'];
$email = $row['email'];
$return_arr[] = array(
"id" => $id,
"username" => $username,
"name" => $name,
"email" => $email);
}
// Encoding array in JSON format
echo json_encode($return_arr);
}
?>
php echo _encode array above returns below Json string format
[{"id":"1","username":"jiten","name":"Jitensingh\t","email":"jiten93mail”},{“id":"2","username":"kuldeep","name":"Kuldeep","email":"kuldeemail”}]
I am looking for something like below.( top half of the script)
<script>
$(document).ready(function(){
$.ajax({
url: 'ajaxfile.php',
type: 'get',
dataType: 'JSON',
success: function(result){
var data =(JSONstring convert to OBJ(result);
//-----The top half of script -------------
$.each(data, function( i, person ) {
if(i == 0) {
$('.card').find('.person_id').text(person.id);
$('.card').find('.person_name').text(person.name);
$('.card').find('.person_username').text(person.username);
$('.card').find('.person_email').text(person.email);
} else {
var personDetailCloned = $('.card').first().clone();
personDetailCloned.find('.person_id').text(person.id);
personDetailCloned.find('.person_name').text(person.name);
personDetailCloned.find('.person_username').text(person.username);
personDetailCloned.find('.person_email').text(person.email);
$('.card-container').append(personDetailCloned);
}
});
});
</script>
I will need help with the closing tags as above is just an example
The solution is:
success: function(result){
data =(result);
There was no need o convert the data to OBJ or anything ( blush). Then the code on the 2nd half of the Ajax script will receive the data and populate. Thanks to all contributors.
I have an HTML page that is too big to post on here, however I'll just post the ajax/jquery I am using to try and access the PHP file variables.
threadPage.html
<script type="text/javascript">
$.ajax({
url : '/ThreadCreation.php',
type : 'POST',
data: {'titles': titles}
crossDomain: true,
dataType : 'jsonp',
success : function (data) {
console.log(data) /
},
error : function () {
alert("error");
}
})
</script>
<!-- bunch of html -->
So essentially I am trying to get the variable from the ThreadCreation.php in JSON form. It should be in an array so that I can loop through it in the HTML file.
ThreadCreation.php
<?php
$username = 'root';
$password = '';
$db = 'main_database';
$conn = mysqli_connect('localhost', $username , $password,$db);
if (!$conn){
die("unable to connect");
}
$sql = mysqli_query($conn, "SELECT title FROM thread");
while($row = mysqli_fetch_array($sql)) {
$titles[] = $row['title'];
echo json_encode($titles);
?>
I will repeat though, that this HTML file is only getting information from the database through PHP. So there is no form submission here.
I keep getting that 'titles is not defined'. This makes sense because there is not titles defined in the HTML, however I am unsure how to construct my ajax request to collect the data, as this format is all I have seen people use.
Mention empty array first just to prevent error in case you have no data
in database then empty array will proceed.
$sql = mysqli_query($conn, "SELECT title FROM thread");
$titles = array();
while ($row = mysqli_fetch_array($sql)) {
array_push($titles,$row['title']); // Push data in empty array
}
echo json_encode($titles);
I have two php files that handle a commenting system I have created for my website. On the index.php I have my form and an echo statement that prints out the user input from my database. I have another file called insert.php that actually takes in the user input and inserts that into my database before it is printed out.
My index.php basically looks like this
<form id="comment_form" action="insertCSAir.php" method="GET">
Comments:
<input type="text" class="text_cmt" name="field1_name" id="field1_name"/>
<input type="submit" name="submit" value="submit"/>
<input type='hidden' name='parent_id' id='parent_id' value='0'/>
</form>
<!--connects to database and queries to print out on site-->
<?php
$link = mysqli_connect('localhost', 'name', '', 'comment_schema');
$query="SELECT COMMENTS FROM csAirComment";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="comment" >';
$output= $row["COMMENTS"];
//protects against cross site scripting
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8');
echo '</div>';
}
?>
I want users to be able to write comments and have it updated without reloading the page (which is why I will be using AJAX). This is the code I have added to the head tag
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
// this is the id of the form
$("#comment_form").submit(function(e) {
var url = "insert.php"; // the script where you handle the form input.
$.ajax({
type: "GET",
url: url,
data: $("#comment_form").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
</script>
However, nothing is happening. The alert() doesn't actually do anything and I'm not exactly sure how to make it so that when the user comments, it gets added to my comments in order (it should be appending down the page). I think that the code I added is the basic of what needs to happen, but not even the alert is working. Any suggestions would be appreciated.
This is basically insert.php
if(!empty($_GET["field1_name"])) {
//protects against SQL injection
$field1_name = mysqli_real_escape_string($link, $_GET["field1_name"]);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO parentComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
header("Location:index.php");
die();
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
it also filters out bad words which is why there's an if statement check for that.
<?php
if(!empty($_GET["field1_name"])) {
//protects against SQL injection
$field1_name = mysqli_real_escape_string($link, $_GET["field1_name"]);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element)
{
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0)
{
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO parentComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
if ($result)
{
http_response_code(200); //OK
//you may want to send it in json-format. its up to you
$json = [
'commment' => $newComment
];
print_r( json_encode($json) );
exit();
}
//header("Location:chess.php"); don't know why you would do that in an ajax-accessed file
//die();
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
}
?>
<script>
// this is the id of the form
$("#comment_form").submit(function(e) {
var url = "insert.php"; // the script where you handle the form input.
$.ajax({
type: "GET", //Id recommend "post"
url: url,
dataType: json,
data: $("#comment_form").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
$('#myElement').append( data.comment );
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
</script>
To get a response from "insert.php" you actually need to print/echo the content you want to handle in the "success()" from the ajax-request.
Also you want to set the response-code to 200 to make sure "success: function(data)" will be called. Otherwise you might end up in "error: function(data)".
Hello I have two files that are supposed to be connected to one another. I want to send an AJAX request to another page that uses a sql query to send form information.
The application that I'm trying to create is a questionnaire with eight questions, each questions has four answers paired together with the same id (qid) and each answer has a value from the database. After you answer eight questions you will see a button that sends an AJAX request to the page test.php, (named submitAJAX).
The problem is that although my connection with AJAX is working, the values from the form are not being sent to my database. Previously I thought that the problem may lie with the form page, but now I I think the problem lies in this file:
test.php (file with json)
<?php
$localhost = "localhost";
$username = "root";
$password = "";
$connect = mysqli_connect($localhost, $username, $password) or die ("Kunde inte koppla");
mysqli_select_db($connect, 'wildfire');
if(count($_GET) > 0){
$answerPoint = intval($_GET['radiobtn']);
$qid = intval($_GET['qid']);
$tid = intval($_GET['tid']);
$sql2 = "INSERT INTO result (qid, points, tid) VALUES ($qid, $answerPoint, $tid)";
$connect->query($sql2);
$lastid = $connect->insert_id;
if($lastid>0) {
echo json_encode(array('status'=>1));
}
else{
echo json_encode(array('status'=>0));
}
}
?>
I think that the problem may lie in the row where: if($lastid>0) {
$lastid should always be more than 0, but whenever I check test.php I get this message: {"status":0} What's intended is that I get this message: {"status":1}
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<?php
$localhost = "localhost";
$username = "root";
$password = "";
$connect = mysqli_connect($localhost, $username, $password) or die ("Kunde inte koppla");
mysqli_select_db($connect, 'wildfire');
$qid = 1;
if(count($_POST) > 0){
$qid = intval($_POST['qid'])+1;
}
?>
<form method="post" action="">
<input type="hidden" name="qid" id="qid" value="<?=$qid?>">
<?php
$sql1 = mysqli_query($connect,"SELECT * FROM question where answer != '' && qid =".intval($qid));
while($row1=mysqli_fetch_assoc($sql1)){
?>
<input type='radio' name='answer1' class="radiobtn" value="<?php echo $row1['Point'];?>">
<input type='hidden' name='tid' class="tid" value="<?php echo $row1['tid'];?>">
<?php echo $row1['answer'];?><br>
<?php
}
?>
<?php if ($qid <= 8) { ?>
<button type="button" onclick="history.back();">Tillbaka</button>
<button type="submit">Nästa</button>
<?php } else { ?>
<button id="submitAjax" type="submit">Avsluta provet</button>
<?php } ?>
</form>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript">
function goBack() {
window.history.go(-1);
}
$(document).ready(function(){
$("#submitAjax").click(function(){
if($('.radiobtn').is(':checked')) {
var radiobtn = $('.radiobtn:checked').val();
var qid = $('#qid').val();
var answer = $('input[name=answer1]:radio').val();
$.ajax(
{
type: "GET",
url: 'test.php',
dataType: "json",
data: "radiobtn="+radiobtn+"&qid="+qid,
success: function (response) {
if(response.status == true){
alert('points added');
}
else{
alert('points not added');
}
}
});
return false;
}
});
});
</script>
</body>
The values that I want to send to my database from test.php are:
qid(int), tid(int), Point(int)
There is a database connection, and my test.php file's sql query should work, but its not sending form information. Is there something that I need to rewrite or fix to make it work?
First, your data parameter in the AJAX call is not using the correct syntax. You're missing brackets. It should look like:
data: JSON.stringify({ radiobtn: radiobtn, qid: qid }),
Second, I'd suggest using POST instead of GET:
type: "POST",
which means that you need to look for your data in $_POST['radiobtn'] and $_POST['qid'] on test.php. NOTE: you should check for the key you expect using isset() before assigning the value to a variable, like so:
$myBtn = isset($_POST['radiobtn']) ? $_POST['radiobtn'] : null;
Third, for testing, use a console.log() inside your condition that checks for the checkbox being checked in order to verify that condition is working as expected.
if($('.radiobtn').is(':checked')) {
console.log('here');
UPDATE:
Fourth: You should specify the content type in your AJAX call, like so:
contentType: "application/json; charset=utf-8",
After you execute your query that inserts the result you can use a sql statement to select the last insert id. Try something like
$sql2 = "INSERT INTO result (qid, points, tid) VALUES ($qid, $answerPoint, $tid)";
$connect->query($sql2);
$result = $connect->query("SELECT LAST_INSERT_ID()");
$row = $result->fetch_row();
$lastid = $row[0];
That should return the correct last insert id, if that was where your error was occurring.
mysqli_insert_id() returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute.
In your SQL, you are providing the ID yourself, there is no auto-increment. So you should get 0 from $connect->insert_id, because the function returns zero if there was no previous query on the connection or if the query did not update an AUTO_INCREMENT value.
For your purpose, you can use the return value of mysqli_query() instead, which returns TRUE on success and FALSE on failure.
if($connect->query($sql2)) {
echo json_encode(array('status'=>1));
}
else{
echo json_encode(array('status'=>0));
}