What is wrong with my Javascript and $POST concatenation? - javascript

I am using Ajax to add 3 values to my database, and then immediately append them at the bottom of my Table using the following:
**EDIT: Added the full code, and I currently only adding 1 value to the database, leaving the others empty (Adding only Text1)
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function() {
$("#Submit").click(function (e) {
e.preventDefault();
if($("#Text1").val()==='')
{
alert("Please enter some text!");
return false;
}
var myData = 'txt1='+ $("#Text1").val(); //build a post data structure
jQuery.ajax({
type: "POST",
url: "ajax.php",
dataType:"text",
data:myData,
success:function(response){
var row_data = "";
row_data +="<tr><td><?php echo $_POST['txt1'] ; ?></td><td><?php echo $_POST['txt1'];?></td><td><?php echo $_POST['txt1'];?></td></tr>";
$("#mytable").append(row_data);
$("#responds").append(response);
$("#Text1").val(''); //empty text field on successful
$("#FormSubmit").show(); //show submit button
$('table').html(data);
},
error:function (xhr, ajaxOptions, thrownError){
$("#FormSubmit").show(); //show submit button
alert(thrownError);
}
});
});
});
</script>
<?php
$servername = "localhost";
$username = "username";
$password = "";
$dbname = "test_database";
$mysqli = new mysqli($servername, $username, $password, $dbname);
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
echo "Connected successfully";
if(isset($_POST["txt1"]) && strlen($_POST["txt1"])>0)
{
$contentToSave = filter_var($_POST["txt1"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$insert_row = $mysqli->query("INSERT INTO test_table(fname) VALUES('".$contentToSave."')");
if($insert_row)
{
$mysqli->close(); //close db connection
}else{
header('ERROR');
exit();
}}
?>
<div class="form_style">
<textarea name="content_txt" id="Text1" cols="45" rows="1"></textarea><br>
<button id="Submit">Add record</button>
</div><br>
<table class="table" id="mytable" style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
//initially filling the table with db data
<?php
$sql = "SELECT fname, lname, age FROM test_table";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>". $row["fname"] . "</td><td>" . $row["lname"] . "</td><td>" . $row["age"] . "</td></tr>";
}
} else {
echo "0 results";
}
$mysqli->close();
?>
</table>
</body>
</html>
The posting does work: txt1, txt2 and txt3 are inserting into the database, but what I see at the bottom of the table is '.$_POST['txt1'].' and so on, instead of the actual POST data

