how to insert value in database using php, jquery and ajax - php

I am struggling very hard to get this to work and I don't know what I'm doing wrong. I have a register page that I want to take the data inserted into the form and INSERT it to the database with jQuery and AJAX. I'm not very experienced with AJAX AND jQuery so be gentle! :P I will show you the files that I have...this is a msg.php page when i have submit data sometimes post submit in database`
mostly not so i want to know that why it s happening i am new in this field
<?
php $id=$_GET['id'];
$id1=$_SESSION['id'];
?>
<form method="post" class="msgfrm" id="msgfrm">
<input type="hidden" value="<?php echo $_GET['id']; ?>" name="rcvrid" id="rcvrid">
<input type="hidden" name="senderid" id="senderid" value="<?php echo $id1;?>" >
<div class="msgdiv" id="chatbox"></div>
<div class="textdiv">
<input type="text" name="msg" id="msg" class="textmsg">
<input type="submit" value="Send" onClick="sendChat()">
</div>
</form>
function sendChat()
{
$.ajax({
type: "POST",
url: "msg_save.php",
data: {
senderid:$('#senderid').val(),
rcvrid:$('#rcvrid').val(),
msg: $('#msg').val(),
},
dataType: "json",
success: function(data){
},
});
}
msg_save.php file
<?php
require_once('include/util.php');
$rcvrid=$_POST['rcvrid'];
$senderid=$_POST['senderid'];
$msg=$_POST['msg'];
$sql="insert into message(rcvrid,senderid,msg) values($rcvrid,$senderid,'$msg')";
mysql_query($sql);
?>

$.ajax({
type: "POST",
url: "msg_save.php",
data: " senderid="+$('#senderid').val()+"rcvrid="+$('#rcvrid').val()+"msg="+$('#msg').val(),
dataType: "json",
success: function(data){
},
});
please try this code and send data ,and use post method in php to get data,it will work

if you are trying chat application check this, it is old but just for idea:
http://www.codeproject.com/Articles/649771/Chat-Application-in-PHP
use mysqli_query instead of mysql_query recommended
<?php
$id=$_GET['id'];
//$id1=$_SESSION['id']; COMMENTED THIS AS I AM NOT IN SESSION. HARDCODED IT IN THE FORM AS VALUE 5
?>
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
<form method="post" class="msgfrm" id="msgfrm">
<input type="hidden" value="<?php echo $_GET['id']; ?>" name="rcvrid" id="rcvrid">
<input type="hidden" name="senderid" id="senderid" value="5" >
<div class="msgdiv" id="chatbox"></div>
<div class="textdiv">
<input type="text" name="msg" id="msg" class="textmsg">
<input type="submit" value="Send" >
</div>
</form>
<script>
$("#msgfrm").on("submit", function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "msg_save.php",
data: $(this).serialize(),
success: function(data) {
$("#chatbox").append(data+"<br/>");//instead this line here you can call some function to read database values and display
},
});
});
</script>
</body>
</html>
msg_save.php
<?php
//require_once('include/util.php');
$rcvrid = $_POST['rcvrid'];
$senderid = $_POST['senderid'];
$msg = $_POST['msg'];
echo $rcvrid.$senderid.$msg;
$con = mysqli_connect("localhost", "root", "", "dummy");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "insert into message(rcvrid,senderid,msg) values($rcvrid,$senderid,'$msg')";
mysqli_query($con,$sql);
mysqli_close($con);
echo "successful"
?>

check that whether you have inserted jquery file or not.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
Then include your function sendChat() inside <script> tags.

On submit button
<button type="submit" id="button">SAVE</button>
<script>
$(document).ready(function(){
$("#button").click(function(){
var firstname=$("#firstname").val();
var lastname=$("#lastname").val();
var email=$("#email").val();
$.ajax({
url:'dbConfigAndInsertionQuery.php',
method:'POST',
data:{
firstname:firstname,
lastname:lastname,
email:email
},
success:function(data){
alert(data);
}
});
});
});
</script>

Related

PHP POST data array is empty

