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));
}
Related
I'm using ajax insert and fetch the data from the database, insert is working perfectly but fetching part is not working give a feedback to fix this issues.
<script>
$(document).ready(function(){
$("#button").click(function(e){
e.preventDefault();
var postId=$("#postId").val();
var userId=$("#userId").val();
var postComm=$("#postComments").val();
$.ajax({
url:'../validate/inserPostComm.php',
method:'POST',
data:{
poId:postId,
usId:userId,
poco:postComm
},
success:function(data){
//alert(data);
displayFromDatabase();
$("#postComments").val('');
}
});
});
});
function displayFromDatabase(){
var postId=$("#postId").val();
alert(postId);
$.ajax({
url: "../validate/getComments.php",
type: "POST",
async: false,
data: {
poId:postId,
},
success: function(data){
('#display_area').html(data);
}
});
}
</script>
and this my html code to retrieve the fetching details from database.
<li>
<div id="display_area">
</div>
</li>
<button type="button" id="button"><i class="fa fa-paper-plane"></i></button>
and also i attached my php code through the ajax i'm passing the id and i'm get the details according to the id.
$postId=$_POST["poId"];
$getPostCom=$postComments->getPostComm($postId,"../");
while($PostComments=mysqli_fetch_assoc($getPostCom))
{
?>
<div class="comet-avatar">
<img src="<?php echo $PostComments["u_image"]; ?>" alt="">
</div>
<div class="we-comment">
<div class="coment-head">
<h5><?php echo $PostComments["u_fname"]; ?> <?php echo $PostComments["u_lname"]; ?></h5>
</div>
<p><?php echo $PostComments["p_comments"]; ?></p>
</div>
<?php
}
exit();
?>
Yes this code working perfectly but i missed the $ in the success block.
<script>
$(document).ready(function(){
$("#button").click(function(e){
e.preventDefault();
var postId=$("#postId").val();
var userId=$("#userId").val();
var postComm=$("#postComments").val();
$.ajax({
url:'../validate/inserPostComm.php',
method:'POST',
data:{
poId:postId,
usId:userId,
poco:postComm
},
success:function(data){
//alert(data);
displayFromDatabase();
$("#postComments").val('');
}
});
});
});
function displayFromDatabase(){
var postId=$("#postId").val();
alert(postId);
$.ajax({
url: "../validate/getComments.php",
type: "POST",
async: false,
data: {
poId:postId,
},
success: function(data){
$('#display_area').html(data);
}
});
}
</script>
The code works on until I reach the action.php where I post my input. The issue is that the Post never reaches the action.php and all I get is a blank variable.
using: https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js
<script type="text/javascript">
function submitdata()
{
var name=document.getElementById('name');
$.ajax({
type: 'post',
url: 'action.php',
data: {
'name':name
},
cache:false,
success: function (data) {
$('#msg').html(data);
}
});
return false;
}
</script>
<form onsubmit="return submitdata();">
<input type="text" name="name">
<input type="submit" value="Check">
</form>
<p id="msg"></p>
action.php:
<?php
$name=$_POST['name'];
echo "Response: ".$name;
?>
EDIT:
Fixed it by adding:
var name=document.getElementById('name').value;
and
input type="text" id="name" instead of name="name"
Your "name" is DOM object. To get value use:
var name=document.getElementById('name').value;
You now submit not a string, but Object and this may be the reason why it fails.
Try to add the dataType on your ajax request
make it 'text'
$.ajax({
type: 'post',
url: 'action.php',
dataType: 'text',
data: {
'name':name
},
cache:false,
success: function (data) {
$('#msg').html(data);
}
});
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.
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 what has gone wrong, but for some reason the success function in Ajax isn't calling the function. I'm asking it to call after the PHP is completed.
For the PHP I have $test = 'Hi'; echo json_encode($test);
Here is my code for the main page:
<?php
session_start();
if(!isset($_SESSION["b2_in"])){
header("Location: b2.php");
}
?>
<script>
$(document).ready(function(){
$("form input:submit").click(function() {
$.ajax({
type: "POST",
url: 'b2_send.php',
data: $('form').serialize(),
dataType: 'json',
//beforeSend: function(){ $("#send").val('Sending...');},
success: function(data) {
TestFunction();
},
statusCode: {
403: function(e) {
$("say").highlight();
$("#message").html(e.responseText);
}
}
});
return false;
});
});
function TestFunction(){
$("#message").val("");
}
</script>
<say>
<form>
<input type="text" name="message" class="Message" id="message"/>
<input type="submit" name="send" value='Say' id="send"/>
<span id="message" style="font-weight:bold;color:red;"></span>
</form>
</say>
Try this
span is a block element of DOM and hence to set data to it, you need to use $(id).html(data); and not val()
Also you should have different id for each elemnt in the dom, it always pick the first id that it gets in the dom, and in your case it is
<input type="text" name="message" class="Message" id="message"/> so it will change the value of this element
<script>
$(document).ready(function(){
$("form input:submit").click(function() {
$.ajax({
type: "POST",
url: 'b2_send.php',
data: $('form').serialize(),
dataType: 'json',
//beforeSend: function(){ $("#send").val('Sending...');},
success: function(data) {
TestFunction();
},
statusCode: {
403: function(e) {
$("say").highlight();
$("#message").html(e.responseText);
}
}
});
return false;
});
});
function TestFunction(){
$("#message").html("");
}
</script>