I have an upload field in my form.
I had this code in my form.php
<form id="photoform" name="photoform" method="post" onSubmit="return false" enctype="multipart/form-data">
<div id="upphotosection"></div>
<label>Upload photo</label>
<input name="uploadphoto" id="uploadphoto" type="file" />
<div class="innerformclear"></div>
<input id="hidden" value="" name="hidden" type="hidden" />
<label> </label>
<input name="upphoto_submit" id="upphoto_submit" type="submit" value="Submit"/>
<div style="clear:both;"> </div>
<label> </label>
<div id="result_upphoto_submit"></div>
</form>
This is the code in formaction.php
header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");
include("../../../wp-load.php");
session_start();
$err = '';
$success = '';
global $wpdb, $PasswordHash, $current_user, $user_ID;
if($upphoto = $_FILES['uploadphoto']["name"] != '' ){
$path = 'images/profilephotos/';
$upphoto = copyServiceImage($path,$_FILES['uploadphoto']) ;}
$postid = 52;
############### Check Duplication
$sel_photo = "SELECT * FROM `pro_table` WHERE `post_id` = '".$postid."'";
$sel_res = mysql_query($sel_photo) ;
if(mysql_num_rows($sel_res) == 0){
$ins_photo = "Insert into pro_table (post_id,photo_photo,int_status) values ('$postid','$upphoto','0')";
$ins_res = mysql_query($ins_photo);
}
else{
$upd_photo = "Update pro_table set photo_photo = '$upphoto' ,int_status='0' where post_id = '$postid' ";
$upd_res = mysql_query($upd_photo);
}
echo $_GET['callback'] . '('.json_encode("success").')';
This is the code in java script file.
$(document).ready(function() {
///////////// Submit action for upload photo
$("#upphoto_submit").click(function() {
if(document.getElementById('uploadphoto').value == '' ){
alert("Please upload Photo");
document.getElementById('uploadphoto').focus();
return false;
}
else {
$('#result_upphoto_submit').html('<img src="http://www.test.com/test/uploads/2012/04/ajax-loader.gif" class="loader" align="absmiddle" /> ').fadeIn();
var input_data = $('#photoform').serialize();
$.ajax({
type: "POST",
url: "http://www.test.com/test/themes/test/formaction.php",
dataType: 'jsonp',
data: input_data,
success: function(msg){
$('#result_upphoto_submit').html(' ');
if(msg == 'success') {
msg = '<p class="success_custom">Photo successfully added.</p>';
$('<div>').html(msg).appendTo('div#upphotosection').hide().fadeIn('slow');
} else {
msg = ' Exists';
alert("Error in updation");
}
}
});
return false;
}
});
});
If i browse an image and click submit it showed me the success message Photo successfully added. But there is no image in profile photos folder and there is no data stored in admin panel. I couldn't track the error. How do i correct that?
is there an error in?
$_FILES["uploadphoto"]["error"];
also i dont know how wordpress handle images but i miss the file movement:
if ($_FILES["uploadphoto"]["error"] != UPLOAD_ERR_OK) {
$tmp_name = $_FILES["uploadphoto"]["tmp_name"];
$name = $_FILES["pictures"]["name"];
$path = "images/profilephotos/".$name;
move_uploaded_file($tmp_name,$path);
}
or i suppose it is called here?
$upphoto = copyServiceImage($path,$_FILES['uploadphoto']) ;}
Related
I have this form
<form id="home" class="validate-form" method="post" enctype="multipart/form-data">
<!-- Form Item -->
<div class="form-group">
<label>How much money do you need? (Kenya Shillings)</label>
<div class="input-group">
<div class="input-group-addon">Ksh</div>
<input id="moneyAmount" type="number" id="amount" name="amount" class="form-control slider-control input-lg" value="100000" min="10000" max="1000000" data-slider="#moneySlider" required>
</div>
<div id="moneySlider" class="form-slider" data-input="#moneyAmount" data-min="10000" data-max="1000000" data-value="100000"></div>
</div>
<!-- Form Item -->
<div class="form-group">
<label>How long? (months)</label>
<div class="input-group">
<input id="monthNumber" type="number" id="duration" name="duration" class="form-control slider-control input-lg" value="10" min="6" max="12" data-slider="#monthSlider" required>
<div class="input-group-addon">months</div>
</div>
<div id="monthSlider" class="form-slider" data-input="#monthNumber" data-min="6" data-max="12" data-value="10"></div>
</div>
<div class="form-group">
<label>Telephone Number</label>
<!-- Radio -->
<input type="number" id="telephone" name="telephone" class="form-control" required/>
</div>
<!-- Form Item -->
<div class="form-group">
<label>3 Months Bank or Paypal or Mpesa Statements</label>
<!-- Radio -->
<input type="file" name="image" class="ml btn btn-primary btn-lg" /><span>Upload</span>
</div>
<!-- Form Item -->
<div class="form-group">
<label>Monthly repayment</label>
<span id="formResult" class="form-total">Ksh<span>262.99</span></span>
</div>
<div class="form-group form-submit">
<button type="submit" class="btn-submit btn-lg"><span>Send a request!
</span></button>
</div>
</form>
This is the Jquery Script.
$( "#home" ).on( "submit", function( event ) {
event.preventDefault();
alert('subsequent clicks');
function chek(fData) {
var reg = new RegExp("^[-]?[0-9]+[\.]?[0-9]+$");
return reg.test(fData)
}
var phone = $('#telephone').val();
var amount = $('#amount').val();
var duration = $('#duration').val();
var ch = chek(phone);
if(phone == ""){
alert('phone cannot be empty');
return;
}
if(amount == ""){
alert('amount cannot be empty');
return;
}
if(duration == ""){
alert('duration cannot be empty');
return;
}
if(ch == false){
alert("Phone number must be a number");
return;
}
if(phone.length < 10 || phone.length > 12 ){
alert("Phone number must have 10 digits");
return;
}
if(ch == true && phone !== "" && amount !== "" && duration !== "" && phone.length == 10){
var s = phone;
s = s.replace(/^0+/, '');
var cc = 254;
var p = cc+s;
var pn = p.toString();
$('#telephone').val(p.toString());
var formData = new FormData($(this)[0]);
$.ajax({
url: 'http://example.com/home.php', //<== just add it to the end of url ***
type: 'POST',
data: formData,
async: true,
success: function (data) {
console.log(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
}
});
This is my PHP code:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
function random_str($length, $keyspace = '0123456789abcdefghijklmnopqrstuvwxyz')
{
$str = '';
$max = mb_strlen($keyspace, '8bit') - 1;
for ($i = 0; $i < $length; ++$i) {
$str .= $keyspace[random_int(0, $max)];
}
return $str;
}
$pass = random_str(4);
/**
Generic Customer Shown Interest
*/
$servername = "localhost";
$username = "root";
$password = "123456";
$dbname = "algo";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Posted Variables
$amount = $_POST['amount'];
$duration = $_POST['duration'];
$telephone = $_POST['telephone'];
$date = date('Y-m-d H:i:s');
//Check If User Exists
$result = $conn->query("select id from users where telephone=$telephone");
if($result->num_rows == 0) {
//Insert New User
$sql = "INSERT INTO users (telephone, password, service_name,date_submitted) VALUES ('$telephone', '$pass', 'loans','$date')";
if ($conn->query($sql) === TRUE) {
echo "User Is Inserted";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
} else {
//Insert New User
$sql2 = "INSERT INTO loans (amount, duration, telephone,documents,status,date)
VALUES ('$amount', '$duration','$telephone','logan2','on-hold','$date')";
if ($conn->query($sql2) === TRUE) {
echo "Loan Is Inserted";
} else {
echo "Error: " . $sql2 . "<br>" . $conn->error;
}
$conn->close();
}
?>
As you can tell the form is pretty basic and its only posting data to the server. When I load the page, I am able to insert data into the database but when I click the link again, nothing is inserted.
Is form data blocking me from posting duplicate data to the server?
change ajax part of your code and replace to this code shown below:
<script type="text/javascript">
$.ajax({
type:'POST',
url:'testing2.php',
data:new FormData($('#svf-form-4')[0]),
cache: false,
contentType: false,
processData: false,
success:function(msg){
$('#message').html(msg);
}
});
return false;
</script>
Hope it will work .
I cant explain what really worked but it seems clearing the form did allow for more post submission although i relied on this comment What does "async: false" do in jQuery.ajax()?
and this page What does "async: false" do in jQuery.ajax()? for inspiration.
This is the success callback
success: function (data) {
$("#home").trigger('reset');
console.log(data);
},
I'm trying to save some data into db using AJAX.It says it's successfully done but nothing happens.No data is being saved.Just keeps saying "Success".
index.php // form
<div id="cont">
<div id="kayit" style="display:none;">
Success
</div>
<div id="basarisiz" style="display:none;">
Empty or Fail
</div>
<form method="post" id="yaz" onsubmit="return false">
<input type="text" name="title" id="baslik" placeholder="Başlık" required><br/>
<textarea name="content" ></textarea><br/>
<input type="submit" name="gonder" value="Gönder" id="gonder" onclick="kayit()">
</form>
yaz.js
function kayit()
{
var baslik = $("input[name=title]").val();
var icerik = $("input[name=content]").val();
if (baslik =="" || icerik == "")
{
$('#basarisiz').show(1);
$('#kayit').hide(1);
}else
{
$.ajax ({
type: "POST",
url: "yazikaydet.php",
data: $("#yaz").serialize(),
success: function (sonuc) {
if (sonuc == "hata") {
alert ("unable to connect to db");
}else {
$('#kayit').show(1);
$('#basarisiz').hide(1);
$("input[name=title]").val("");
$("input[name=content]").val("");
}
}
}) }}
yazikaydet.php //the file which will save the data,not processing
<?php
include 'giris.php'; //sessions and connection strings
if(isset($_POST["gonder"]))
{
$baslik = $_POST["title"];
$icerik = $_POST["content"];
$tarih = date("d/m/20y");
$kull = $_SESSION["username"];
$kaydet = mysqli_query($connect,"INSERT INTO gonderiler (yazar,tarih,baslik,icerik) VALUES ('$kull','$tarih','$baslik','$icerik')");
if($kaydet)
{
echo "Yes";
}
else
{
echo "No";
}
}
?>
how to Getting error when submitting a form by ajax to page msg.php
file 1 = msg.php
<?php
$id = $_SESSION['id'];
$touser = htmlspecialchars($_GET['iduser']);
$postid = htmlspecialchars($_GET['post']);
?>
<div id="send">
<div id="title">صندوق المحادثة</div>
<form id="my-form" method="post" enctype="multipart/form-data">
<textarea id="_text" name="text" required=""></textarea>
<input id="_from" name="from" type="hidden" value="<?php echo $id; ?>"/>
<input name="to" type="hidden" value="<?php echo $touser; ?>"/>
<input name="post" type="hidden" value="<?php echo $postid ?>" />
<div class="file">
<li>ملفات .zip فقط</li>
<input class="up" type="file" name="up" />
</div>
<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token_madmoun']; ?>" />
<button class="submit">ارسال الان</button>
</form>
<script>
$( '#my-form' )
.submit( function( e ) {
$.ajax({
url: 'chat_a.php',
type: 'POST',
data: new FormData( this ),
processData: false,
contentType: false
} );
e.preventDefault();
document.getElementById("my-form").reset();
});
</script>
</div>
chat_a.php
<?php
include "config.php";
if(!$user->is_logged_in()){
header('Location: unregistered.php');
exit();
}
if (isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token_madmoun']) {
$id = $_SESSION['id'];
$data = date('Y-m-d');
$time = time();
$post = htmlspecialchars($_POST['post']);
$to = htmlspecialchars($_POST['to']);
$file_name = $_FILES['up']['name'];
$file_size = $_FILES['up']['size'];
$FileType = pathinfo($file_name,PATHINFO_EXTENSION);
if(!empty($_POST['text'])){
if(empty($FileType)) {
$sqladdcontent = $db->prepare("INSERT INTO chat_a SET _from = :_from, _to = :_to, _post = :_post, _data = :_data, _time = :_time, _text = :_text");
$sqladdcontent->bindParam(':_from', $id);
$sqladdcontent->bindParam(':_to', $to);
$sqladdcontent->bindParam(':_post', $post);
$sqladdcontent->bindParam(':_data', $data);
$sqladdcontent->bindParam(':_time', $time);
$sqladdcontent->bindParam(':_text', htmlspecialchars($_POST['text']));
$sqladdcontent->execute();
}else {
if($FileType != "zip" && $FileType != "ZIP") {
$error = "<center><div id='no-ok'>قم برفع ملفات بصيغة .zip فقط</div></center>";
}else {
if ($file_size > 104857600) {
$error = "<div id='no'>ممنوع حجم الملف اكبر من 100 ميجا</div>";
}else {
$time_digit = time() . '_';
$new_file_name = $time_digit.'.zip';
move_uploaded_file($_FILES['up']['tmp_name'], "upload-msg/".$new_file_name);
$sqladdcontent = $db->prepare("INSERT INTO chat_a SET _from = :_from, _to = :_to, _post = :_post, _data = :_data, _time = :_time, _text = :_text, _file = :_file");
$sqladdcontent->bindParam(':_from', $id);
$sqladdcontent->bindParam(':_to', $to);
$sqladdcontent->bindParam(':_post', $post);
$sqladdcontent->bindParam(':_data', $data);
$sqladdcontent->bindParam(':_time', $time);
$sqladdcontent->bindParam(':_text', htmlspecialchars($_POST['text']));
$sqladdcontent->bindParam(':_file', $new_file_name);
$sqladdcontent->execute();
}
}
}
}
}
?>
how to Getting error when submitting a form by ajax to page msg.php
The name of the variable is the error = $error
collect errors in php script as $errors array, then finaly ouput it as JSON:
print json_encode($errors);
and process it in success event handler
<script>
$( '#my-form' )
.submit( function( e ) {
$.ajax({
url: 'chat_a.php',
type: 'POST',
data: new FormData( this ),
processData: false,
contentType: false,
success: function(msg)
{
json = $.parseJSON(msg);
if (json.error[1] != "") //
$("#div-error-1").html(json.error[1]);
if (json.error[2] != "") //
$("#div-error-2").html(json.error[2]);
// and so on. Or you can use foreach construction. it will make code more universal
}
} );
e.preventDefault();
document.getElementById("my-form").reset();
});
</script>
I'm trying to host the files repo_display.php ---> repo_ajax.js ---> repo_action_with_DB.php --->return to repo_display.php. This works great on my localhost but once I publish it to the server it doesn't work.
When I submit repo_display.php form to call AJAX, it transfers me to the server page with the error message "error 403 - forbidden"
I try change permissions of js to 755-700 and it's works unless AJAX , it's forbidden to access repo_action_with_DB.php although I change their permission too ! . I try to access the page without submit the form it's display same problem
403 error forbidden Uncaught ReferenceError: prettyPrint is not
defined
repo_display.php
<html>
<head>
<!-- report java script -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type='text/javascript' src='scripts/repo_ajax.js'> </script>
</head>
<body>
<form action="" id="report">
<legend style="margin-left:40px;">text : </legend>
<p id="success" class="success"></p>
<input id="radio1" name="radio" value="Publisher" type="radio" onclick="radioClicked1()" required>
<input id="radio2" name="radio" value="Journal" type="radio" onclick="radioClicked2()" >
<input name="title1" type="text" required>
<input id="ISSN" name="ISSN" type="text" required>
<input id="url" name="url" type="url" required><br>
<input type="text" value="1" style="display:none;"/>
<input type ="submit" value="Save"/>
</form>
</body>
</html>
repo_ajax.js
$(document).ready(function () {
$("#send").click(function () {
var type;
if (document.getElementById('radio1').checked) {
type = document.getElementById('radio1').value;
}
else if (document.getElementById('radio2').checked) {
type = document.getElementById('radio2').value;
}
var title1 = document.getElementById('title1').value;
var ISSN = document.getElementById('ISSN').value;
var url = document.getElementById('url').value;
if (type == 'Journal' && ISSN == '') {
$("report")[0].checkValidity();
}
else if (type == '' || title1 == '' || url == '') {
// alert("fill all required fields !");
("report")[0].checkValidity();
if (type == 'Journal' && ISSN == '') {
$("report")[0].checkValidity();
}
}
else {
var r = confirm
("Are you sure to send this Report ?");
if (r == true)
{
$.ajax({
type: "GET",
url: "repo_action_with_DB.php",
data: "radio=" + type + "&title1=" + title1 + "&ISSN=" + ISSN + "&url=" + url,
success: function (data) {
if (data == 1)
{
$("#success2").html("Done");
}
else if (data == 2)
{
$("#success").html("Your Report is exist already");
}
else
{
$("#success").html("Faild ,please try again !");
}
}
});
}
}
return false;
});
});
function radioClicked1() {
}
function radioClicked2() {
}
repo_action_with_DB.php
<?php
ob_start();
//------------------Database section------------------------------------------
include('database.php');
//------------------Get the data ------------------------------------------
$title = $_GET['title1'];
$type = $_GET['radio'];
$url = $_GET['url'];
// ----------------------add -----------------------------------
if ($type == "k") {
$IS = $_GET['IS'];
$qry ="SELECT k_name FROM k where ISSN = '".$IS."'";
$result = mysql_query($qry);
if (mysql_num_rows($result) == 1) {
echo '2';
}
else {
$qry1 = "insert into k (`k_name`, `IS`, `URL`, `is_r`) values('" . $title . "','" . $IS . "','" . $url . "',1);";
$result1 = mysql_query($qry1);
if ($result1) {
echo '1';
}
}
}
?>
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.