save dynamic records in DB using Php, Ajax, JSON - php

I have a table each row contain fields for 1 DB record
table rows are dynamically added and removed
I want to send all text boxes data to a php file using ajax
table is below
<table id="tblDmc" frame="box" rules="all" width="100%">
<tr>
<th>Subject</th><th>Total Marks</th><th>Obtained</th><th>Class Highest</th><th>Remarks</th><th> </th>
</tr>
<tr class="subRecord">
<td><input type="text" class="dmcTxt subject"></td>
<td><input type="number" class="dmcTxt total"></td>
<td><input type="number" class="dmcTxt obtained"></td>
<td><input type="number" class="dmcTxt highest"></td>
<td><input type="text" class="dmcTxt remarks"></td>
<td><a href="#" class="removeRow">x<a></td>
</tr>
</table>
Jquery Ajax code
$("#btnSave").click(function(){
var data1 = [];
var stdRow = {"s_id":$("#drpClass").val(),"month":$("#drpMonth").val(),"percent":$("#percentage").val(),"grade":$("#grade").val(),"position":$("#position").val(),"curricular":$("#curricular").val()};
data1.push(stdRow);
$("#tblDmc .subRecord").each(function(){
if($(this).find(".subject").val()!="")
{
var rowData = {};
rowData["subject"] =$(this).find(".subject").val();
rowData["total"] =$(this).find(".total").val();
rowData["obtained"] =$(this).find(".obtained").val();
rowData["highest"] =$(this).find(".highest").val();
rowData["remarks"] =$(this).find(".remarks").val();
data1.push(rowData);
}
});
//$(this).after(JSON.stringify(data1));
$.ajax({
url:'savedmc.php',
type:'POST',
data: JSON.stringify(data1),
contentType: "application/json; charset=UTF-8",
success: function(e){
alert(e);
}
});
});
JSON.stringify(data1) returns the following
[
{"std_id":"6","month":"4","percent":"77","grade":"1","position":"33","curricular":"abc"},
{"subject":"Maths","total":"100","obtained":"99","highest":"100","remarks":"remarks"},
{"subject":"Physics","total":"100","obtained":"94","highest":"99","remarks":"emarks"}
]
code in savedmc.php is
<?php print_r($_POST); ?>
which returns NULL array()
My question is how to send the above json object/array to php file via ajax,
or any alternative?

Replace the ajax call in your JS code with this version:
$.ajax({
url:'savedmc.php',
type:'POST',
dataType: "json",
data: JSON.stringify(data1),
contentType: "application/json; charset=UTF-8",
success: function(e){
alert(e);
}
});

Related

Cannot able to fetch data from ajax to php page

