I am trying to insert value using ajax in php, but data is not inserted in database. I have taken this code from the questions answered in other question from this site. Can anyone suggest where am I making mistake..?
<script>
$("#submit").click(function() {
var name= $("#name").val();
var password= $("#password").val();
$.ajax({
type: "POST",
url: "insert.php",
data: "name=" + name+ "&password=" + password,
success: function(data) {
alert("sucess");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<?php
//------insert.php------
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$name=$_POST['name'];
$pass=$_POST['password'];
$sql= mysqli_query($conn,"INSERT INTO insert_tbl(name,pass) VALUES('".$name."','".$pass."')");
?>
<script>
$("#FORM_ID").submit(function() {
var name= $("#name").val();
var password= $("#password").val();
$.ajax({
type: "POST",
url: "insert.php",
data: "name=" + name+ "&password=" + password,
success: function(data) {
alert("sucess");
}
});
});
</script>
and also either load
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
before your script tag or use
<script>
$(document).ready(function(){
$("#FORM_ID").submit(function() {
var name= $("#name").val();
var password= $("#password").val();
$.ajax({
type: "POST",
url: "insert.php",
data: "name=" + name+ "&password=" + password,
success: function(data) {
alert("sucess");
}
});
});
});
</script>
This is html form for insert data
<form id="frmrecord" method="post">
<input type="text" name="txtusermame" />
<input type="password" name="txtpassword" />
<input type="submit" value="Insert" />
</form>
Use this code for call insert.php file to insert data
jQuery(document).ready(function ($) {
$("#frmrecord").submit(function (event) {
event.preventDefault();
//validation for login form
$("#progress").html('Inserting <i class="fa fa-spinner fa-spin" aria-hidden="true"></i></span>');
var formData = new FormData($(this)[0]);
$.ajax({
url: 'insert.php',
type: 'POST',
data: formData,
async: true,
cache: false,
contentType: false,
processData: false,
success: function (returndata)
{
//show return answer
alert(returndata);
},
error: function(){
alert("error in ajax form submission");
}
});
return false;
});
});
After calling file you can receive data in php file Insert.php
<?php
$usernmae=$_POST['txtusername'];
$password=$_POST['password'];
$sql= mysqli_query($conn,"INSERT INTO insert_tbl(name,pass)
VALUES('".$usernmae."','".$password."')");
?>
Download Demo
You can use this ajax to insert data in database.
$(document).ready(function() {
//register
$("#register_btn").on("click", function() {
$("#register_btn").html(
'Please Wait ...'
);
$(".error").html("");
$.ajax({
type: "POST",
url: "register-submit.php",
dataType: "json",
data: $("#register_form").serialize(),
success: function(response) {
alert(response.mesage)
$("#register_btn").html("Sign Up");
},
error: function(error) {
console.log(error);
$("#register_btn").html("Sign Up");
},
});
});
})
At "register-submit.php" you will place your PHP code file name with path. you can check this tutorial for complete example.
Related
I have this jQuery AJAX code that into Mysql form php. It works without reloading the page. The problem is that it When the user enters something into the form, then clicks submit, I would like to use php and ajax (with jquery). But it do not print the string in alert() . Can someone please show me how this can be achieved?
HTML :
<form id="students" method="post">
<div class="row">
<input name="a[]" value="" type="text" >
<input name="b[]" value="" type="text" >
</div>
<div class="row">
<input name="a[]" value="" type="text" >
<input name="b[]" value="" type="text" >
</div>
<input type="submit" value="submit" id="submitbutton" class="insert"/>
</form>
<script type="text/javascript">
$('#students').submit(function(){
event.preventDefault();
$.ajax({
type: 'POST',
url: 'ajax_insert.php',
data: $('#students').serialize(),
dataType: 'JSON',
success: function(data) {
alert('form has been posted successfully');
}
});
});
</script>
and ajax_insert.php :
$a1=$_POST['a'];
$b1=$_POST['b'];
//$query_values = array();
$index=0;
foreach($a1 as $s){
$sql = "INSERT INTO test_data(a,b) VALUES('$s','".$b1[$index]."')";
$result = mysql_query($sql);
if($result)
{
echo "1";
}
$index++;
}
$('#students').submit(function(event){
event.preventDefault();
$.ajax({
type: 'POST',
url: 'ajax_insert.php',
data: $('#students').serialize(),
dataType: 'JSON',
success: function(data) {
alert('form has been posted successfully');
}
});
check official document here and learn how to use event.preventDefault();
You probably have to event.preventDefault(); in the submit event callback :
$('#students').submit(function(){
event.preventDefault();
$.ajax({
type: 'POST',
url: 'ajax_insert.php',
data: $('#students').serialize(),
dataType: 'JSON',
success: function(data) {
alert('form has been posted successfully');
}
});
});
You need return valid json when use dataType: "json" in $.ajax call
Or you can use dataType: "html" without rewriting php code
Update (examples of code, that should work):
in HTML:
<script type="text/javascript">
$('#students').submit(function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'ajax_insert.php',
data: $('#students').serialize(),
dataType: 'JSON',
success: function(data) {
if(data.result == 1) {
alert('form has been posted successfully');
} else {
alert(data.error);
}
}
});
});
</script>
ajax_insert.php
$a1=$_POST['a'];
$b1=$_POST['b'];
//$query_values = array();
$index=0;
$errors = array();
foreach($a1 as $s){
$sql = "INSERT INTO test_data(a,b) VALUES('$s','".$b1[$index]."')";
$result = mysql_query($sql);
if(!$result)
{
$errors[] = "\"$sql\"";
}
$index++;
}
if(!empty($errors)) {
echo json_encode(array('result'=>0,'error'=>"Error executing following queries: \n".implode("\n", $errors)));
} else {
echo json_encode(array('result'=>1));
}
How to echo value input type text when use ajax upload ?
This is my code for upload file to dir attachments_files and it's work good.
But i have some issue. I want to know how to echo value from id="username_uploader" in upload.php using php ?
i tried to use like this
echo $_POST['username_uploader'];
but not work. Please help me .
index.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input id="username_uploader" type="text" name="username_uploader" value="test_user"/>
<input id="attachment_file_input_id" type="file" name="sortpic" onchange="test_fn()"/>
<div id="demoajax"></div>
<script>
function test_fn () {
var file_data = $('#attachment_file_input_id').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'upload.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert("upload success");
$('#demoajax').append(php_script_response);
}
});
};
</script>
upload.php
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"], "attachments_files/" .$_FILES["file"]["name"]);
echo $_POST['username_uploader'];
}
?>
You need to include the username_uploader value in the FormData you send, as you currently omit it. Try this:
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('username_uploader', $('#username_uploader').val());
It would also be better practice for your PHP code to return JSON, that way you don't need to worry about the formatting or whitespace in the returned value. Here's a complete example:
function test_fn () {
var form_data = new FormData();
form_data.append('file', $('#attachment_file_input_id').prop('files')[0]);
form_data.append('username_uploader', $('#username_uploader').val());
$.ajax({
url: 'upload.php',
type: 'POST',
dataType: 'json',
cache: false,
processData: false,
data: form_data,
success: function(response){
alert("upload success");
$('#demoajax').append(response.uploader);
}
});
};
<?php
if (0 < $_FILES['file']['error']) {
echo json_encode(array('error' => 'Error: ' . $_FILES['file']['error'] . '<br>'));
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"], "attachments_files/" .$_FILES["file"]["name"]);
echo json_encode(array('uploader' => $_POST['username_uploader']));
}
?>
This is my ajax function
$(function(){
$("#myform").submit(function(){ //i want to get data from my form after submittingit
dataString = $("#myform").serialize();
alert(dataString);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/customer/viewCustomerData",
data: dataString,
success: function(data){
alert(data);
}
});
return false;
});
});
this is my controller class function
function viewCustomerData(){
if($_POST){
$name = $_POST['name'];
return 'name';
}
else {
return false;
}
}
other thing is i tried to alert data string taken from form serialize, but it also empty. I want to return data set from database after sending key word from javascript file. i tried if the javascript file connect correctly with my controller function. so i tried to return some value and display it using alert box. but it gives empty result.
This is better way to submit a form with ajax
$(document).on("submit", "#myform", function(event)
{
event.preventDefault();
$.ajax({
url: "<?php echo base_url(); ?>index.php/customer/viewCustomerData"
type: "POST",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
alert(data);
},
error: function (xhr, desc, err)
{
}
});
});
try this
$(function(){
$("#myform").submit(function(){
dataString = $("#myform").serialize();
alert(dataString);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/customer/viewCustomerData",
data: dataString,
cache: false,
datatype: 'json',
success: function(data){
alert(data.result);
}
});
});
});
in controller
function viewCustomerData(){
if($this->input->post('name'){
$result = $this->input->post('name');
} else {
$result = false;
}
header('Content-Type: application/json');
echo json_encode(array('result' => $result));
}
you cant alert $("#myform").serialize(); because this is an object instead of alert it try console.log($("#myform").serialize();)
then open browser console and see what is printed
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/customer/viewCustomerData",
data: dataString,
})
.done(function( data ) {
if ( console && console.log ) {
console.log( "Sample of data:", data);
}
});
I have a small question, which I guess in my opinion will sound stupid. I have actually this code
<script type="text/javascript">
$(document).ready(function(){
var email_value = prompt('Please enter your email address');
if(email_value !== null){
//post the field with ajax
$.ajax({
url: '="/new/cfolder.php',
type: 'POST',
dataType: 'text',
data: {data : email_value},
success: function(response){
//do anything with the response
console.log(response);
}
});
}
});
</script>
I would like to link it to my button which does this
<form action="/new/cfolder.php" method="post">
</font><input type="submit" value="Create Vdisk" class="myButton6" onClick="function()">
<br></form>
Is it actually possible to do this? thank you for any answer.
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click', '.myButton6', function(){
var email_value = prompt('Please enter your email address');
//post the field with ajax
if(email_value.length > 0){
$.ajax({
url: '/new/cfolder.php',
type: 'POST',
dataType: 'text',
data: {data : email_value},
success: function(response){
alert(response);
}
});
}
)};
});
</script>
try that way
// this is the id of the form
$("#idForm").submit(function() {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: '="/new/cfolder.php',
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
give your form an id
<form id="idForm" action="/Same/path/as/your/ajax/" method="post">
</font><input type="submit" value="Create Vdisk" class="myButton6" onClick="function()">
<br></form>
Yes of course you can do this . Like this code and you will have to include jquery1.9.0.js or above.
<script type="text/javascript">
$(document).ready(function(){
$("#myButton6").click(fuction(){
var email_value = prompt('Please enter your email address');
if(email_value !== null){
//post the field with ajax
$.ajax({
url: '/new/cfolder.php',
type: 'POST',
dataType: 'text',
data: {data : email_value},
success: function(response){
//do anything with the response
console.log(response);
}
});
}
});
});
</script>
I would like to link it to my button which does this
</font><input type="submit" value="Create Vdisk" class="myButton6" id="myButton6">
<br>
I'm not sure why I'm not able to post the content of email field,
here is my code.
<html>
<head>
<title></title>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
</head>
<body>
<input type="text" id="email" name="email">
<input type="button" id="submit" name="submit" value="submit">
</body>
<script type="text/javascript">
$(document).ready(function () {
$('#submit').click(function (event) {
var email = $('#email').val();
console.log(email),
$.ajax({
url: 'db.php',
type: 'POST',
data: 'email=' + 'email',
success: function (data) {
console.log(data);
}
})
});
});
</script>
</html>
backend file "db.php"
<?php
$email = $_POST['email'];
echo "$email";
I'm able to console.log email, and displays correctly, before it gets submitted to db.php.
console log returns "email" only.
Not sure whats wrong, your help is highly appreciated.
Thanks
You are sending string "email", while you want to send a variable value:
$.ajax({
url: 'db.php',
type: 'POST',
data: 'email=' + email, // or data: {email: email}
success: function (data) {
console.log(data);
}
});
Use this it will help
<script type="text/javascript">
$(document).ready(function () {
$('#submit').click(function (event) {
var email = $('#email').val();
console.log(email),
$.ajax({
url: 'db.php',
type: 'POST',
data: {email: email},
success: function (data) {
console.log(data);
}
})
});
});
</script>