if you want to use php code in javascript then try below ==>
success:function(response){
var row_data = "";
row_data +="<tr><td><?php echo $_POST['txt1'] ; ?></td><td><?php echo $_POST['txt2'];?></td><td><?php echo $_POST['txt3'];?></td></tr>";

The argument you named response in the declaration of the function for success setting of the ajax call (I assume you are using jQuery's $.ajax) contains whatever your Web server sent to you.
In your case if you send AJAX request to the code you provided, that is, if the code you provided is exactly that ajax.php you referenced in the url setting of the jQuery.ajax call, THEN THE response VAR WILL CONTAIN FULL HTML TEXT RENDERED, which is probably absolutely useless to you.
Proper usage of the AJAX would be like this:
$.ajax({
// ...
dataType: 'json', // I can remember incorrectly here. It assumes your PHP backend sends JSON-encoded string.
success: function (data) { // data will be an object already parsed from JSON string sent by server.
var row_data = "";
row_data += "<tr><td>";
row_data += data.txt1;
row_data += "</td><td>";
row_data += data.txt2;
row_data += "</td><td>";
row_data += data.txt3;
row_data += "</td></tr>";
}
});
Move the block of code starting with if(isset($_POST["txt1"]) && strlen($_POST["txt1"])>0) to the very beginning of the file and do the following on successful insert to the database:
header("Content-Type: application/json");
echo json_encode(['txt1' => $_POST['txt1'], 'txt2' => #$_POST['txt2'], 'txt3' => #$_POST['txt3']);
die();
This way when handler registered in success will be entered, the response will contain the proper JSON block. You don't need to re-render the whole page on AJAX requests.
You don't need the $("#responds").append(response); block because it'll lie to you due to rendering of the response contents according to HTML rendering rules. Just use the F12 in browser and inspect the server response directly.

Related

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.

html code in javascript function

Heads up before reading. I'm totally new in html and so, so please be patient. I have the following html code and two javascript functions.
<HTML> <HEAD> ..... </HEAD>
<BODY>
<CENTER>
<form id="keyForm">
Όνομα/Επώνυμο: <input type="text" name="keyword"><br><br>
<input type="button" onClick="resetFunction()" value="Επαναφορά">
<input type="button" onClick="my_search(this.form.keyword.value)" value="Αναζήτηση">
</form>
<p id="results"></p>
</CENTER>
<script>
function resetFunction() {
document.getElementById("results").innerHTML = "";
document.getElementById("keyForm").reset();
}
</script>
<script>
function my_search(kw) {
document.getElementById("results").innerHTML = (
<table border="1" style="width:500px">
<tr>
<td>ID</td>
<td>Επίθετο</td>
<td>Όνομα</td>
<td>Ημερομηνία πρόσληψης</td>
<td>Τμήμα</td>
</tr>
</table> );
}
</script>
</BODY>
</HTML>
I want the "results" to be be table that is described in function "my_search" extended by the actual results produced by the following php code.
<?php
header("content-type: text/html;charset=utf-8");
$link = mysqli_connect("127.0.0.1","root", "tralalalalala", "mycompany");
if (!$link) {
printf("Connect failed: %s\n",
mysqli_connect_error());
exit();
}
//printf("Host information: %s<br>",
//mysqli_get_host_info($link));
$key = $_POST['keyword']; //Keyword in initialized in html
//echo $key; echo "<br>";
$stmt = mysqli_prepare($link, "
select e.emp_id, e.first_name, e.last_name, e.hire_date, d.dept_name
from employee e, department d
where e.dept_id = d.dept_id and (e.first_name like ? or e.last_name like ?)");
$likeKey = "%{$key}%";
mysqli_stmt_bind_param($stmt, "ss", $likeKey, $likeKey);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $id, $f_name, $l_name, $hire_date, $d_name);
$stmt->store_result();
$rows = $stmt->num_rows;
if ($rows)
printf("Βρέθηκαν %d αποτελέσματα<br>", $rows);
else
printf("Δε βρέθηκαν αποτελέσματα για τη λέξη-κλειδί \"%s\" <br>", $key);
for ($i = 0; $i<$rows; $i++){
mysqli_stmt_fetch($stmt);
printf("%d %s %s %s %s <br>", $id, $f_name, $l_name, $hire_date, $d_name);
}
mysqli_stmt_close($stmt);
mysqli_close($link);
?>
In the end I wanna have something like this
It's Greek but I think you can handle it ;) Thank you for your replies :)
You can append a string using +=
var str;
str += '<tr>';
str += '<td>Text</td>';
str += '<tr>';
-Do not use <center>, it is deprecated
Here is more information about deprecated attributes http://www.w3.org/TR/html4/index/attributes.html
-You have to use AJAX. Here is some information about AJAX jQuery http://api.jquery.com/jquery.ajax/ and http://jquery.com/
You can try this:
$(function(){
$("form").submit(function(){
$.ajax({
url: "", //put the name of the php file
type: "post",
data: { keyword: $(".keyword").val() },
success: function(response){
//add the output from the php file to the div in the html file using
//append() or html()
}
});
});
}

Ajax, PHP Live search & show more code works separately but not together

I have a Ajax PHP Show More feature like youtube and Live search scripts but I can't get them to work together. For example my live search works but then the show more feature doesn't work with it on the search results and when I use the show more then the live search doesn't work.
They don't seem to be messing with each other. Can anyone help me out? I am new to this website so I will try my best to show my code and explain it.
INDEX.PHP
<?php
include_once("connect.php");
$sql = "SELECT COUNT(*) FROM database";
$query = mysqli_query($connect,$sql) or die (mysqli_error());
$item_per_page = 3;
$total_rows = mysqli_fetch_array($query);
$pages = ceil($total_rows[0]/$item_per_page);
?>
<!DOCTYPE html>
<head>
<script type="text/javascript">
// Show More Scripted
$(document).ready(function() {
var track_click = 0;
var total_pages = <?php echo $pages; ?>;
$('#news-table-wrap').load("showmore_search.php", {'page':track_click}, function() {track_click++;});
$(".load_more").click(function (e){
$(this).hide();
$('.animation_image').show();
if(track_click <= total_pages){
$.post(showmore_search.php',{'page': track_click}, function(data) {
$(".load_more").show();
$("#news-table-wrap").append(data);
$("html, body").animate({scrollTop: $("#load_more_button").offset().top}, 500);
$('.animation_image').hide();
track_click++;
}).fail(function(xhr, ajaxOptions, thrownError){
alert(thrownError);
$(".load_more").show();
$('.animation_image').hide();
});
if(track_click >= total_pages-1){
$(".load_more").attr("disabled", "disabled");
}
}
});
});
// Live Search Script
function searchNews(value) {
$.post("showmore_search.php", {newsResult:value}, function(data){
$("#news-table-wrap").html(data);
});
}
</script>
</head>
<body>
<input type="text" name="search" id="search" class="search-box" onKeyUp="searchNews(this.value)" placeholder="Search News">
<table id="news-table-wrap" class="news-table-wrap" cellpadding="0" cellspacing="0">
</table>
<div align="center">
<div class="load_more" id="load_more_button">Show More</div>
<div class="animation_image" style="display:none;"><img src="/files/ajax-loader.gif"></div>
</div>
</body>
</html>
SHOWMORE_SEARCH.php
<?php
include_once("connect.php");
$newsResult = $_POST['newsResult'];
$item_per_page = 3;
$page_number = $_POST["page"];
$position = ($page_number * $item_per_page);
$sql = "SELECT * FROM database WHERE headline LIKE '%$newsResult%' OR post LIKE '%$newsResult%' ORDER BY date DESC LIMIT $position, $item_per_page";
$query = mysqli_query($connect,$sql) or die (mysqli_error());
while ($row = mysqli_fetch_array($query)){
$headline = $row['headline'];
$author = $row['author'];
$date = $row['date'];
$post = $row['post'];
$name = $row['name'];
echo "<tr class='news-preview-wrap'>";
echo "<td><div class='news-preview-content'><div class='news-preview-headline'><a href='news_post?name=".$name."'>".$headline."</a></div>
<div class='news-preview-date'>Written by ".$author." on ".$date."</div>
<div class='news-preview-post'>".$post."</div></div>
<div class='news-more'><a href='news_post?name=".$name."'>Read More</a></div></td>";
echo "</tr>";
} else {
echo "<div class='search-error'>No search results were found...</div>";
}
?>
Here is something you can do with Ajax, PHP and JQuery. Hope this helps or gives you a start.
See live demo and source code here.
http://purpledesign.in/blog/to-create-a-live-search-like-google/
Create a search box, may be an input field like this.
<input type="text" id="search" autocomplete="off">
Now we need listen to whatever the user types on the text area. For this we will use the jquery live() and the keyup event. On every keyup we have a jquery function “search” that will run a php script.
Suppose we have the html like this. We have an input field and a list to display the results.
<div class="icon"></div>
<input type="text" id="search" autocomplete="off">
<ul id="results"></ul>
We have a Jquery script that will listen to the keyup event on the input field and if it is not empty it will invoke the search() function. The search() function will run the php script and display the result on the same page using AJAX.
Here is the JQuery.
$(document).ready(function() {
// Icon Click Focus
$('div.icon').click(function(){
$('input#search').focus();
});
//Listen for the event
$("input#search").live("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search_st.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}return false;
}
})
;
In the php, shoot a query to the mysql database. The php will return the results that will be put into the html using AJAX. Here the result is put into a html list.
Suppose there is a dummy database containing two tables animals and bird with two similar column names ‘type’ and ‘desc’.
//search.php
// Credentials
$dbhost = "localhost";
$dbname = "live";
$dbuser = "root";
$dbpass = "";
// Connection
global $tutorial_db;
$tutorial_db = new mysqli();
$tutorial_db->connect($dbhost, $dbuser, $dbpass, $dbname);
$tutorial_db->set_charset("utf8");
// Check Connection
if ($tutorial_db->connect_errno) {
printf("Connect failed: %s\n", $tutorial_db->connect_error);
exit();
}
$html = '';
$html .= '<li class="result">';
$html .= '<a target="_blank" href="urlString">';
$html .= '<h3>nameString</h3>';
$html .= '<h4>functionString</h4>';
$html .= '</a>';
$html .= '</li>';
$search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
$search_string = $tutorial_db->real_escape_string($search_string);
// Check Length More Than One Character
if (strlen($search_string) >= 1 && $search_string !== ' ') {
// Build Query
$query = "SELECT *
FROM animals
WHERE type LIKE '%".$search_string."%'
UNION ALL SELECT *
FROM birf
WHERE type LIKE '%".$search_string."%'"
;
$result = $tutorial_db->query($query);
while($results = $result->fetch_array()) {
$result_array[] = $results;
}
// Check If We Have Results
if (isset($result_array)) {
foreach ($result_array as $result) {
// Format Output Strings And Hightlight Matches
$display_function = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['desc']);
$display_name = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['type']);
$display_url = 'https://www.google.com/search?q='.urlencode($result['type']).'&ie=utf-8&oe=utf-8';
// Insert Name
$output = str_replace('nameString', $display_name, $html);
// Insert Function
$output = str_replace('functionString', $display_function, $output);
// Insert URL
$output = str_replace('urlString', $display_url, $output);
// Output
echo($output);
}
}else{
// Format No Results Output
$output = str_replace('urlString', 'javascript:void(0);', $html);
$output = str_replace('nameString', '<b>No Results Found.</b>', $output);
$output = str_replace('functionString', 'Sorry :(', $output);
// Output
echo($output);
}
}

How to Modify PHP/Jquery/Ajax script to have more than one form field posst

I have an php/Ajax/Jquery script that inserts a form field into MySQL and updates the page without refreshing when you hit submit. I would like the script to submit four form fields, instead of just one.
I have already updated the database table add_delete_record with 3 additional fields: balance, account_number and monthly, plus the content field that was already there.
Below is probably overkill of code because I only need to modify a few lines, but I figured this would answer all the questions.
This is the php & html page:
<div class="content_wrapper">
<ul id="responds">
<?php
//include db configuration file
include_once("config.php");
//MySQL query
$Result = mysql_query("SELECT id,content FROM add_delete_record");
//get all records from add_delete_record table
while($row = mysql_fetch_array($Result))
{
echo '<li id="item_'.$row["id"].'">';
echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$row["id"].'">';
echo '<img src="images/icon_del.gif" border="0" />';
echo '</a></div>';
echo $row["content"].'</li>';
}
//close db connection
mysql_close($connecDB);
?>
</ul>
<div class="form_style">
<textarea name="content_txt" id="contentText" cols="45" rows="5"></textarea>
<button id="FormSubmit">Add record</button>
</div>
</div>
This is the php it posts to:
<?php
//include db configuration file
include_once("config.php");
//check $_POST["content_txt"] is not empty
if(isset($_POST["content_txt"]) && strlen($_POST["content_txt"])>0)
{
//sanitize post value, PHP filter FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH
$contentToSave = filter_var($_POST["content_txt"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
// Insert sanitize string in record
if(mysql_query("INSERT INTO add_delete_record(content) VALUES('".$contentToSave."')"))
{
//Record is successfully inserted, respond to ajax request
$my_id = mysql_insert_id(); //Get ID of last inserted record from MySQL
echo '<li id="item_'.$my_id.'">';
echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$my_id.'">';
echo '<img src="images/icon_del.gif" border="0" />';
echo '</a></div>';
echo $contentToSave.'</li>';
mysql_close($connecDB);
}else{
//output error
//header('HTTP/1.1 500 '.mysql_error());
header('HTTP/1.1 500 Looks like mysql error, could not insert record!');
exit();
}
}
elseif(isset($_POST["recordToDelete"]) && strlen($_POST["recordToDelete"])>0 && is_numeric($_POST["recordToDelete"]))
{//do we have a delete request? $_POST["recordToDelete"]
//sanitize post value, PHP filter FILTER_SANITIZE_NUMBER_INT removes all characters except digits, plus and minus sign.
$idToDelete = filter_var($_POST["recordToDelete"],FILTER_SANITIZE_NUMBER_INT);
//try deleting record using the record ID we received from POST
if(!mysql_query("DELETE FROM add_delete_record WHERE id=".$idToDelete))
{
//If mysql delete record was unsuccessful, output error
header('HTTP/1.1 500 Could not delete record!');
exit();
}
mysql_close($connecDB);
}else{
//Output error
header('HTTP/1.1 500 Error occurred, Could not process request!');
exit();
}
?>
This is the JQuery
$(document).ready(function() {
//##### Add record when Add Record Button is clicked #########
$("#FormSubmit").click(function (e) {
e.preventDefault();
if($("#contentText").val()==="") //simple validation
{
alert("Please enter some text!");
return false;
}
var myData = "content_txt="+ $("#contentText").val(); //post variables
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "response.php", //Where to make Ajax calls
dataType:"text", // Data type, HTML, json etc.
data:myData, //post variables
success:function(response){
$("#responds").append(response);
$("#contentText").val(''); //empty text field after successful submission
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError); //throw any errors
}
});
});
//##### Delete record when delete Button is clicked #########
$("body").on("click", "#responds .del_button", function(e) {
e.preventDefault();
var clickedID = this.id.split("-"); //Split string (Split works as PHP explode)
var DbNumberID = clickedID[1]; //and get number from array
var myData = 'recordToDelete='+ DbNumberID; //build a post data structure
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "response.php", //Where to make Ajax calls
dataType:"text", // Data type, HTML, json etc.
data:myData, //post variables
success:function(response){
//on success, hide element user wants to delete.
$('#item_'+DbNumberID).fadeOut("slow");
},
error:function (xhr, ajaxOptions, thrownError){
//On error, we alert user
alert(thrownError);
}
});
});
});
This is not my script so I thought I should also give a link to credit the author of it:
http://www.sanwebe.com/2012/04/ajax-add-delete-sql-records-jquery-php
i'm no php expert, but this should get you through:
First change the form area on the main page:
<div class="form_style">
<textarea name="content_txt" id="contentText" cols="45" rows="5"></textarea><br/>
<input type="text" id="balance" /><br/>
<input type="text" id="acctNum" /><br/>
<input type="text" id="monthly" /><br/>
<button id="FormSubmit">Add record</button>
</div>
then your myData looks like this:
var myData = {
content_txt: $("#contentText").val(),
balance: $("#balance").val(),
acctNum: $("#acctNum").val(),
monthly: $("#monthly").val()
};
and later in the ajax response:
$("#contentText").val(''); //empty text field after successful submission
$("#balance").val('');
$("#acctNum").val('');
$("#monthly").val('');
and finally the PHP:
//sanitize post value, PHP filter FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH
$content = filter_var($_POST['content_txt'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$balance = filter_var($_POST['balance'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$account = filter_var($_POST['acctNum'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$monthly = filter_var($_POST['monthly'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$qry= "INSERT INTO add_delete_record(content,balance,account,monthly) VALUES('".$content."','".$balance."','".$account."','".$monthly."')";
// Insert sanitize string in record
if(mysql_query("INSERT INTO add_delete_record(content,balance,account,monthly) VALUES('".$content."','".$balance."','".$account."','".$monthly."')"))
{
//Record is successfully inserted, respond to ajax request
$my_id = mysql_insert_id(); //Get ID of last inserted record from MySQL
echo '<li id="item_'.$my_id.'">';
echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$my_id.'">';
echo '<img src="images/icon_del.gif" border="0" />';
echo '</a></div>';
echo $content.'</li>';
mysql_close($connecDB);
}else{
//output error
//header('HTTP/1.1 500 '.mysql_error());
header('HTTP/1.1 500 Looks like mysql error, could not insert record!');
exit();
}
var myData = {
content_txt: $("#contentText").val(),
other_var: $("#anotherField").val()
};
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "response.php", //Where to make Ajax calls
dataType:"text", // Data type, HTML, json etc.
data:myData, //post variables
success:function(response){
$("#responds").append(response);
$("#contentText").val(''); //empty text field after successful submission
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError); //throw any errors
}
});
This is an easier way to send several fields (notice the myData object). In PHP you can retrieve and save your new variable like this:
//check $_POST["content_txt"] is not empty
if(isset($_POST["content_txt"]) && strlen($_POST["content_txt"])>0 && !empty($_POST["other_var"])) // !empty() checks that the variable is set and not empty
{
//sanitize post value, PHP filter FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH
$contentToSave = filter_var($_POST["content_txt"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$otherVarToSave = filter_var($_POST["other_var"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
// Insert sanitize string in record
if(mysql_query("INSERT INTO add_delete_record(content, other) VALUES('".$contentToSave."', '".$otherVarToSave."')"))
{
Something like this:
var myData = "content_txt="+ $("#contentText").val()+"&other_value"+ $("#foo").val(); //post variables
In the php file:
$other_value = $_POST['other_value'];
UPDATE:
balance, account_number and monthly
JS:
var myData = "content_txt="+ $("#contentText").val()+"&balance"+ $("#balance").val();
myData = myData + "&account_number="+$('#acnum').val()+"&monthly="+$('#month').val();
PHP:
$content = filter_var($_POST['content_txt'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$balance = filter_var($_POST['balance'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$account = filter_var($_POST['account_num'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$monthly = filter_var($_POST['monthly'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$qry= "INSERT INTO add_delete_record(content,balance,account,monthly) VALUES('".$content."','".$balance."','".$account."','".$monthly."')";
if(mysql_query($qry)){

PHP is not reloaded automatically after processing

Hi I have a PHP file with data. The value is passed on to another php file which process it successfully. But the first php file does not refresh to update the new result. It have to do it manually. Can any one tell me where I'm wrong or what needs to be done. Please find my code below.
PHP code (1st page, index.php)
function display_tasks_from_table() //Displayes existing tasks from table
{
$conn = open_database_connection();
$sql = 'SELECT id, name FROM todolist';
mysql_select_db('todolist'); //Choosing the db is paramount
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
echo "<form class='showexistingtasks' name='showexistingtasks' action='remove_task.php' method='post' >";
while($row = mysql_fetch_assoc($retval))
{
echo "<input class='checkbox' type='checkbox' name='checkboxes{$row['id']}' value='{$row['name']}' onclick='respToChkbox()' >{$row['name']} <img src='images/show_options.gif' /><br>";
}
echo "</form>";
echo "<label id='removeerrormsg'></label>";
close_database_connection($conn);
}
Javascript code which finds the selected value:
var selVal; //global variable
function respToChkbox()
{
var inputElements = document.getElementsByTagName('input'),
input_len = inputElements.length;
for (var i = 0; i<input_len; i++)
{
if (inputElements[i].checked === true)
{
selVal = inputElements[i].value;
}
}
}
jQuery code which passes value to another page (remove_Task.php):
$(document).ready(function() {
$(".checkbox").click(function(){
$.ajax({
type: "POST",
url: "remove_task.php", //This is the current doc
data: {sel:selVal, remsubmit:"1"},
success: function(data){
//alert(selVal);
//console.log(data);
}
});
});
});
PHP code (2nd page, remove_task.php);
session_start();
error_reporting(E_ALL);ini_set('display_errors', 'On');
$task_to_remove = $_POST['sel'];
function remove_from_list() //Removes a selected task from DB
{
$db_connection = open_database_connection();
global $task_to_remove;
mysql_select_db('todolist');
$sql = "DELETE FROM todolist WHERE name = "."'".$task_to_remove."'";
if($task_to_remove!='' || $task_to_remove!=null)
{
mysql_query($sql, $db_connection);
}
close_database_connection($db_connection);
header("Location: index.php");
}
if($task_to_remove != "") {
remove_from_list();
}
The selected value is getting deleted but the display on index.php is not updated automatically. I have to manually refresh to see the updated result. Any help would be appreciated.
By calling header("Location: index.php"); you don't redirect main page. You sent an ajax request - you can think about it as of opening a new page at the background, so this code redirects that page to index.php.
The better way to solve your task is to return status to your success function and remove items which were deleted from the database.
success: function(data){
if(data.success){
//remove deleted items
}
}

Categories