How to insert multiple row from textarea to multiple column? - php

I have this code from index.php :
<?php
require("../inc/config.php");
$url = $_GET['url'];
?>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>
<body>
<form method="" action="">
<textarea type="text" class="form-control" id="ketqua" name="ketqua" value="" required="" placeholder="Name|Url" rows="6"></textarea>
<input type="text" class="form-control" id="link" name="link" required="" value="<?php echo $url ?>">
<button type="button" class="btn btn-success" name="insert-data" id="insert-data" onclick="ThemTap()">Add</button>
</form>
<script type="text/javascript">
function ThemTap() {
var ketqua = $("#ketqua").val();
var link = $("#link").val();
$.ajax({
type: "POST",
url: "api.php",
data: {
action: 'ThemTap',
ketqua: ketqua,
link: link
},
dataType: "JSON",
success: function(data) {
$("#message").html(data);
$("p").addClass("alert alert-success");
},
error: function(err) {
alert(err);
}
});
}
</script>
This is my api.php .I think my code is missing or missing in this section and I don't know how to solve it:
<?php
include('../inc/config.php');
if($_POST['action'] == 'ThemTap') {
$ketqua=$_POST['ketqua'];
$string = $ketqua;
$HuuNhan = explode('|',$string);
$link=$_POST['link'];
$stmt = $DBcon->prepare("INSERT INTO tap(tap,link,player) VALUES(N'".$HuuNhan[0]."', N'$link',N'".$HuuNhan[1]."')");
mysqli_query($conn,"UPDATE phim SET updatephim = updatephim + 1 WHERE link = '$link'");
if($stmt->execute())
{
if (mysqli_query($conn, $sql)) {
}
$res="<div class='alert alert-success'>Đã thêm tập <b>".$HuuNhan[0]."</b> thành công !</div>";
echo json_encode($res);
}
else {
$error="<div class='alert alert-danger'>Thêm không thành công</div>";
echo json_encode($error);
}
}
?>
I tried running it as follows:
From text area
EP1|Link1
EP2|Link2
EP3|Link3
But it only inserts a row:
EP1|Link
And not insert EP2|Link2 and EP3|Link3
Please correct my source code so I can add many different rows, thank you very much!

Related

jQuery(AJAX) post to php issue when I try to insert data into DB

