AJAX works fine, but $_POST does not have a value.
What I have tried:
$data = json_decode(file_get_contents('php://input'), true); &
$post = json_decode($data); into storecart.php
Changing the data into 'jCart=' + jData'
removing datatype (Jaromanda X)
answer (Umakant Mane)
cart is an array of objects
Javascript:
$(document).ready(function(){
$("#showcart").click(function(event){
event.preventDefault();
showcart();
url = 'cart.php';
$(location).attr("href",url);
});
});
function showcart(){
var jData = JSON.stringify(cart);
$.ajax({
url:"storecart.php",
type:"post",
data: {jCart : jData},
datatype: "json",
success: function(data){
console.log("SUCCESS")
console.log(jData);
},
error: function(data){
console.log("REDO")
}
});
}
storecart.php:
<?php
if(isset($_POST['jCart'])){
echo "Right";
}else{
echo "Wrong";
}
?>
How do get the $_POST to accept the json.stringify?
SOLUTION:
SOLVED:
All i did was add a form that has a hidden value
<form id = "postform" action = "cart.php" method = "post">
<input type = "hidden" id="obj" name="obj" val="">
<input type = "submit" value = "Show Cart" id = "showcart">
</form>
In the Javascript:
$(document).ready(function(){
$("#showcart").click(function(){
var json = JSON.stringify(cart)
$('#obj').val(json);
$('#obj').submit();
});
});
Thank you for everyone that has answered but hope this helps.
$(document).ready(function(){
var data = {one:"one", two:"two", three:"three"};
var jsonData = JSON.stringify(data);
$("#clickme").click(function() {
$.ajax({
url:"demo.php",
type:"POST",
data:{cart:jsonData},
success:function(response){
console.log(response);
}, error:function(err) {
console.log(err);
}
})
});
});
PHP
<?php
if(isset($_POST['cart'])){
echo "Right";
}else{
echo "Wrong";
}
?>
Related
I am using Codeigniter and javaScript file upload and insert database but not responce so please check my code abd share valuable idea. share all code heare...view page form data , javascript code responce error and modals submit data code here.....
view
<form id="frm_submit" enctype="multipart/form-data">
<input type="file" name="reportfile" class="form-control">
<button type="submit" class="btn btn-info" name="submit"> Save</button>
</form>
javaScript
$("#frm_submit").on('submit', function (e){
e.preventDefault();
$.ajax({
url: '<?php echo base_url() ?>vendors/upload-report-file',
type: 'POST',
data: $("#frm_submit").serialize()
}).always(function (response){
var r = (response.trim());
if(r !=0){
$(".success").show();
$(".danger").css("display","none");
setInterval('location.reload()',2000);
}else{
$(".danger").show();
$(".success").css("display","none");
}
});
});
models
public function vendors_upload_report_file()
{
$db2 = $this->load->database('bstdc',TRUE);
date_default_timezone_set('Asia/Kolkata');
$vendorsid = $this->session->userdata['vendors_data'][0]['vendor_id'];
$file_request_id = $this->input->post('file_department_id');
$file_request_id = $this->input->post('file_request_id');
$reportfile = $this->input->post('reportfile');
$today_date = date("Y-m-d");
if(!empty($reportfile)){
$filename = $_FILES['reportfile']['name'];
if (!empty($filename)){
$pic = $a.'-'.rand(5,10).time()."".$filename;
move_uploaded_file($_FILES['reportfile']['tmp_name'],'upload/files/'.$pic);
$report_pic_url = ''.base_url().'upload/files/'.$pic.'';
$db2->query('INSERT INTO bstdc_reports_file (request_id,sendor_type,sendor_id,reports_file,reports_file_url,created_date,act_status,del_status)
VALUES ("'.$file_request_id.'","Vendors","'.$vendorsid.'","'.$pic.'","'.$report_pic_url.'", "'.$today_date.'", "Y","N")');
return true;
}else{
return false;
}
}
}
Use FormData object to upload file
$("#frm_submit").on('submit', function (e) {
e.preventDefault();
$.ajax({
url: '<?php echo base_url() ?>vendors/upload-report-file',
type: 'POST',
data: new FormData(this), // <== changed from $("#frm_submit").serialize()
}).always(function (response) {
var r = (response.trim());
if (r != 0) {
$(".success").show();
$(".danger").css("display", "none");
setInterval('location.reload()', 2000);
}
else {
$(".danger").show();
$(".success").css("display", "none");
}
});
});
I didn't understand how to get data from php by ajax.
Here is my javascript code :
$('#value').on('keyup', function(event){
event.preventDefault();
var form_data = $(this).serialize();
var sending = $("#sending").val();
var value = $("#value").val();
var recevied = $("#recevied").val();
$.ajax
({
type: "POST",
//async: true,
dataType : 'json',
url: "{{url('/calculate')}}",
data: {_token:"{{csrf_token()}}", sending:sending,value:value,recevied:recevied}
}).done( function(data){
//swal("Good job!", "Your personal information has been successfully updated!", "success")
$("#mainvalue").val(data)
console.log('Ajax was Successful!')
console.log(data)
}).fail(function(xhr, textStatus, error){
console.log(textStatus)
console.log(error)
});
});
here is my php code :-
public function index(Request $request)
{
$sending = $request->get('sending');
$value = $request->get('value');
$recevied = $request->get('recevied');
$relations = DB::table('tbl_relations')
->where('exid1',$sending)
->where('exid2',$recevied)
->select()
->first();
if ($relations != null) {
$rate = $relations->exrate2;
$mainvalue = $sending * $rate;
return $rate;
}else{
return $request->all();
}
}
How to restore $rate value into #mainvalue ?
well i guess you can try the following inside the php code :
$post = file_get_contents('php://input');
I would like to get the 2 values separately in order to fill automatically the input in the first file from the PHP via AJAX, but when i console.log(data) I get all the data and I want to retrieve it separately in order to put it in different tags
<input id="regist" type="text" name="regist" onblur="passdata();">
<input id="atyp" type="text" name="atyp" >
<input id="mtow" type="text" name="mtow" >
<script>
$(document).ready(function(){})
function passdata() {
var regist = $('#regist').val();
$.ajax({
type: 'post',
url: 'checkdb.php',
data: 'regist='+regist,
success: function(data){
var atyp = $('#myvalue1').val();
var mtow = $('#myvalue1').val();
$('#atyp').text(atyp);
$('#mtow').text(mtow);
alert (aty+mtow);
console.log(data);
}
})
}
</script>
and PHP file.... of course with db connection
$regist = $_POST['regist'];
$conn = mysqli_connect($host,$user,$pwd,$db);
$sql= ("SELECT * FROM aircrafts where regist='$regist'");
$datas = mysqli_query($conn,$sql);
foreach ($datas as $row) {};
if(mysqli_num_rows($datas) == 0) {
echo 'non ce niente';
} else { ?>
<span id="myvalue1"><?php echo $atyp = $row['atyp'];?></span>
<span id="myvalue2"><?php echo $atyp = $row['mtow'];?></span>
<?php };
?>
Change your Ajax request to:
$.ajax({
type: 'post',
url: 'checkdb.php',
data: 'regist='+regist,
dataType: 'json', // NEW LINE
success: function(data) {
//var atyp = $('#myvalue1').val();
//var mtow = $('#myvalue1').val();
//$('#atyp').text(atyp);
//$('#mtow').text(mtow);
var atyp = data.atyp;
var mtow = data.mtow;
alert ('aty: ' + aty , 'mtow: ' + mtow);
console.log(data);
}
})
and in your PHP: change these lines
else{?>
<span id="myvalue1"><?php echo $atyp = $row['atyp'];?></span>
<span id="myvalue2"><?php echo $atyp = $row['mtow'];?></span>
<?php };
to this exactly lines
else {
echo json_encode( $row );
}
EDIT
Regarding your "DOM-event"-handling ("document onready" and "input#regist onblur") I recommend to do it like this.
HTML:
<!-- <input id="regist" type="text" name="regist" onblur="passdata();"> -->
<input id="regist" type="text" name="regist">
<input id="atyp" type="text" name="atyp">
<input id="mtow" type="text" name="mtow">
JavaScript:
function passdata(event) {
$.ajax({
type: 'post',
url: 'checkdb.php',
data: 'regist=' + $(event.target).val(),
dataType: 'json',
success: function(data){
console.log(data);
}
})
}
$(document).ready(function(){
// on blur event
$('#regist').on('blur', passdata)
// on input event | maybe this would be also an interesting option as it fires immidiately on input
// $('#regist').on('input', passdata)
})
This bootstrap seperates the logic from the markup which is a good practice in general.
My code seems to not run the jQuery at all for some reason, I have spent lots of time attempting to figure out what's wrong and have tested my delete PHP file separately
jQuery script:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
$.ajaxSetup({ cache: false });
$(document).ready(function(){
$('#button').on('click', '#btn',function()) {
var clickBtnName = $(this).attr('name');
var ajaxurl = 'http://127.0.0.1/SQLDeleteHandler.php';
var data = {'id': clickBtnName};
$.post(ajaxurl, data, function(response) {
window.location.href="http://localhost/store.php";
});
});
});
</script>
Php:
$query = "SELECT * FROM accounts";
$resultset= mysqli_query($connection,$query);
while($row = mysqli_fetch_array($resultset,MYSQLI_NUM)){
echo $row[0]." ".$row[1]." ".$row[2]." ".'<input type="submit" class="btn" name="".$row[0]."" value="delete" />';
echo "</br>";
}
use this :
$(document).ready(function(){
$('.btn').click(function(e){
e.preventDefault();
alert('Button is pressed');
var clickBtnName = $(this).attr('name');
var ajaxurl = 'http://127.0.0.1/SQLDeleteHandler.php';
var data = {'id': clickBtnName};
$.post(ajaxurl, data, function(response) {
window.location.href="http://localhost/store.php";
});
});
});
I am storing my checkbox selections in an array then splitting each array and posting them using AJAX so my PHP function can use the posted id/ids to query my MySQL database.
First part of my JavaScript
$('#tbl_list').click(function (event) {
var tbls = new Array();
$("input:checkbox[name='tbl[]']:checked").each(function () {
tbls.push($(this).val());
});
var tbl = tbls.join('|');
alert(tbl);
This first part works as intended, where every time I click a checkbox the value is alerted.
AJAX post
$.ajax({
type: "POST",
url: "index.php",
data: "tbl=" + tbl
});
});
Finally my PHP
function describeTables() {
if (isset ( $_POST ['tbl'] )) {
$tbl = $_POST ['tbl'];
echo $tbl;
}}
I don't get any vlaues of tbl even if I choose just one option. Why is this????
EDIT
My Checkbox
function showTables() {
if (isset ( $_GET ['db'] )) {
$db = $_GET ['db'];
$link = mysqli_connect ( 'localhost', 'root', '', $db );
$qry = "SHOW tables";
$tbl_list = mysqli_query ( $link, $qry );
echo '<ul>';
while ( $row = mysqli_fetch_array ( $tbl_list ) ) {
echo '<input type="checkbox" name="tbl[]" class="tbl_list" value="' . $row [0] . '" class="tablebox" />';
echo $row [0];
echo '<br>';
}
}
}
showTables ();
SECOND EDIT
After suggestions I have amended my code but now have a new problem where the page doesn't load #dbdisplay Below is my full JS code
if (!location.search.match(/db=[^&#]+/i)) {
$("#dbdisplay").show();
} else {
$("#qryDisplay").show();
}
$(document).on("change", ".checkbox", function () {
var db = $(this).val();
window.sessionStorage.setItem("db", db);
window.location.assign("index.php?db=" + db);
$("#dbdisplay").hide();
});
$('#tbl_list').click(function (event) {
var tbls = new Array();
$("input:checkbox[name='tbl[]']:checked").each(function () {
tbls.push($(this).val());
});
var tbl = tbls.join('|');
//alert(tbl);
$.ajax({
type: "POST",
url: "index.php",
data: {'tbl': tbl }
});
});
The old function
/*
$(document).on("change", ".tablebox", function () {
var tbls = new Array();
$("input:checkbox[name='tbl[]']:checked").each(function () {
tbls.push($(this).val());
});
var tbl = tbls.join('|');
var yourDB = window.sessionStorage.getItem("db");
window.location.assign("index.php?db=" + yourDB + '&tbl=' + tbl);
});
*/
How do I fix this??
In ajax call, data has to be object data: {'tbl': tbl}
This should to the job
$.ajax({
type: "POST",
url: "someurl",
data: {"tbl=" + tbl}
});
http://api.jquery.com/jquery.getjson/
See here for documentation
First thing in your ajax call, data has to be object
data: {'tbl': tbl}
Secondly Ajax can't call php function directly
so your index.php file should be something like this without function
if (isset ( $_POST ['tbl'] )) {
$tbl = $_POST ['tbl'];
echo $tbl;
}
You should use "{ }" with data
$.ajax({
type: "POST",
url: "index.php",
data: {'tbl' : tbl}
});
or
$.ajax({
type: "POST",
url: "index.php&tbl="+tbl
});