AJAX POST - infrequent XHR Failed loading - data missing in PHP post - php

Likely a duplicate in theme/name, but no previous solutions will work either because I'm missing something or there is something else going on.
The form - seemingly at random - fails (not altering data in any field, just the defaults set in html) and when it does succeed the PHP file logs only two of the values, the second one and the fourth (both pure numbers/ints). The two it doesn't echo are 1: a text field and 3: a float.
This is the result the .php picks up -
Connected
'' + '8080' + '' + '1'
Here is the .html and .js, what on earth am I missing here?
<form id="form_0" name="form_0" method="post" action="">
<input type="text" id="coinname" name="coinname" value="litecoin"><br>
<input type="number" id="coins" name="coins" value="8080"><br>
<input type="number" id="cost" name="cost" value="0.0808"><br>
<input type="number" id="show" name="show" value="1"><br>
<input type="submit" id="submit" name="submit" value="Save">
</form>
<script>
$("#form_0").submit(function() {
var selectedcoin = $("#coinname").val();
var coins = $("#coins").val();
var buyprice = $("#cost").val();
var show = $("#show").val();
$.ajax({
type: "POST",
url: "write-database.php",
data: "selectedcoin=" + selectedcoin + "&coins=" + coins + "&buyprice=" + buyprice + "&show=" + show,
success: function(data) {
alert(data);
}
});
});
</script>
and here is the .php
<?php
$servername = "localhost";
$username = "#";
$password = "#";
$dbname = "#";
// Create connection
$con = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else {
echo "Connected <br>";
}
$selectedcoin=$_POST['selectedcoin'];
$coins=$_POST['coins'];
$buyprice=$_POST['buyprice'];
$show=$_POST['show'];
$sql= mysqli_query($conn,"INSERT INTO coin_price (coin_name, coin, price, display) VALUES ('".$selectedcoin."','".$coins."','".$buyprice."','".$show."')");
echo "'$selectedcoin' + '$coins' + '$buyprice' + '$show'";
mysqli_close($con);
?>

Just use serialize method to get all data from form values, as inputs names in $_POST global variable.
<form id="form_0" name="form_0" method="post" action="">
<input type="text" id="coinname" name="coinname" value="litecoin"><br>
<input type="number" id="coins" name="coins" value="8080"><br>
<input type="number" id="cost" name="cost" val="0.0808"><br>
<input type="number" id="show" name="show" value="1"><br>
<input type="submit" id="submit" name="submit" value="Save">
</form>
<script>
$("#form_0").submit(function() {
e.preventDefault();
$.ajax({
type: "POST",
url: "write-database.php",
data: $(this).serialize(),
success: function(data) {
alert(data);
}
});
});
</script>
<?php
$selectedcoin=$_POST['coinname'];
$coins=$_POST['coins'];
$buyprice=$_POST['cost'];
$show=$_POST['show'];
$sql= mysqli_query($conn,"INSERT INTO coin_price (coin_name, coin, price, display) VALUES ('".$selectedcoin."','".$coins."','".$buyprice."','".$show."')");
echo "'$selectedcoin' + '$coins' + '$buyprice' + '$show'";
?>

I hadn't disabled the default submit behaviour that refreshes the page...
$("#form_0").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "write-database.php",
data: $(this).serialize(),
success: function(data) {
alert(data);
}
});
});

Related

How to retrieve data from serialized jQuery string

How to retrieve data when post using AJAX my function is that
jQuery("#wp_pass_reset").submit(function() {
var url = document.getElementById('imgurl').innerHTML;
var url2 = document.getElementById('adminurl').innerHTML;
jQuery('#result').html('<span class="loading"><img src="' + url + '/img/load.gif" /></span>').fadeIn();
var input_data = jQuery('#wp_pass_reset').serialize();
jQuery.ajax({
type: "POST",
url: url2 + 'admin-ajax.php',
data: {
action: 'resetpass_process',
value: input_data,
},
success: function(msg){
jQuery('.loading').remove();
jQuery('<div>').html(msg).appendTo('div#result').hide().fadeIn('slow');
}
});
return false;
});
This is the form:
<form class="user_form" id="wp_pass_reset" action="" method="post" name="wp_pass_reset">
<h1>
Enter Your Email or Username
</h1>
<input type="text" class="text" name="user_input" value=""><br>
<input type="hidden" name="action" value="tg_pwd_reset">
<a class="close">X</a>
<input type="hidden" name="tg_pwd_nonce" value="'.wp_create_nonce(">
<input type="submit" id="submitbtn" class="reset_password btn" name="submit" value="Reset Password">
</form>
When I retrieve data using $_POST['value'] all of my data show but when I use $_POST['user_input'] an error happens.
What can I do?
Here, you are submitting form by ajax then you have to pass it in data like,
data: {
action: 'resetpass_process',
value: input_data,
user_input : $('input[name="user_input"]').val(),
// add more parmeters which you need
},
Add user_input from your form field name to data object:
...
data: {
action: 'resetpass_process',
value: input_data,
user_input: $('input[name="user_input"]').val()
},
...

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

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>