when I echo the php variable it work properly , but when I try to insert the data into database it doesn't work , what is the solution please I get stuck
I got this error on console
POST http://localhost/validate.php 500 (Internal Server Error)
send # jquery-3.1.1.min.js:4
ajax # jquery-3.1.1.min.js:4
(anonymous) # jquery.PHP:26
dispatch # jquery-3.1.1.min.js:3
q.handle # jquery-3.1.1.min.js:3
HTML/JQUERY
<form action="" id="myForm">
<input type="text" id="name" ><br/>
<input type="text" id="age" ><br/>
<input type="submit" value="Submit">
</form>
<div id="result"></div>
<script>
$(function() {
$("#myForm").submit(function(e) {
e.preventDefault();
var name = $('#name').val();
var age = $('#age').val();
$.ajax({
url: 'validate.php',
method: 'POST',
data: {postname:name, postage:age},
success: function(res) {
$("#result").append(res);
}
});
});
});
</script>
PHP
<?php
include 'mysqldb.php';
$name = $_POST['postname'];
$age = $_POST['postage'];
$sql = "insert into uss (first, last) values('".$name."','".$age."')";
$result = $conn->query($sql);
echo $result ;
?>
mysqldb.php
<?php
$conn = mysql_connect('localhost', 'root', 'password' , 'datab');
if (!$conn) {
die("Connection failed: ".mysqli_connect_error());
}
?>
Please add the details of the error message you get.
Make little changes to your code so that it can show the query error if any
<?php
include 'mysqldb.php';
$name = $_POST['postname'];
$age = $_POST['postage'];
$sql = "INSERT INTO `uss` (`first`, `last`) VALUES('{$name}','{$age}')";
if($conn->query($sql))
{
echo "Record inserted";
}
else
{
echo $conn->error;
}
?>
Sugesstions: Your query have the chances of the SQL Injection. Make it secure.
if you are using ajax , try the following,
<form >
<input type="text" id="name" ><br/>
<input type="text" id="age" ><br/>
<input type="submit" value="Submit" id="submit">
</form>
<div id="result"></div>
$("#submit").click(function(){
var name = $('#name').val(); // getting name
var age = $('#age').val();
$.ajax({
url : "validate.php",
type: "POST",
data: {name:name, age:age},
success: function(data)
{
$("#result").html(data);
}
});
});
in your controller function,echo the result
<?php
include 'mysqldb.php';
$name = $_POST['postname'];
$age = $_POST['postage'];
$sql = "insert into uss (first, last) values('$name','$age')";
$result = $conn->query($sql);
echo $result;
?>
jQuery Ajax
Form with id myFrom
<form action="" id="myForm">
<input type="text" id="name" ><br/>
<input type="text" id="age" ><br/>
<input type="submit" value="Submit">
</form>
<div id="result"></div>
jQuery Ajax section
$(function() {
$("#myForm").submit(function(e) {
e.preventDefault();
var name = $('#name').val(); // getting name
var age = $('#age').val(); // getting age
/* Ajax section */
$.ajax({
url: 'validate.php',
method: 'POST',
data: {postname:name, postage:age},
success: function(res) {
$("#result").append(res);
}
});
});
});
validate.php
<?php
include 'mysqldb.php';
$name = $_POST['postname'];
$age = $_POST['postage'];
//check ajax response by `echo $name` and `$age`
$sql = "insert into uss (first, last) values('".$name."','".$age."')";
$result = $conn->query($sql);
echo $result ;
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<form >
<input type="text" id="name" ><br/>
<input type="text" id="age" ><br/>
<input type="button" value="Submit" onclick="postdata();">
</form>
<div id="result"></div>
<script type="text/javascript">
function postdata() {
alert("ashad");
var name = $('#name').val();
var age = $('#age').val();
$.post('validate.php',{postname:name,postage:age},
function(data){
$('#result').html(data);
});
}
</script>
<?php
include 'mysqldb.php';
$name = $_POST['postname'];
$age = $_POST['postage'];
//check ajax response by `echo $name` and `$age`
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else
{
$sql = "insert into uss(first, last) values('$name','$age')";
$result = $conn->query($sql);
}
echo $result ;
?>

How to return output on the same page ajax php

