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";
}
}
?>
Related
I want to enter data into my database using PHP and Ajax.
I have a kind of user guestbook.
When I run my code it always jumps automatically to the else {} area, my text does not enter the database.
Could you guys help me please?
This is my Ajax Code
$("#addComment").on("click", function(e){
e.preventDefault();
var comment = $("#comment").val();
$.ajax({
url: 'add_comment.php?page=<?php echo $page; ?>',
type: 'POST',
data: {comment: comment},
success: function(data){
if (data == 1) {
loadData();
alert('Comment Submitted Successfully.');
$("#commentBox").trigger("reset");
}else {
alert("Comment Can't Submit.");
}
}
});
});
This is my PHP Code:
session_start();
include("assets/include/config.php");
require_once('assets/JBBCode/Parser.php');
$userid = $_SESSION['userid'];
$username = $_SESSION['username'];
$page = $_GET['page'];
echo $username;
$parser = new JBBCode\Parser();
$parser->addCodeDefinitionSet(new JBBCode\DefaultCodeDefinitionSet());
$error = false;
$comment = htmlentities($_POST['comment']);
$parser->parse($comment);
$bbcode = $parser->getAsHtml();
if(strlen(trim($bbcode)) == 0){
$error = true;
}
if($error == false){
$stmt = $pdo->prepare("INSERT INTO threadComments (subThreadsID, username, userid, threadContent) VALUES (?,?,?,?)");
$stmt->execute([$page, $username, $userid, $bbcode]);
}
and this is my HTML Code:
<form id="commentBox" action="subcomments.php?page=<?php echo $page ?>" method="POST">
<div class="alert alert-light" role="alert">
<div class="input-group mb-3">
<textarea name="comment" id="comment" class="form-control" row="3" placeholder="Whats up.?" required></textarea>
</div>
<button type="submit" id="addComment" name="addComment" class="button-8">Comment</button>
</form>
With the help of $_GET['page'] I tell the database which guestbook the comment should be added to.
I am trying to use window.location = "userpage.php"; after a successful login but the page does not redirect.
I am using Ajax and a modal form in my code
Everything works fine. I don't get any errors. I check the network headers. and there is no response in the network
I have not been able to figure out the issue.
I have tried
window.location.href
window.location.replace.
Nothing is working
need help
Thanks
This is part of the js file
$("#loginform").submit(function(event) {
//prevent default php processing
event.preventDefault();
//collect user inputs
var datatopost = $(this).serializeArray();
//send them to login.php using AJAX
$.ajax({
url: "login.php",
type: "POST",
data: datatopost,
success: function(data) {
if (data == "success") {
window.location = "user_page.php";
} else {
$("#loginmessage").html(data);
}
},
error: function() {
$("#loginmessage").html(
"<div class='alert alert-danger'>There was an error with the Ajax Call. Please try again later.</div>"
);$
}
});
});
This is part of my login.php file
//Start session
session_start();
//Connect to the database
include("connection.php");
...
$email = mysqli_real_escape_string($conn, $email);
$password = mysqli_real_escape_string($conn, $password);
$password = hash('sha256', $password);
//Run query: Check combinaton of email & password exists
$sql = "SELECT * FROM users WHERE email='$email' AND password='$password' AND activation='activated'";
$result = mysqli_query($conn, $sql);
if (!$result) {
echo '<div class="alert alert-danger">Error running the query!</div>';
exit;
}
//If email & password don't match print error
$count = mysqli_num_rows($result);
if ($count !== 1) {
echo '<div class="alert alert-danger">Wrong Username or Password</div>';
} else {
//log the user in: Set session variables
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['username'] = $row['username'];
$_SESSION['email'] = $row['email'];
if (empty($_POST['remember'])) {
echo "success";
} else {
// todo logic for remember me
}
}
This is the form modal
//Start session
session_start();
//Connect to the database
include("connection.php");
...
<form method="post" class="login_form modal" id="loginform">
<div class="form-body">
<div class="form-head"><h3>Login form</h3></div>
<div class="form-logo"><img src="/dist/img/logo.svg" alt="" /></div>
<div id="loginmessage"></div>
<div class="form-inputs">
<p><input type="email" name="email" placeholder="email" /></p>
<p><input type="password" name="password" placeholder="Password" /></p>
</div>
<div class="login-session">
<div class="remember">
<input type="checkbox" id="remember" name="remember" value="remember" />
<label for="remember">Remember me</label>
</div>
<div class="">
Forgot my password
</div>
</div>
<div class="form-submit">
<input class="btn btn-primary" type="submit" value="log in"/>
<a class="btn btn-small" href="#signupform" rel="modal:open">register</a>
</div>
</div>
</form>
I finally found the solution to the issue.
In the index.js file:
success: function(data) {
if (data == "success") {
window.location = "user_page.php";`
was changed to:
success: function(data) {
if ($.trim(data) == "success") {
window.location = "user_page.php";`
Because the response message success for some reason had whitespace in it. I trimmed all whitespace and it worked.
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 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.
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']) ;}