I am using HTML, PHP and AJAX to create a search field.
Here is my HTML Code:
<form action="search.php" id="search_form" method="post" >
<div class="search_bar">
<input type="text" name="search_text" id="search_text" placeholder="Search anything" >
</div>
<div class="search_button">
<button type="submit" id="search_button" name="search_submit" >Search</button>
</div>
</form>
This is my AJAX Code:
$('#search_button').click(function(event) {
var search_data = $('#search_text').val();
var postData ={
"content":search_data};
event.preventDefault();
$.ajax({
type: 'POST',
url: 'search.php',
data:{myData: postData},
error: function()
{
alert("Request Failed");
},
success: function(response)
{
alert("Success");
}
});
});
In PHP I tried the following:
$obj = $_POST['myData'];
echo $obj;
print_r($_POST);
All I am getting is:
Notice: Undefined index: myData in C:\xampp\htdocs\workspace\MakeMyApp\WebContent\search.php on line 9
Array ( )
I have also tried with:
file_get_contents('php //input')
but there also I am getting empty array. I don't know what exactly the problem is. Am I missing anything?
Sorry, I can't comment as I don't have enough 'reputation'.
I have tried to replicate your issue and it seems to work ok for me.
Here is the HTML page ...
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#search_button').click(function(event) {
var search_data = $('#search_text').val();
var postData ={
"content":search_data};
event.preventDefault();
$.ajax({
type: 'POST',
url: 'search-submit.php',
data:{myData: postData},
error: function()
{
alert("Request Failed");
},
success: function(response)
{
alert(response);
}
});
});
});
</script>
</head>
<body>
<form action="search.php" id="search_form" method="post" >
<div class="search_bar">
<input type="text" name="search_text" id="search_text" placeholder="Search anything" >
</div>
<div class="search_button">
<button type="submit" id="search_button" name="search_submit" >Search</button>
</div>
</form>
</body>
</html>
And this is the receiving PHP page
<?php
echo '<pre>';
print_r($_POST);
echo '</pre>';
?>
In the ajax request, you can see I'm using alert to output the response in an alert but, and if all goes well it should output the content outputted by the receiving PHP page.
Also, it may not help much, but his is how I would have done the ajax request; it's slightly less code and you don't have to define each form field individually (if you have more than one field)
$(document).ready(function(){
$('#search_form').submit(function() {
var formData = $(this).serialize();
$.ajax({
type: 'POST',
url: 'search-submit.php',
data: formData,
error: function()
{
alert("Request Failed");
},
success: function(response)
{
alert(response);
}
});
return false;
});
});

file is not uploading in ajax php mysql

I am trying to upload a file using ajax which is giving me an error and the rest of data upload successfully i have try without ajax the file is uploading but when i try to upload file via ajax it give me error i am totally confuse why ajax is giving me the problem.here is my code.
<html>
<head>
<script src="jquery-1.8.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#button").click(function(){
var form_data = $('#reg_form').serialize();
$.ajax({
type:"POST",
url:"process.php",
data:form_data,
success: function(data)
{
$("#info").html(data);
}
});
});
});
</script>
</head>
<body>
<form id="reg_form" enctype="multipart/form-data" method="post" action="">
name : <input type="text" name="name" id="name"/>
</br>
message : <input type="text" name="message" id="message" />
</br>
Image : <input type="file" name="file" id="file" />
<input type="button" value="Send Comment" id="button">
<div id="info" />
</form>
</body>
</html>
The process.php file coding is here.
<?php
mysql_connect("localhost","root","");
mysql_select_db("ajaxdatabase");
$name=$_POST["name"];
$message=$_POST["message"];
//storing file in filename variable
$fileName = $_FILES['file']['name'];
//destination dir
$to="image/".$fileName;
move_uploaded_file($_FILES['file']['tmp_name'],$to);
$query=mysql_query("INSERT INTO common(name,message,destination) values('$name','$message','$to') ");
if($query){
echo "Your comment has been sent";
}
else{
echo "Error in sending your comment";
}
?>
First of all serialize() function don't work for file you should have to make an object of form through which you can post the data and will work perfectly I had the same problem and I have just resolved your issue and is working 100% because I have tested this. Please check out.
The form.
<form name="multiform" id="multiform" action="process.php" method="POST" enctype="multipart/form-data">
name : <input type="text" name="name" id="name"/>
</br>
message : <input type="text" name="message" id="message" />
</br>
Image : <input type="file" name="file" id="file" />
</form>
<input type="button" id="multi-post" value="Run Code"></input>
<div id="multi-msg"></div>
The script.
<script type="text/javascript">
$(document).ready(function(){
$("#multiform").submit(function(e)
{
var formObj = $(this);
var formURL = formObj.attr("action");
if(window.FormData !== undefined)
{
var formData = new FormData(this);
$.ajax({
url: formURL,
type: 'POST',
data: formData,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
success: function(data, textStatus, jqXHR)
{
$("#multi-msg").html('<pre><code>'+data+'</code></pre>');
},
error: function(jqXHR, textStatus, errorThrown)
{
$("#multi-msg").html('<pre><code class="prettyprint">AJAX Request Failed<br/> textStatus='+textStatus+', errorThrown='+errorThrown+'</code></pre>');
}
});
e.preventDefault();
e.unbind();
}
});
$("#multi-post").click(function()
{
//sending form from here
$("#multiform").submit();
});
});
</script>
And your php file is the same I have tested and is working.
<?php
mysql_connect("localhost","root","");
mysql_select_db("ajaxdatabase");
$name=$_POST["name"];
$message=$_POST["message"];
//storing file in filename variable
$fileName = $_FILES['file']['name'];
//destination dir
$to="image/".$fileName;
move_uploaded_file($_FILES['file']['tmp_name'],$to);
$query=mysql_query("INSERT INTO common(name,message,destination) values('$name','$message','$to') ");
if($query){
echo "Your comment has been sent";
}
else{
echo "Error in sending your comment";
}
?>