Radio/Checkboxes not saving to db

I have this form in a foreach loop, so it shows multiple times on the same page.
Everything submits fine in each form EXCEPT the radio buttons and checkboxes. They don't save the values to the db.
EDIT: I've narrowed it down to the ajax causing the error but can't figure out how to correct it.
<form action="process.php" method="post" name="editInvoice'.$invoice_id.'" id="editInvoiceForm'.$invoice_id.'" class="editInvoiceForm edit_invoice_container" enctype="multipart/form-data">
<div class="form_item_row">
<input type="radio" value="Unsent" '.$unsent.' name="status"/><span class="choice">Unsent</span>
<input type="radio" value="Sent" '.$sent.' name="status"/><span class="choice">Sent</span>
<input type="radio" value="Paid" '.$paid.' name="status"/><span class="choice">Paid</span>
</div>
<div class="form_item_row">
<label for="include_timelog'.$invoice_id.'">Include Time Log</label>
<input type="checkbox" value="true" '.$include_timelog.' name="include_timelog" id="include_timelog'.$invoice_id.'" />
</div>
<div class="clear"></div>
<div class="form_item_row_btns">
<input type="hidden" value="'.$invoice_id.'" name="hiddenInvoiceID"/>
<input type="submit" class="btn" value="Update Invoice" name="action"/>
</div>
</form>
$query = "UPDATE invoices SET status = ".$db->prep($_POST['status']).", include_timelog = ".$db->prep((isset($_POST['include_timelog'])?1:0))." WHERE invoice_id = ".$db->prep($invoice_id);
$(document).ready(function()
{
var action = '';
$(".due_date").datepicker();
$('input[name=action]').click(function(){
action = $(this).val();
});
$(".editInvoiceForm").submit(function() {
$('.editInvoiceForm .form_message').html('<img src="images/loadingAnimation.gif" alt="loadingAnimation" width="30" height="8"/>');
var dataToSend = {};
$(this).find(':input').each(function (i,el) {
dataToSend[el.name] = $(el).val();
});
dataToSend.action = action;
$.ajax({
type: "POST",
url: "process.php",
data: dataToSend,
dataType: "json",
cache: false,
success: function(data){
//console.log(data.status);
if(data.status == 'error'){
$('.editInvoiceForm .form_message').removeClass('status_green').addClass('status_red').html(data.message).append(data.script);
}else{
$('.editInvoiceForm .form_message').removeClass('status_red').addClass('status_green').html(data.message).append(data.script);
}
}
});
return false;
});
});
You need quotes around the value for status in your SQL since the value is a string. Your include_timelog and invoice_id values are integers and do not need quotes.
$query = "UPDATE invoices SET status = '".$db->prep($_POST['status'])."', include_timelog = ".$db->prep((isset($_POST['include_timelog'])?1:0))." WHERE invoice_id = ".$db->prep($invoice_id);

passing input value using jquery on mysql query

I have following html form:
<form method="post" action="">
<input type="hidden" name="userid" id="user" value="<?php echo $user ?>"/>
<textarea name="comment" class="subcomment_form" id="ctextarea<?php echo $suggestid ?>"></textarea>
<input type="submit" value="Post" id="<?php echo $suggestid ?>" class="form_btn" style="margin-top: 5px"/>
</form>
following JS code:
$('.form_btn').live("click",function()
{
var ID = $(this).attr("id");
var user= $("input[name=userid]").val();
var comment= $("#ctextarea"+ID).val();
var dataString = 'comment='+ comment + '&suggestid=' + ID + 'user' + user;
if(comment=='')
{
alert("Please Enter Comment Text");
}
else
{
$.ajax({
type: "POST",
url: "action/subcomment.php",
data: dataString,
cache: false,
success: function(html){
$("#commentload"+ID).append("html");
$("#ctextarea"+ID).val('');
$("#ctextarea"+ID).focus();
}
});
}
return false;
});
and following php code for subcomment.php file:
if($_POST['comment'])
{
$comment=$_POST['comment'];
$suggestid=$_POST['suggestid'];
$user=$_POST['user'];
$sql = "INSERT INTO user_suggestions_comments (uvd_id, user_id, usc_comment) VALUES ('".$_POST['suggestid']."', '".$_POST['user']."','".$_POST['comment']."')";
mysql_query( $sql);
}
the problem I have is that value from <input type="hidden" name="userid" id="user" value="<?php echo $user ?>"/> is not passed on php file and textarea content is passed. What I need to change inside that JS code to make it work?
It looks like your dataString is not being built to what your PHP code is expecting.
Try this change.
var dataString = 'comment='+ comment + '&suggestid=' + ID + 'user' + user;
becomes
var dataString = 'comment='+ comment + '&suggestid=' + ID + '&user=' + user;
You are looking for three values from your $_POST and only passing 2
$comment=$_POST['comment'];
$suggestid=$_POST['suggestid'];
$user=$_POST['user'];