I design a simple page were user can put name, password and image using html.
I try to sent those data using ajax to specific php page, but I cannot implement this.
how I do this thing
Html code
<?php include('connection.php'); ?>
<form id="form" enctype="multipart/form-data">
<table>
<tr>
<td>Name:</td>
<td><input type="name" id="name"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" id="pass"></td>
</tr>
<tr>
<td>Photos:</td>
<td><input type="file" id="photos"></td>
</tr>
<tr>
<td><input type="submit" id="go"></td>
</tr>
</table>
</form>
Jquery and ajax
<script>
$(document).ready(function(){
$('#go').click(function(){
var img_name = $('#img_name').val();
var name = $('#name').val();
var pass = $('#pass').val();
$.ajax({
type : "POST",
url : "singup_submit.php",
data : { img_name:img_name, name:name, pass:pass},
success : function(done){
alert(done);
}
});
});
});
</script>
Php code
<?php
include('connection.php');
if(isset($_POST)){
$name = $_POST['name'];
$pass = $_POST['pass'];
$img_name=$_FILES['img_name']['name'];
$qr="INSERT INTO data (name,pass,img_name) VALUES ('$name','$pass','$img_name')";
$ex=mysqli_query($con,$qr) or die(mysqli_error($con));
if($ex==1)
echo 'done';
else
echo 'not done';
}
Follow this code ..It may help you
<script>
$(document).ready(function(){
$("#go").click(function(){
var name = $("#name").val();
var pasword = $("#password").val();
var photos = $("#photos").val();
if(name==''||pass==''||photos==''){
alert("Please Fill All Fields");
}
else{
$.ajax({
type : "POST",
url : "singup_submit.php",
data : formData,
cache : false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
</script>
you are not sending any file in your ajax request.
$(document).ready(function(){
$("#go").on('submit',function(e){
e.preventDefault()
$.ajax({
url: 'singup_submit.php',
type: 'POST',
data: new FormData(this),
contentType: false,
processData: false,
success: function(response){
alert(done);
},
error: function(data){
console.log("error");
console.log(data);
}
},
});
});
});
and then take data from global variables in php as you are doing now.
and please assign name to your form fields like so
<form id="form" enctype="multipart/form-data">
<table>
<tr>
<td>Name:</td>
<td><input type="name" name="name" id="name"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" id="pass"></td>
</tr>
<tr>
<td>Photos:</td>
<td><input type="file" name="img" id="photos"></td>
</tr>
<tr>
<td><input type="submit" name="submit" id="go"></td>
</tr>
</table>
</form>
and it should work.

PHP AJAX JSON - Convert Input to JSON and Other PHP File Get The Value

I noob and get mad when submit php form, convert input value to json, and other php file get it.
html
<form action="submit.php" method="post" name="form1" id="myform">
<table width="100%" border="0" style="font-size: 65px;">
<tr>
<td>Name</td>
<td><input type="text" name="name" id="name"></td>
</tr>
<tr>
<tr>
<td></td>
<td><button id="submit">Submit</button></td>
</tr>
</table>
</form>
<script src="script.js"></script>
script.js
$('#myform').submit(function (event) {
name = $('#name').val();
var data = {
name: name
}
$.ajax({
type: "POST",
url: 'submit.php',
contentType: 'application/json',
data: JSON.stringify(data),
dataType: 'json'
});
return false
});
php file
header('Content-Type: application/json');
$name_dirty = json_decode($_POST['name']);
echo $name_dirty;
Can someone help me? submit.php got blank, I cant get the value that I submit from html page. Big Thanks
Your Html
<table width="100%" border="0" style="font-size: 65px;">
<tr>
<td>Name</td>
<td><input type="text" name="name" id="name"></td>
</tr>
<tr>
<tr>
<td></td>
<td><button id="submit">Submit</button></td>
</tr>
</table>
<script src="script.js"></script>
Your JS
$('#submit').click(function() {
name = $('#name').val()
var data = {
name: name
}
$.ajax({
type: "POST",
url: 'submit.php',
data: data
dataType: 'json'
complete: function (resultData) {
alert('data has been send')
})
})
In your php:
<?php
print_r($_POST['data'])
A few notes. Make sure you check your paths. In my answer i assumed that the problem is in the code and not in wrong paths. Also when you use form tag you can use a submit button like <input type="submit" value="Submit"> to submit your form without using Javascript. It would work in your case but it's just another way to tackle your issue.
In my answer i removed your form tags and triggered the action on button click. There will be no redirect to the page but you can set a redirect inside the js if it is important to you, on success function of the ajax that i added. At the moment i just throw an alert message when it works successfully.

Dynamically generated ajax data Post from jQuery to PHP

I have a table that generating dynamic raw's, I need to send through ajax post to receive from PHP. Below I have given all my selected codes, this is not working.
In console showing as
PHP ERROR: Undefined index all_ch_no, all_yd_stock_no, all_comments
HTML FORM, below table rows are dynamically generated through ajax, if I place static table data, then it's working! How can I solve?
<form method="post" id="customer_do_add">
<input type="text" id="phone_no" name="phone_no">
<table class="table" id="group_cars">
<thead>
<tr>
<th style="width: 20%;">Chassis No</th>
<th style="width: 15%;">Yard Stock No</th>
<th style="width: 50%;">Comments</th>
<th style="width: 15%;">Remove</th>
</tr>
<tr>
<td><input type="text" class="waz" value="DD51T-224534" name="all_ch_no[]"></td>
<td><input type="text" class="waz" value="77832" name="all_yd_stock_no[]"></td>
<td><input type="text" class="waz" value="Test3" name="all_comments[]"></td>
</tr>
<tr>
<td><input type="text" class="waz" value="DD51T-45354" name="all_ch_no[]"></td>
<td><input type="text" class="waz" value="123123" name="all_yd_stock_no[]"></td>
<td><input type="text" class="waz" value="Test" name="all_comments[]"></td>
</tr>
...
</thead>
</table>
</form>
jQuery:
$('#customer_do_add').on('submit', function(e) {
e.preventDefault();
var val = $('#customer_do_add').serializeArray();
$.ajax({
url: "auction/customer_do_add/",
data:val,
type: "POST",
success: function (responseText, statusText, xhr, $form) {
result = $.parseJSON(responseText);
}
});
return false;
});
PHP
public function customer_do_add(){
print_r($_POST);
exit;
}
Printing Only Phone number, Arrays are not printing
Array
(
[phone_no] => 123456
)
Send data params in Jquery call then only you can receive post
$('#customer_do_add').on('submit', function(e) {
e.preventDefault();
var val = $('#customer_do_add').serializeArray();
$(this).ajaxSubmit({
url: "auction/customer_do_add/",
data: val,
success: function (responseText, statusText, xhr, $form) {
result = $.parseJSON(responseText);
}
});
return false;
});
Your $_POST is empty because jQuery.ajax() will pass data as GET data (it's being appended to the url). Setting the method arg to post will fix this.
$.ajax({
url: "/auction/customer_do_add/",
data: val,
success: function (data) {
console.log(data);
},
dataType: 'json',
method: 'POST',
});
You could also use jQuery.post() for a simplified syntax;
$.post({
url: "/auction/customer_do_add/",
data: val,
success: function (data) {
console.log(data);
},
dataType: 'json'
});

jquery ajax return full page content

at the first , excuse me for my bad english
i working in ubuntu for a jquery/ajax system
my codes in below:
index.html
...
<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
</head>
<body>
<form name="stuSelForm" id="stuSelForm">
<table id="inputTable">
<tr><td colspan="3" align="center">Stu From</td></tr>
<tr>
<td> </td>
<td>St No : </td>
<td><input type="text" name="StNo" id="StNo" /></td>
</tr>
<tr>
<td></td>
<td>name : <br/> family : </td>
<td><input type="text" name="Fname" id="Fname" /><br/><input type="text" name="Lname" id="Lname" /></td>
</tr>
<tr>
<td colspan="3" align="right"><input type="submit" id="send" name="send" value="show" /></td>
</tr>
</table>
</form>
</body>
<script type="text/javascript" src="js/jscodes.js"></script>
...
js file :
$(document).ready(function()
{
$('#stuSelForm').submit(function(event)
{
var form = $(this);
inputs = form.find("input");
serializedData = form.serialize();
inputs.attr("disabled","disabled");
$.ajax({
url:'process.php',
type:'POST',
data: serializedData,
dataType:'text',
cache: false,
success : function(data,textStatus,jqXHR){ alert(data); },
error : function(jqXHR,textStatus,errorThrown) { alert(textStatus+jqXHR.status+jqXHR.responseText+"..."); },
complete : function(jqXHR,textStatus)
{
inputs.removeattr("disabled");
}
});
event.preventDefault();
});
});
and process.php :
<?php
header("Content-Type: text/html");
$StNo = $_POST['StNo'];
echo $_POST['StNo'];
?>
now all things are ok but the return value isn't StNo
it is whole content of process.php
it's mean
please help me why this happen
are this for php extensions or a mistake from me or ...
tanx for ur help
It sounds like the php is not running. Are you running your HTML file which calls the php file through localhost / a server or directly from the directory? You need the php server to evaluate your php script.
problem in your header:
you write in jquery dataType: text but you write in php header("Content-Type: text/html");
change it for get success:
like this:
$.ajax({
url:'process.php',
type:'POST',
data: serializedData,
cache: false,
success : function(data,textStatus,jqXHR){ alert(data); },
error : function(jqXHR,textStatus,errorThrown) { alert(textStatus+jqXHR.status+jqXHR.responseText+"..."); },
complete : function(jqXHR,textStatus){inputs.removeattr("disabled");}
});
I remove dataType:, because jquery default settings is dataType:'html'
and you don't need write dataType in this case

Update record without refresh all page on my site

How can updating record without refreshing page, I have a system where I want to up date a record, change its status between 0 and 1, to turn a feature on or off. This is my form to turn it on or off:
<table class="tablesorter" cellspacing="0">
<thead>
<tr>
<th></th>
<th>nane</th>
<th>time</th>
<th>out</th>
<th>enter</th>
<th>
<div align="center">admin</div>
</th>
<th></th>
</tr>
</thead>
<tbody>
<?php $qu_req=mysql_query( "select * from `exit_request` where `date`='$date_now' order by id desc "); while($row_req=mysql_fetch_row($qu_req)){ ?>
<tr>
<td>
<input type="checkbox">
</td>
<td><?php print($row_req[1]); ?>
</td>
<td>
<?php print($row_req[2]); ?>
</td>
<td>
<?php print($row_req[6]); ?>
</td>
<td>
<?php print($row_req[7]); ?>
</td>
<td>
<div align="center">
<input name="<?php print(" chk_exit ".$row_req[0]); ?>" type="radio" value="0" <?php if($row_req[3]==0){print( 'checked');} ?>/>
<label>accept</label>
<input name="<?php print(" chk_exit ".$row_req[0]); ?>" type="radio" value="1" <?php if($row_req[3]==1){print( 'checked');} ?>/>
<label>not acept</label>
</div>
</td>
<td>
<input class="alt_btn" name="send" type="submit" value="رد الادارة" />
</td>
</tr>
<? } ?>
</tbody>
</table>
code of update
if(isset($_POST['send'])){
$qu=mysql_query("select * from `exit_request` ");
while($row=mysql_fetch_row($qu)){
$id=$row[0];
$chk_str="chk_exit".$id;
$chk_str=$$chk_str;
//if($chk_str==1)
mysql_query("update `exit_request` set `accept`='$chk_str' where id=$id");
print('<meta http-equiv="refresh" content="0;URL=index.php" />');
}
}
http://api.jquery.com/jQuery.ajax/
You can use AJAX request to post your form serialized content as seen in many many tutorials about AJAX in web, if you need to update your form's content after the request is sent to PHP try to send JSON data back to form and parse/update the form, this would make your update of data without changing page.
The procedure it depends on how do you write your form handling
you could jQuery for your AJAX requests see documentation for examples,
also see json_encode for php side of form handling, jQuery UI to make Dialogs.
you can find examples here or see this
There are lots of examples available in net.
Refer this question in stackoverflow How do i update mysql database with ajax and php in innerhtml
This is some code I wrote for a small chatbox, in order to submit a new chat post:
$("#shout").keypress(function(e) {
if(e.keyCode == 13) {
$.ajax({
url: "http://example.com/api.php",
contentType: "text/html; charset=ISO-8859-1",
data: {
action: "shout",
message: $("#shout").val()
},
success: function() {
$("#shout").val("");
}
})
}
});
As soon as you'd press Enter on the input field with the id shout, this would take the value from the input field, put it in an AJAX request, and then send it. Also, after it has been successfully send, it'd clear the input field.
action & data specify the GET parameters of the URL call (that would be http://example.com/api.php?action=shout&message=valueFromInputFieldGoeshere). But you can also use post, just have a look at the options of .ajax().
Hope this gives you an idea on how to send data to the server.
This was the corresponding code, to check if new posts were made to the chatbox, and if so, load them.
$(document).ready(function() {
var lastShout;
// This one gets the timestamp of the last chat entry
$.ajax({
url: "http://example.com/api.php",
contentType: "text/html; charset=ISO-8859-1",
async: false,
data: {
action: "lastshout"
},
success: function(data) {
lastShout = data + 0
}
})
// This one loads the content of the chatbox containing the posts
$.ajax({
url: "http://example.com/api.php",
contentType: "text/html; charset=ISO-8859-1",
data: {
action: "getshouts"
},
success: function(data) {
$("#shouts").html(data);
}
})
// This will be executed every 5 seconds. It takes the timestamp from the beginning, asks the server again for the latest timestamp
// and then checks if the response timestamp is higher than the timestamp from the beginning.
// If so, he'll pull the chatbox content and put it into the specified div
setInterval(function() {
$.ajax({
url: "http://example.com/api.php",
contentType: "text/html; charset=ISO-8859-1",
async: false,
data: {
action: "lastshout"
},
success: function(data) {
data = data + 0
if(data > lastShout) {
lastShout = data;
$.ajax({
url: "http://example.com/api.php",
data: {
action: "getshouts",
init: 1
},
success: function(data) {
if(data != "") {
$("#shouts").html(data);
}
}
})
}
}
})
}, 5000)
})

Categories