Send input value to php using ajax with result printed to div

I'm trying to send an input value to a php script and have the returned value posted to a div, using ajax, but I can't seem to get this right. Any help/suggestions would be appreciated. Thanks!!
This is what I have by now, but console says: "Failed to load resource: the server responded with a status of 404 (Not Found)".
test1.php:
<script>
$.ajax({
type: 'POST',
url: 'test2.php',
data: {url: $('#id1').val()},
success: function (data)
{
$(document).ready(function(){$("#content").load("test2.php");});
}
});
</script>
<form name="input">
<input type="text" id="id1">
<input type="submit">
</form>
<div id="content"></div>
test2.php:
<?php
$string=$_POST['id1'];
require_once('connect.php');
$inf = "SELECT * FROM `comments` WHERE date='$string'";
$info = mysql_query($inf);
while($info2 = mysql_fetch_object($info)) {echo $info2->username.$info2->date;}
?>
<script>
$(document).ready(function() {
$('#submit').click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'test2.php',
data: {id1: $('#id1').val()},
success: function(data)
{
$("#content").html(data);
}
});
});
});
</script>
<form name="input">
<input type="text" id="id1">
<input type="submit" id="submit">
</form>
<div id="content"></div>
When you submit the ajax request, you're already submitting your content to test2.php, so you don't need to load it again. In the success function, you can append the result to the div from the callback.
$(document).on('click','#submit',function(e) {
e.preventDefault();
$.post('test2.php',{url: $('#id1').val()},function(data){
$("#content").html(data);
}
});
});
404 (Not Found) Error is for page not found. Please make sure that file test2.php is exist in same folder. Check url.
Also you can copy the URL from console and paste it in the browser URL to check the url correct or incorrect.
jQuery
<script>
$(document).ready(function() {
$('#submit').click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'test2.php',
data: {id1: $('#id1').val()},
success: function(data)
{
$("#content").html(data);
}
});
});
});
</script>
HTML
<form name="input">
<input type="text" id="id1">
<input type="submit" id="submit">
</form>
You could try this:
<script>
$('#submitBtn').on('click',function(){
$.ajax({
type: 'POST',
url: 'test2.php',
data: {url: $('#id1').val()},
success: function (data)
{
$("#content").html(data);
}
});
return false;
});
</script>
<form name="input">
<input type="text" id="id1">
<input id="submitBtn" type="submit">
</form>
<div id="content"></div>

Submit an AJAX FORM from within an AJAX Success

