Using AJAX to send form information to another page using a button - javascript

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

Related

How to fetch data from MYSQL with AJAX from PHP

i want to call my array data from database using ajax. but i don't know the way. im confused in ajax call to show it into text field. how to get array data from my sql query
this the index.php looks like..
<body>
<div class="container" >
<h2>View data</h2>
<h4>Word List : </h4>
<div class="form-group">
<input id="wordlist" type="text" class="form-control" name="wordlist">
</div><br>
<button id="display" title="Generate Word">Generate</button>
<div class="input-single">
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#display").click(function() {
$.ajax({
type: "POST",
url: "getword.php",
dataType: "json",
cache: false,
success: function(result){
$('#wordlist').html(result[0]);
}
});
});
});
</script>
</body>
and then this is the url getword.php looks like
<?php
$host = "localhost";
$user = "root";
$password = "";
$dbname = "wordlist";
$con = mysqli_connect($host, $user, $password, $dbname);
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "select kata from word";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
$result[]= $row[0];
}
echo json_encode(array('kata'=>$result));
mysqli_close($con);
?>
id="wordlist" is an input, what you passing back from the API is a object
{
kata: [...]
}
So $('#wordlist').html(result[0]); wont work, your need to use $('#wordlist').val(result.kata[0]); (note: val not html) for first item, else it will join the values word1,word2,word3 etc
If your intention is not to place all words in a single input then you should change it so it loops over result.kata and creates an input for each word etc
I would like to suggest you to debug your code by yourself using following steps :
1.You can check what response you are getting from server side by printing your ajax response data at console to print this use below code.
success: function(result){
console.log(result);
// $('#wordlist').html(result[0]);
}
This will print that you are receiving data from server side.
2.Another point is you are handling the response inside an input field if want to print fetch data inside input field then you have to replace $('#wordlist').html(result[0]); from $('#wordlist').val(result[0]); this line from your JavaScript code because it is an input field.

Jquery/Ajax to get database using php

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

Ajax request : get text from database and display in div

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

Returning a value from server to html for manipulation