I want to organize the selection query from index.php to action, so i can be able to call the file with ajax to show the data on the page.(index.php). So, the activity I want to do is to able to submit data of the form to the database and to display result on the same page(index.php) without refreshing the page. Help please
Here's my files
1.action.php
2.index.php
3.maker.js
//-----------------------action.php-----------------------------
<?php
include ("db_connect.php"); // Connecting to the database
$user = $_REQUEST['user'];
$text = $_REQUEST['text'];
$ParentId = $_REQUEST['ParentId'];
$action = $_REQUEST['action'];
if ($action=="add")
{
$query="INSERT into `comments` VALUES (NULL,'{$ParentId}','{$user}','{$text}',NOW())";
$result = mysqli_query($conn,$query);
}
if ($action=="delete")
{
$delete = "DELETE FROM `comments` WHERE id=$text";
$result = mysqli_query ($conn,$delete);
}
?>
//index.php
<div id="table_content"></div>
<script type="text/javascript" src="maker.js">
<?php
function ShowForm($AnswerCommentId)
{ ?>
<form id="myForm">
<input type="hidden" name="comment_on" id="comment_on" readonly="readonly" value="<?php print md5($_SERVER['PHP_SELF']); ?>" />
<input id="user" name="user" value="name" autocomplete="off" onfocus="if(this.value == 'name'){this.value = ''}" onblur="if(this.value == ''){this.value = 'name'}"/>
<textarea id='text' name='text' value="comment" onfocus="if(this.value == 'comment'){this.value = ''}" onblur="if(this.value == ''){this.value = 'comment'}" ></Textarea>
<input id="ParentId" name="ParentId" type="hidden" value="<?php echo($AnswerCommentId);?>"/>
<button type='button' OnClick=SendComment()>Comment</button>
</form>
<?php
}
$query="SELECT * FROM `comments` ORDER BY id ASC";
$result = mysqli_query($conn,$query);
if (isset($_REQUEST['AnswerId']))
{ $AnswerId = $_REQUEST['AnswerId']; }
else
{ $AnswerId = 0; }
$i=0;
while ($mytablerow = mysqli_fetch_row($result))
{
$mytable[$i] = $mytablerow;
$i++;
}
function tree($treeArray, $level, $pid = 0)
{
global $AnswerId;
if (! $treeArray)
{ return; }
foreach($treeArray as $item){
if ($item[1] == $pid)
{
?>
<div class="CommentWithReplyDiv" style="margin-left:<?php echo($level*60);?>px">
<div class="CommentDiv">
<pre class="Message"><?php echo($item[3]) ; ?></pre>
<div class="User"><?php echo($item[2]) ; ?></div>
<div class="Date"><?php echo($item[4]) ; ?></div>
<?php
if ($level<=4) { echo 'Reply'; }
echo 'Delete';
?> </div> <?php
if ($AnswerId == $item[0])
{
?><div id="InnerDiv"><?php ShowForm($AnswerId); ?></div>
<?php
}
?> </div> <?php
tree($treeArray, $level+1, $item[0]); // Recursion
}
}
}
tree($mytable, 0);
?>
//maker.js
function DeleteComment(number){
$.ajax({
type: "POST",
url: "action.php",
data: "user=1"+"&text="+number+"&ParentId=1"+"&action=delete",
success: function(html){
$("#table_content").html(html);
}
});
}
function AnswerComment (id){
$.ajax({
type: "POST",
url: "index.php",
data: "AnswerId="+id,
success: function(html){
$("#table_content").html(html);
}
});
}
function SendComment (){
var user1 = $("#user").val();
var text1 = $("#text").val();
var ParentId1 = $("#ParentId").val() + "";
$.ajax({
type: "POST",
url: "action.php",
cache: false,
data: "user="+user1+"&text="+text1+"&ParentId="+ParentId1+"&action=add",
success: function(html){
$("#table_content").html(html);
clean_form();
}
});
return false;
}
So you are basically trying to make ajax based comment system, From what i see, your code organization is not clear based on there tasks, specifically your index.php file so here is what you can do to simplify things :
your action.php should hanlde all php database releted tasks
Move your html code to some other file (Create Template)
Here is the modified code that i have come up with (This is just for your reference, you should modify this accoring to you needs, and as Xorifelse suggested in comment you should always use prepared statements in production system because of security concerns):
Action.php
<?php
include ("db_connect.php"); // Connecting to the database
$action = $_REQUEST['action'];
if ($action=="add")
{
$user = $_REQUEST['user'];
$text = $_REQUEST['text'];
$ParentId = $_REQUEST['ParentId'];
$query="INSERT into `comments` VALUES (NULL,'{$ParentId}','{$user}','{$text}',NOW())";
$result = mysqli_query($conn,$query);
}
if ($action=="delete")
{
$text = $_REQUEST['text'];
$delete = "DELETE FROM `comments` WHERE id=$text";
$result = mysqli_query ($conn,$delete);
}
if ($action=="get")
{
$query="SELECT * FROM `comments` ORDER BY id ASC";
$result = mysqli_query($conn,$query);
if (isset($_REQUEST['AnswerId']))
{ $AnswerId = $_REQUEST['AnswerId']; }
else
{ $AnswerId = 0; }
$i=0;
$mytable = array();
while ($mytablerow = mysqli_fetch_row($result))
{
$mytable[$i] = $mytablerow;
$i++;
}
tree($mytable, 0, $AnswerId);
}
function tree($treeArray, $level, $ansId, $pid = 0)
{
$AnswerId = $ansId;
if (! $treeArray)
{ return; }
foreach($treeArray as $item){
if ($item[1] == $pid)
{
include('comments.template.php');
tree($treeArray, $level+1,$AnswerId, $item[0]); // Recursion
}
}
}
?>
index.php
<html>
<head>
<title>Test page</title>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<script type="text/javascript" src="maker.js"></script>
</head>
<body onload="loadComments();">
<div id="table_content">
</div>
</body>
</html>
comments.template.php
<div class="CommentWithReplyDiv" style="margin-left:<?php echo($level*60); ?>px">
<div class="CommentDiv">
<pre class="Message"><?php echo($item[3]) ; ?></pre>
<div class="User"><?php echo($item[2]) ; ?></div>
<div class="Date"><?php echo($item[4]) ; ?></div>
<?php
if ($level<=4) {
echo 'Reply';
}
echo 'Delete';
?>
</div>
<?php if ($AnswerId == $item[0]) { ?>
<div id="InnerDiv"><?php include('commentForm.template.php'); ?></div>
<?php } ?>
commentForm.template.php
<form id="myForm">
<input type="hidden" name="comment_on" id="comment_on" readonly="readonly" value="<?php print md5($_SERVER['PHP_SELF']); ?>" />
<input id="user" name="user" value="name" autocomplete="off" onfocus="if(this.value == 'name'){this.value = ''}" onblur="if(this.value == ''){this.value = 'name'}"/>
<textarea id='text' name='text' value="comment" onfocus="if(this.value == 'comment'){this.value = ''}" onblur="if(this.value == ''){this.value = 'comment'}" ></Textarea>
<input id="ParentId" name="ParentId" type="hidden" value="<?php echo($AnswerId);?>"/>
<button type='button' OnClick="SendComment()">Comment</button>
</form>
marker.js
function DeleteComment(number){
$.ajax({
type: "POST",
url: "action.php",
data: "user=1"+"&text="+number+"&ParentId=1"+"&action=delete",
success: function(html){
$("#table_content").html(html);
loadComments();
}
});
}
function AnswerComment (id){
$.ajax({
type: "POST",
url: "action.php",
data: "AnswerId="+id+"&action=get",
success: function(html){
$("#table_content").html(html);
}
});
}
function SendComment (){
var user1 = $("#user").val();
var text1 = $("#text").val();
var ParentId1 = $("#ParentId").val() + "";
$.ajax({
type: "POST",
url: "action.php",
cache: false,
data: "user="+user1+"&text="+text1+"&ParentId="+ParentId1+"&action=add",
success: function(html){
$("#table_content").html(html);
loadComments();
}
});
return false;
}
function loadComments (){
$.ajax({
type: "POST",
url: "action.php",
cache: false,
data: "action=get",
success: function(html){
$("#table_content").html(html);
//clean_form();
}
});
return false;
}