I need to perform another AJAX Form Post from within the first forms success function.
Example, this does 2 AJAX requests.
Search Movie => Pick Movie Wanted => View Specific Movie Details
I am able to load the results into a div <div id="results"></div> just fine but once I select a movie title it isnt performing another AJAX Request, the request goes to the main window.
Here is the initial search page that handles the results.
<script type="text/javascript">
$(document).ready(function(){
$("#searchtitle").submit(function() {
var id = $(this).children('input[name="thetitle"]').attr('value');
$.ajax({
type: "POST",
url: "s.php",
data: $('#searchtitle').serialize(),
cache: false,
success: function(data){
$('#status').html(data);
}
});
return false;
});
});
</script>
<form id="searchtitle">
<input type="text" name="thetitle" />
<input type="submit" name="submit" class="button expand postfix" value="Search" />
</form>
<div id="status"></div>
s.php which returns results within #results
<?php
if(empty($_POST['thetitle'])) {
?>
<div class="alert-box error">
<div class="alert-error"></div>
Error: Nothing Found
</div>
<?php
}
if(!empty($_POST['thetitle'])) {
$myid = strtoupper($_POST['thetitle']);
$searchReults = $tmdb_V3->searchMovie($myid,'en');
?>
<?php
foreach($searchReults['results'] as $result) {
?>
<form class="sform">
<input type="hidden" name="mid" value="<?php echo $result['id']); ?>" />
<h5><?php echo $result['title']; ?></h5>
<span class="mreleased">Year: <?php echo $result['year']; ?></span>
<input type="submit" class="button" value="Select">
</form>
<?php
}
}
?>
This is the code that will post the results from s.php
<script type="text/javascript">
$(".sform").submit(function () {
$.ajax({
type: 'POST',
url: 'sx.php',
data: $(this).closest("form").serialize();
success: function (response) {
$('#status').load(response);
$('#status').find('script').each(function (i) {
eval($(this).text());
});
}
});
return false;
}
</script>
I have tried putting this within s.php, within the bottom of the initial search page, in the head of the initial page and no luck, it submits fine just not the sx.php where it should.
In s.php the statement:
<input type="hidden" name="mid" value="<?php echo $result['id']); ?>" />
Should be:
<input type="hidden" name="mid" value="<?php echo $result['id']; ?>" /> //remove extra bracket
In your javascript code in s.php there are some typos:
data: $(this).closest("form").serialize(); // here should be comma not semicolon
After return false you should close the script properly } should be });.
And since you are trying to submit the dynamic content $(".sform").submit(function () will not work. You should use on for dynamic contents. So the correct script would be:
<script type="text/javascript">
$(document).on('submit', '.sform', function () {
$.ajax({
type: 'POST',
url: 'sx.php',
data: $(this).closest("form").serialize(),
success: function (response) {
$('#status').load(response);
$('#status').find('script').each(function (i) {
eval($(this).text());
});
}
});
return false;
});
</script>
I have checked and verified in my localhost (with a simple setup). It is making both ajax request. Hope this helps!

Get the textbox Text using ajax on button click

I want a code for get textbox value when submit button is clicked. It must be Ajax.Here is the code I tried so far.But I culdent get to work....
<form action="" method="post">
<p>Route No :
<input type="text" name="route_no" required="required" />
<input type="submit" value="Search" name="search" />
</form>
Ajax Code
<script type="text/javascript">
$(document).ready(function() {
$("#sub").click(function() {
var textboxvalue = $('name or id of textfield').val();
$.ajax({
type: "POST",
url: 'ajaxPage.php',
data: {txt1: textboxvalue},
success: function(result) {
$("div").html(result);
}
});
});
});​
</script>
PHP code
$txt = null;
if((isset($_POST)) && (isset($_POST['txt1'])))
{
echo $txt = $_POST['txt1'];
}
HTML:
<label for="route_no">Route No:</label><input type="text" id="route_no" name="route_no" required="required" />
<input type="button" value="Search" id="search" />
<div id="result"></div>
JavaScript:
$(document).ready(function()
{
$("#search").click(function()
{
var textboxvalue = $('input[name="route_no"]').val();
$.ajax(
{
type: "POST",
url: 'ajaxPage.php',
data: {txt1: textboxvalue},
success: function(result)
{
$("#result").html(result);
}
});
});
});​
ajaxPage.php:
if(isset($_POST) && isset($_POST['txt1']))
{
echo $_POST['txt1'];
}
You have problem here
$("#sub").click(function() {
you are using id ="sub" for submit button but you are not assigning id to that button so give id to submit button as id="sub".
To get the value of the textbox you can use:
$('#elementid').val()

Categories