I want to manipulate the value that it is stored in this variable $result[]. Specifically i want to return that value from php file to my html file. What should i do? Can you give me some reference code when i want to return things from server side to client side for further manipulation?
My php file:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("127.0.0.1", "root", "", "mysql3");
// Check connection
if($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$user_id =$_POST['user_id'];
$book_id =$_POST['book_id'];
$game_id =$_POST['game_id'];
$site_id =$_POST['site_id'];
//Attempt insert query execution
$query = "SELECT site_id FROM components WHERE user_id='$user_id' && book_id='$book_id' && game_id='$game_id' ORDER BY site_id DESC LIMIT 1";
$res = mysqli_query($link,$query);
$result = array();
$res = mysqli_query($link,$query) or die(mysqli_error($link));
while($row = mysqli_fetch_assoc($res)){
$result[]=$row['site_id'];
}
// Close connection
mysqli_close($link);
?>
My html file:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<script>
function load3() {
var flag1 = true;
do{
var selection = window.prompt("Give the User Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection)) {
flag1=false;
}
}while(flag1!=false);
$("#user_id").val(selection)
//$("#user_id").val(prompt("Give the User Id:"))
var flag2 = true;
do{
var selection2 = window.prompt("Give the Book Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection2)) {
flag2=false;
}
}while(flag2!=false);
$("#book_id").val(selection2)
//$("#book_id").val(prompt("Give the Book Id:"))
var flag3= true;
do{
var selection3 = window.prompt("Give the Game Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection3)) {
flag3=false;
}
}while(flag3!=false);
$("#game_id").val(selection3)
//$("#game_id").val(prompt("Give the Game Id:"))
}
var fieldNameElement = document.getElementById('outPut');
if (fieldNameElement == 4)
{
window.alert("bingo!");
}
</script>
</head>
<body>
<form name="LoadGame" id="LoadGame" method="post" action="http://127.0.0.1/PHP/mine1.php" enctype="multipart/form-data">
<input type="submit" value="Load" id="load" onclick="load3()" class="button12" />
<input type="hidden" name="user_id" id="user_id">
<input type="hidden" name="book_id" id="book_id">
<input type="hidden" name="game_id" id="game_id">
<input type="hidden" name="site_id" id="site_id">
</form>
</body>
</html>
Note that this answer is making use of jQuery notation, so you will need to include a jQuery library in your application in order to make this example work:
<script src="/js/jquery.min.js" type="text/javascript"></script>
Since you have your HTML and PHP in separate files, you can use AJAX to output your HTML in an element you so desire on your HTML page.
Example of jQuery AJAX:
<script>
function submitMyForm() {
$.ajax({
type: 'POST',
url: '/your_page.php',
data: $('#yourFormId').serialize(),
success: function (html) {
//do something on success?
$('#outPut').html(html);
var bingoValue=4;
if( $('#outPut').text().indexOf(''+bingoValue) > 0){
alert('bingo!');
}
else {
alert('No!');
}
}
});
}
</script>
Note that I encapsulated the AJAX function in another function that you can choose to call onclick on a button for example.
<button id="mySubmitButton" onclick="submitMyForm();">Submit form!</button>
Step-by-step:
What we do in our AJAX function, is that we declare our data type, just like you would do with a form element. In your PHP file I noticed that you used the POST method, so that's what I incorporated in the AJAX function as well.
Next we declare our URL, which is where the data will be sent. This is the same page that your current form is sending the data to, which is your PHP page.
We then the declare our data. Now, there are different ways of doing this. I assume you are using a form currently to POST your data to your PHP page, so I thought we might as well make use of that form now that you have it anyways. What we do is that we basically serialize the data inside your form as our POST values, just like you do on a normal form submit. Another way of doing it, would be to declare individual variables as your POST variables.
Example of individual variables:
$.ajax({
type: 'POST',
url: '/your_page.php',
data: {
myVariable : data,
anotherVariable : moreData
//etc.
},
success: function (html) {
//do something on success?
$('#outPut').html(html);
}
});
A literal example of a variable to parse: myVariable : $('input#bookId').val().
The operator : in our AJAX function is basically an = in this case, so we set our variable to be equal to whatever we want. In the literal example myVariable will contain the value of an input field with the id bookId. You can do targeting by any selector you want, and you can look that up. I just used this as an example.
In the success function of the AJAX function, you can basically do something upon success. This is where you could insert the HTML that you wish to output from your PHP page into another element (a div for example). In my AJAX example, I am outputting the html from the PHP page into an element that contains the id outPut.
We also write a condition in our success function (based off comments to this answer), where we check for a specific substring value in the div element. This substring value is defined through the variable bingoValue. In my example I set that to be equal to 4, so whenever "4" exists inside the div element, it enters the condition.
Example:
<div id="outPut"></div>
If you make use of this example, then whatever HTML you structure in your PHP file, making use of the PHP values in your PHP file, will be inserted into the div element.
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("127.0.0.1", "root", "", "mysql3");
// Check connection
if($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$user_id =$_POST['user_id'];
$book_id =$_POST['book_id'];
$game_id =$_POST['game_id'];
$site_id =$_POST['site_id'];
//Attempt insert query execution
$query = "SELECT site_id FROM components WHERE user_id='$user_id' && book_id='$book_id' && game_id='$game_id' ORDER BY site_id DESC LIMIT 1";
$res = mysqli_query($link,$query);
$result = array();
$res = mysqli_query($link,$query) or die(mysqli_error($link));
while($row = mysqli_fetch_assoc($res)){
$result=$row['site_id'];
echo $result.' ';
}
// Close connection
mysqli_close($link);
?>
Your form also no longer needs an action defined as all of that is now taken care of by the AJAX function.
So change:
<form name="LoadGame" id="LoadGame" method="post" action="http://127.0.0.1/PHP/mine1.php" enctype="multipart/form-data">
to:
<form name="LoadGame" id="LoadGame" method="post" enctype="multipart/form-data">
And make sure that your button: <button id="mySubmitButton" onclick="submitMyForm();">Submit form!</button> is outside of your form tag, as buttons without a defined type attribute will have type="submit" by default inside a form tag.
If you need anything elaborated, let me know. :)
First of all: remove the script tag from your php.
Secondly: Why are you executing the sql statement two times?
To your question:
You have to send a request to your PHP script via AJAX: (Place this inside <script> tags and make sure to include jquery correctly)
$(() => {
$('form').on('submit', () => {
event.preventDefault()
$.ajax({
type: 'POST',
url: '<your-php-file>', // Modify to your requirements
dataType: 'json',
data: $('form').serialize() // Modify to your requirements
}).done(function(response){
console.log(response)
}).fail(function(){
console.log('ERROR')
})
})
})
Your PHP-Script which needs to return JSON:
$query = "SELECT site_id FROM components WHERE user_id='$user_id' && book_id='$book_id' && game_id='$game_id' ORDER BY site_id DESC LIMIT 1";
// Execute Query
$res = mysqli_query($link,$query) or die(mysqli_error($link));
// Get Rows
while($row = mysqli_fetch_assoc($res)){
$result[] = $row['site_id'];
}
// Return JSON to AJAX
echo json_encode($result);
Take a look at your developer console.
Haven't tested it.

ajax -- add comments asynchronously

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)".

Categories

Resources