why is my ajax unable to get the currently typed string in the input form?

I have a simple form, then I placed some data from the table to each of the input forms value attribute. now my problem is, whenever i typed something new to the input form, to update the data, it's unable to pick up the currently typed string, am not sure how to solve this, because I think it is picking up the value echoed out instead of the currently typed string when on this update page,
here's my front-end
<fieldset id="personaldetails">
<legend>Personal Details</legend>
Resume Title: <input type="text" name="resumetitle" id="resumetitle" value="<?php echo $v['ResumeTitle']; ?>" size="50" maxlength="50" /><br />
Name: <input type="text" name="cvname" id="cvname" size="30" maxlength="30" value="<?php echo $v['Name']; ?>" /><br />
DOB: <input type="text" id="datepicker" name="dob" value="<?php $date = new DateTime($v['DOB']); echo $date->format('m/d/Y'); ?>" /><br />
Gender: <input type="radio" name="gender" id="gender-male" value="1" <?php if($v['Gender'] == 1){ echo "checked"; } ?>/> <b>Male</b> |
<input type="radio" name="gender" id="gender-female" value="0" <?php if($v['Gender'] == 0){ echo "checked"; } ?>/> <b>Female</b><br /><br />
<input type="hidden" name="cvid" id="cvid" value="<?php echo $v['ResumeID']; ?>" />
<button name="pdetails" id="pdetails">Update</button>
</fieldset><br /><br />
//here's my js
$(document).ready(function(){
var resumetitle = $('#resumetitle').val();
var cvid = $('input[type="hidden"]').val();
var name = $('#cvname').val();
var dob = $('#datepicker').val();
var gender = $('input[name="gender"]:checked').val();
$('button#pdetails').click(function(){
$.ajax({
type: "POST",
url: "classes/ajax.resumeupdate.php",
data: "resumeid="+cvid+"&resumetitle="+resumetitle+"&name="+name+"&dob="+dob+"&gender="+gender,
success: function(){
//window.location = "resumeview.php?cvid="+cvid;
},
});
});
});
//here's my php code
require 'class.resume.php';
$db = new Resume();
if(isset($_POST['resumetitle']) || isset($_POST['name']) || isset($_POST['dob']) ||
isset($_POST['gender']) || isset($_POST['cvid'])){
$result = $db->updatepdetails($_POST['resumetitle'],$_POST['name'],$_POST['dob'],$_POST['gender'],$_POST['cvid']);
if($result){
echo "success!";
} else {
echo "failed! ".$db->error;
}
}
You are only reading the values on document ready, move that code into the click event:
$(document).ready(function(){
$('button#pdetails').click(function(){
var resumetitle = $('#resumetitle').val();
var cvid = $('input[type="hidden"]').val();
var name = $('#cvname').val();
var dob = $('#datepicker').val();
var gender = $('input[name="gender"]:checked').val();
$.ajax({
type: "POST",
url: "classes/ajax.resumeupdate.php",
data: "resumeid="+cvid+"&resumetitle="+resumetitle+"&name="+name+"&dob="+dob+"&gender="+gender,
success: function(){
//window.location = "resumeview.php?cvid="+cvid;
},
});
});
});
Your javascript is resolving the form values just once (on page load), so if you enter something after the page has loaded, the variables don't change.
You can simply calculate the values inside the Ajax callback instead. But what you really should do is use jQuery's $.serialize() function, which creates a standard a=1&b=2&c=3 querystring including the (properly escaped) form data:
$(function(){
$('button#pdetails').click(function(){
$.ajax({
type: "POST",
url: "classes/ajax.resumeupdate.php",
data: $('form').serialize(),
success: function(){
//window.location = "resumeview.php?cvid="+cvid;
}
});
});
});
Also note that you had a trailing comma after the success function - this will fail in IE so I've changed that as well.

Categories