ajax login error, can't check

I have problem, I can't check username and password, can you help me?
login.php:
<form class="login-form" method="post" name="loginform" action="">
<div class="title-section">
<h1><span>Login</span></h1>
</div>
<p>Welcome! Login in to your account</p>
<label for="user_login">Username or email address<span>*</span>
</label>
<input type="text" name="log" id="user_login">
<label for="user_pass">Password<span>*</span>
</label>
<input name="pwd" id="user_pass" type="password">
<div id="error"></div>
<button type="submit" name="submit-login" id="submit-login"> <i class="fa fa-arrow-circle-right"></i> Login </button>
</form>
model.php;
<?php
ob_start();
session_start();
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
?>
<?php
global $pdo;
session_start();
if(isset($_POST['submit-login'])) {
$user_email = trim($_POST['log']);
$user_password = trim($_POST['pwd']);
try {
global $pdo;
$stmt = $pdo->prepare("SELECT * FROM user WHERE username=:email");
$stmt->execute(array(":email"=>$user_email));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$count = $stmt->rowCount();
if($row['user_password']==$password){
echo "ok"; // log in
echo $_SESSION['user_session'] = $row['id_user'];
}
else {
echo "email or password does not exist."; // wrong details
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
?>
ajax.js
$(document).ready(function(){
$("#submit-login").click(function(){
username=$("#user_login").val();
password=$("#user_pass").val();
$.ajax({
type: "POST",
url: "admin/module/admin/model/acc_model.php",
data: "name="+username+"&pwd="+password,
success: function(html){
if(html=='ok') {
window.location="profile.php";
}
else {
alert('Please, Error');
}
},
beforeSend:function() {
$("#error").html("<img src='http://www.chinesecio.com/templates/base/images/loading.gif' /> Loading...")
}
});
return false;
});
});
You should pass the data like this
$(document).ready(function(){
$("#submit-login").click(function(){
username=$("#user_login").val();
password=$("#user_pass").val();
$.ajax({
type: "POST",
url: "admin/module/admin/model/acc_model.php",
data: {
name : username,
pwd : password
},
success: function(html){
if(html=='ok') {
window.location="profile.php";
}
else {
alert('Please, Error');
}
},
beforeSend:function()
{
$("#error").html("<img src='http://www.chinesecio.com/templates/base/images/loading.gif' /> Loading...")
}
});
return false;
});
});
Also use parameter like below :
$user_email = trim($_POST['name']);
$user_password = trim($_POST['pwd']);
I think that when you are sending data from your ajax request you are using different variable names and in your model.php you are using your form elements name. Please check into that
data : {"name":username, "password ":password}

Show/hide DIV with create, edit, delete

I have three buttons (create,edit,delete) with three separate functions defined in a class.
When I click on create, create function should be called and likewise for edit and delete.
Everything was working fine up-to here, but when I click on submit in anyone of the options(create/edit/delete), the page is redirecting by displaying the first div "cs_content" all the time.
My Requirement is : Until the data is stored to database successfully by submitting, then only the page should redirect to "cs_content" else in case any errors, the page should be
on the selected div.
$ (document).ready(function ()
{
//$("#cs_content").show();
$('#cs').click(function ()
{
$('#cs_content').fadeIn('slow');
$('#rp_content').hide();
});
$('#ed').click(function ()
{
$('#ed_content').fadeIn('slow');
$('#cs_content').hide();
});
$('#del').click(function ()
{
$('#del_content').fadeIn('slow');
$('#ed_content').hide();
});
});
<div class="container2">
<div id="cs" style="float:left;margin:0px 0px;padding:7px;"><input type="button" value="Create"></div>
<div id="ed" style="float:left;margin:0px 0px;padding:7px;"><input type="button" value="Edit"></div>
<div id="del" style="float:left;margin:0px 0px;padding:7px;"><input type="button" value="Delete"></div>
<div id="cs_content"><?php $ds->create_ds($db_host,$db_username,$db_password); ?> </div>
<div id="ed_content" style="display:none;"> <?php $ds->update_ds($db_host,$db_username,$db_password); ?> </div>
<div id="del_content" style="display:none;"> <?php $ds->delete_ds($db_host,$db_username,$db_password); ?> </div>
</div>
Updated code:
class Datasource
{
private $db;
public function __construct($database){
$this->db = $database;
}
//CREATE DATASOURCE
public function create_ds($db_host,$db_username,$db_password)
{
if (isset($_POST['create_dsource']))
{
$dsource_host = htmlentities($_POST['dsource_host']);
$dsource_username = htmlentities($_POST['dsource_username']);
$dsource_password = $_POST['dsource_password'];
$dsource_name = htmlentities($_POST['dsource_name']);
if (empty($_POST['dsource_host']) || empty($_POST['dsource_username']) || empty($_POST['dsource_name']))
{
$errors[] = '<span class="error">All fields are required.</span>';
}
else
{
if (isset($_POST['dsource_host']) && empty($_POST['dsource_host'])) { $errors[] = '<span class="error">Datasource Host is required</span>'; }
else if ($_POST['dsource_host'] !== $db_host)
{ $errors[] = '<span class="error">dsource Host is not matching with the application data source host </span>'; }
if(isset($_POST['dsource_username']) && empty($_POST['dsource_username'])) { $errors[] = '<span class="error">Datasource username is required</span>'; }
else if ($_POST['dsource_username'] !== $db_username)
{ $errors[] = '<span class="error">Datasource Username is not matching with the application datasource username </span>'; }
if ($_POST['dsource_password'] !== $db_password)
{ $errors[] = '<span class="error">Datasource Password is not matching with the application datasource password </span>'; }
if (isset($_POST['dsource_name']) && empty($_POST['dsource_name'])) { $errors[] = '<span class="error">Datasource name is required</span>'; }
else if (!ctype_alnum($_POST['dsource_name']))
{ $errors[] = '<span class="error">Please enter a datasource name with only alphabets and numbers</span>'; }
}
if (empty($errors) === true)
{
try
{
$this->db->exec("CREATE DATABASE IF NOT EXISTS ".$dsource_name."");
$this->db->query("USE ".$dsource_name."");
$sql_filename = "includes/datasource.sql";
$sql_contents = file_get_contents($sql_filename);
$sql_contents = explode("##", $sql_contents);
foreach($sql_contents as $query)
{
$result = $this->db->prepare($query);
$result->execute();
}
}
catch (PDOException $e) {
die("DB ERROR: ". $e->getMessage());
}
header('Location:home.php?success');
exit();
}
}
if (isset($_GET['success']) && empty($_GET['success']))
{
header('Refresh:0; url=home.php');
echo '<span class="error">Datasource is succesfully created</span>';
}
?>
<form action="" method="POST" accept-charset="UTF-8" id="create_ds" name="create_ds">
<table class="create_dsource">
<tr><td><label>Datasource Host</label><span style="color:#A60000">*</span></td>
<td><input type="text" name="dsource_host" required placeholder="localhost/server" value="<?php if(isset($_POST["dsource_host"])) echo $dsource_host; ?>" size="30">
</td></tr>
<tr><td><label>Datasource Username</label><span style="color:#A60000">*</span></td>
<td><input type="text" name="dsource_username" required placeholder="Datasource username" size="30" value="<?php if(isset($_POST["dsource_username"])) echo $dsource_username; ?>">
</td></tr>
<tr><td><label>Datasource Password</label></td>
<td><input type="password" name="dsource_password" placeholder="Datasource password" size="30" value="<?php if(isset($_POST["dsource_password"])) echo $dsource_password; ?>" autocomplete="off">
</td></tr>
<tr><td><label>Datasource Name</label><span style="color:#A60000">*</span></td>
<td><input type="text" name="dsource_name" size="30" required placeholder="Datasource name" value="<?php if(isset($_POST["dsource_name"])) echo $dsource_name; ?>">
</td></tr>
<tr><td><input type="submit" value="create datasource" style="background:#8AC007;color:#080808;padding:6px;" name="create_dsource"></td></tr>
</table>
</form>
<?php
//IF THERE ARE ERRORS, THEY WOULD BE DISPLAY HERE
if (empty($errors) === false)
echo '<div>' . implode('</p><p>', $errors) . '</div>';
}
} //class closes here
$ds = new Datasource($db);
UPDATED WITH EXAMPLE.
You doing bad mistake it's not the right way to do what you want.
You should use ajax.
Read here jQuery.AJAX guide .
I made you example how to do it VERY BASIC but will do the job:
HTML PAGE :
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$ (document).ready(function ()
{
//$("#cs_content").show();
$('#cs').click(function ()
{
createDs();
});
$('#ed').click(function ()
{
updateDs();
});
$('#del').click(function ()
{
deleteDs();
});
});
function createDs(){
$.ajax({
url: "check.php?proc=create",
type: "POST",
dataType:'json',
success: function(data)
{
$('#returnMessage').show();
$('#returnMessage').html(data.mes);
}
});
return false;
}
function updateDs(){
$.ajax({
url: "check.php?proc=update",
type: "POST",
dataType:'json',
success: function(data)
{
$('#returnMessage').show();
$('#returnMessage').html(data.mes);
}
});
return false;
}
function deleteDs(){
$.ajax({
url: "check.php?proc=delete",
type: "POST",
dataType:'json',
success: function(data)
{
$('#returnMessage').show();
$('#returnMessage').html(data.mes);
}
});
return false;
}
</script>
<div class="container2">
<div style="float:left;margin:0px 0px;padding:7px;"><input type="submit" value="Create" id="cs"></div>
<div style="float:left;margin:0px 0px;padding:7px;"><input type="submit" value="Edit" id="ed"></div>
<div style="float:left;margin:0px 0px;padding:7px;"><input type="submit" value="Delete" id="del"></div>
<div style="float:left;margin:0px 0px;padding:7px;"><input type="submit" value="Clear DIV" id="clear"></div>
<div id="returnMessage" style="display:none;"></div>
<div id="returnMessage" style="display:none;"></div>
</div>
check.php: (don't forget include here $ds-)
<?php
//include here $ds- so it could work and won't give you a error.
if(isset($_GET['proc']) && !empty($_GET['proc'])){
$proc = $_GET['proc'];
if($proc == 'create'){
$ds->create_ds($db_host,$db_username,$db_password);
$return = array('mes' => 'Created' );
header('content-type: application/json; charset=utf-8');
echo json_encode($return);
}elseif($proc == 'update'){
$ds->update_ds($db_host,$db_username,$db_password);
$return = array('mes' => 'Updated' );
header('content-type: application/json; charset=utf-8');
echo json_encode($return);
}elseif($proc == 'delete'){
$ds->delete_ds($db_host,$db_username,$db_password);
$return = array('mes' => 'Deleted' );
header('content-type: application/json; charset=utf-8');
echo json_encode($return);
}
}else{
$return = array('mes' => 'The $_GET is empty , check if all parms and ajax function passing to the true file, good luck :).' );
header('content-type: application/json; charset=utf-8');
echo json_encode($return);
}
?>
You muse include files to check.php either to use $ds- , its must basic and you should take a look how ajax works.
EDIT:
Here working example :
Click on me to go to demo , Here you can download the example:Click on me to download the example
Working perfect,don't forget uncomment // from the check.php so it will do you'r stuff that you needed.
If you still can't make it work (even when you have WORKING DEMO) , go learn php and Javascript , this all i can help you.
Also research google about firebug , this will help you see error's from ajax/post request, and will help you either in anyway.
You need ajax to dynamically run some php code when binding to events such as click. Try read on .ajax()
PHP code is executed before your DOM is created. So your jquery is not running the function again it is just showing the content that is already sent by your php functions. You need Ajax to run your php function and display data sent back by it.

jquery/ajax form another div refresh

I would start with my code...
<script type="text/javascript">
$(document).ready(function(){
$("#cForm").validate({
debug: false,
rules: {
name: "required",
email: {
required: true,
email: true
},
comment: "required"
},
messages: {
name: "Empty.",
email: "Invalid email.",
comment: "Empty.",
},
submitHandler: function(form) {
// do other stuff for a valid form
$.post('process.php', $("#cForm").serialize(), function(data) {
$('#results').html(data);
});
}
});
});
The above code is working fine with the form below, and giving success message out of my process.php fine into div with id results but i have another div before that with id comments which selects and displays the data from the same table where this ajax/jquery form stores the data...I want to refresh that with the latest changes when the form is submitted..have a look at my code first.
<div id="comments">
<h2>Comments</h2>
<?php
$query3 = "SELECT name, c_c, c_date FROM blog_comments WHERE art_id='$id'";
$result3 = #mysql_query($query3);
while($rr=mysql_fetch_array($result3))
{
echo '<div class="comen">';
echo "<h3>";
echo $rr['name'];
echo "</h3>";
echo "<h4>";
echo $rr['c_date'];
echo "</h4>";
echo "<p>";
echo $rr['c_c'];
echo "</p>";
echo '</div>';
}
mysql_close();
?>
</div>
<p>Post your comments. All fields are obligatory.</p>
<div id="results"></div>
<form action="" id="cForm" name="cForm" method="post" class="cform">
<table>
<tr><td><label for="name" id="name_label">Name</label></td><td><input type="text" name="name" id="name" size="30" /></td></tr>
<tr><td><label for="email" id="email_label">Email</label></td><td><input type="text" name="email" id="email" size="30" /></td></tr>
<tr><td><label for="comment" id="comment_label">Comment</label></td><td><textarea name="comment" id="comment" cols="30" rows="5"></textarea></td></tr>
<tr><td><input type="hidden" name="idi" value="<?php echo $id ?>" /></td></tr>
<tr><td></td><td><input type="submit" name="submit" value="Submit" /></td></tr>
</table>
</form>
and my process php looks like this
if (isset($_POST['submit']))
{
include ('databas/conektion.php');
function escape_data ($data)
{
global $con;
if (ini_get('magic_quotes_gpc'))
{
$data = stripslashes($data);
}
return mysql_real_escape_string($data,$con);
}
if (empty($_POST['name']))
{
$n = FALSE;
echo '<p>Invalid name</p>';
}
else
{
$n = escape_data($_POST['name']);
}
if (empty($_POST['email']))
{
$e = FALSE;
echo '<p>Invalid Email</p>';
}
else
{
$e = escape_data($_POST['email']);
}
if (empty($_POST['comment']))
{
$c = FALSE;
echo '<p>Invalid Comments</p>';
}
else
{
$c = escape_data($_POST['comment']);
}
$id = $_POST['idi'];
if($n && $e && $c)
{
$query2 = "INSERT INTO blog_comments (name, c_email, c_c, art_id, c_date) VALUES ('$n', '$e', '$c', '$id', NOW())";
$result2 = #mysql_query($query2);
if($result2)
{
echo '<p>Your comments have been posted successfully.</p>';
}
else
{
echo '<p>System Error</p><p>' . mysql_error() . '</p>';
}
mysql_close();
}
else
{
echo '<p style="color:red">Please try again.</p>';
}
}
?>
what i want to do is refresh div with id comments, once form is submitted.what changes should i make in my code...thanks!!
Create a new file called comments.php (with source code of your comments block)
Initially load comments
$(document).ready(function() { $("#comments_div").load("comments.php"); });
Then when you want to refresh, just call $("#comments_div").load("comments.php");
ie. from your first given code
submitHandler: function(form) {
// do other stuff for a valid form
$.post('process.php', $("#cForm").serialize(), function(data) {
$('#results').html(data);
$("#comments_div").load("comments.php");
});
}
EDIT:
If you have an ID in your url, then replace
$("#comments_div").load("comments.php");
with
$.get("comments.php", {"id": "<?=(0+$_GET['id'])?>"},
function(response) {
$("#comments_div").html(response);
}
);
Where your_id is the name of GET parameter.
EDIT2:
So how about if you try something like:
$.get("comments.php", {id: <?php echo (0+$_GET['id']); ?>},
function(response) {
$("#comments_div").html(response);
}
);
Thanks bro for your help,,and giving me so much time...my head tags look like this altogether now...
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><?php echo $page_title; ?></title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"> </script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function(){
$("#cForm").validate({
debug: false,
rules: {
name: "required",
email: {
required: true,
email: true
},
comment: "required"
},
messages: {
name: "Empty.",
email: "Invalid email.",
comment: "Empty.",
},
submitHandler: function(form) {
// do other stuff for a valid form
$.post('process.php', $("#cForm").serialize(), function(data) {
$('#results').html(data);
$.get("comment.php", {"id": "<?=(0+$_GET['id'])?>"},
function(response) {
$("#comment").html(response);
}
);
});
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function() { $.get("comment.php", {"id": "<?=(0+$_GET['id'])?>"},
function(response) {
$("#comment").html(response);
}
); });
</script>
</head>

Categories