PHP Values not updating with AJAX Post - javascript

I have the need to receive javascript variables in PHP so I set up my Ajax call and script, I have verified that AJAX is sending back the proper response it just seems like server side is not wanting to actually pull the information. Here is my javascript
$("#payments2").on("change", function() {
$("#p1").val($(this).find("option:selected").text());
var Id = $(this).find("option:selected").attr('value');
var Ids = $("#payments").find("option:selected").attr('value');
$.post("postit.php", {
Id: Id,
Ids: Ids
}, function(data){
var theResult = data;
}, 'json' );
});
$("#exchange").on("change", function() {
var am = $(this).attr('value');
var fee = $("#fee").attr('value');
var cost = $("#cost").attr('value');
var perc = fee / 100;
var tot = perc * am;
var total = am - tot - cost;
$("#return").val(total);
});
and here is my PHP variable call
<li>
<label for="exchange">Amount to Exchange</label>
<input type="text" id="exchange" name="exchange" maxlength="100">
<span>Amount to Exchange</span>
</li>
<?php
$amounts = $db->query("SELECT * FROM `exchange` WHERE `fromp` = '".$_POST['fromp']."' AND `top` = '".$_POST['top']."'");
$amo = $amounts->fetch_assoc();
?>
<input type="hidden" id="fee" name="fee" value="<?php echo $amo['fee'] ?>" />
<input type="hidden" id="cost" name="pay" value="<?php echo $amo['cost'] ?>" />
<li>
<label for="return">Amount to Receive</label>
<input type="text" id="return" name="return" maxlength="100" value="">
<span>Amount you will receive</span>
</li>
Since I can clearly tell that my Ajax call is sending back the proper information and I am not getting any errors in my query then I am unsure as to why my values for fees and cost aren't changing causing me to receive NaN in my return text box.
Here is also the contents of my postit.php file
$Id= isset($_POST['Id']) ? $_POST['Id'] : '';
$Ids= isset($_POST['Ids']) ? $_POST['Ids'] : '';
include "connect.php";
$que = $db->query("SELECT * FROM `exchange` WHERE `fromp` = '".$Ids."' AND `top` = '".$Id."'");
/* Get query results */
$results = $que->fetch_assoc();
/* Send back to client */
echo json_encode($results);
exit;
This is my first time using posting variables from javascript to php so I am sure I have done something wrong, or maybe there is a way to get the information that was passed by the script using javascript, perhaps a way to get the variables I need within my javascript function rather than the mysql query?

You're not setting the values for the fields from your json response, try
$.post("postit.php", {
Id: Id,
Ids: Ids
}, function(data){
$("#fee").val(data['fee']);
$("#cost").val(data['cost']);
}, 'json' );

Perhaps I'm missing something, but your jQuery is sending 'Id' and 'Ids' as the form data, and the PHP is trying to use 'fromp' and 'top'.
Additionally, it doesn't appear that your response handler is doing anything with the DOM. Have you inspected the Network panel of your chrome debugger to see what the PHP script is responding with?

Related

Accessing hidden input array using ajax / php

I have a form that contains several of the following types of elements
<input type="hidden" name="selected_models[]" value="1">1</td>
<input type="hidden" name="selected_models[]" value="2">2</td>
<input type="hidden" name="selected_models[]" value="3">3</td>
<input type="hidden" name="selected_models[]" value="4">4</td>
I am trying to pass this array, along with all my other form data to a jQuery $.post function, but I can't access the data in php correctly.
I've tried to pass it using the following (jQuery):
var _data = { models: $('input[name="selected_models[]"]').serialize() }
and then access it in PHP using:
$models = $_POST['models'];
just for the purpose of trying to check the data, I pass this variable to the ajax response, and log it back to the console using:
Php
$response = jseon_encode(
array(
'success' => true,
'models' => json_encode($models)
)
);
and
JS
console.log(JSON.parse(response.models)
Which outputs the following:
selected_models%5B%5D=37&selected_models%5B%5D=51&selected_models%5B%5D=57
so, honestly now I'm just stuck with how to loop through those values in php so I can actually do something with them. Ideally, I would be able to do something like:
Php
foreach ( $models as $model ) {
$id = $model.selected_models
// Do more stuff
}
But this isn't working. What am I doing wrong?
I ended up solving this in jQuery and passing a parsed value to PHP, instead:
var uniqueModels = [];
if ( document.getElementById('acInheritFromVehicle').checked ) {
var models = jQuery( 'input[name="selected_models[]"]:checked');
var modelIDs = [];
//console.log(models);
models.each(function() {
if( jQuery.inArray( ))
modelIDs.push( jQuery(this).val() );
});
uniqueModels = unique(modelIDs);
uniqueModels = jQuery.grep( uniqueModels, function(value) {
return value != 0
});
//console.log(uniqueModels);
}
You were doing it correctly, just some minor PHP tweaks and you would have got it. Once you serialize your data and sent to PHP you can always check what that array looks like by using print_r($models) function.
To loop through your $models array, do the following:
foreach($models as $model) {
echo 'Value of hidden input is: ' . $model;
echo '<br />';
}
$model will represent an actual value received through PHP request. Check out this example

Pass value from a table into a function using jquery

I was trying to pass the variable thecode, which is in the table using jquery into the function named getComments(). My code has as following. First I have my jquery script which is this:
$(document).ready(function(){
$("#comment_process").click(function(){
if($("#comment_text").val() != ""){
$('.post_loader').show();
$.post("comments_business.php?action=post", {
comment: $("#comment_text").val()
}, function(data) {
$(".comments").hide().html(data).fadeIn('slow');
$("#comment_text").val("");
$('.post_loader').hide();
});
}
});
});
Next I have the following script with html and php:
<!--- more code at the top---->
<?php $auto = $profile_data_business['business_code']; ?>
<table>
<textarea rows="3" id="comment_text" placeholder="share an update."></textarea>
<input type="" id="comment_code" name="thecode" value="<?php echo $auto; ?>" />
<input type="button" id="comment_process" />
</table>
<div class="comments"><?php include_once("comments_business.php");?> </div>
the page named comments_business.php includes a function which is the following:
<?php
function getComments(){
$session_user_id = $_SESSION['user_id'];
$comments = "";
// can't get variable $thisemail
$thisemail = mysql_real_escape_string($_POST['thecode']);
$sql = mysql_query("SELECT * FROM comments_business WHERE ( `flag`=0 and `user`='$thisemail' and `comments_id` NOT IN (SELECT `comments_id` FROM `hide_comment_business` where `user`='$session_user_id') ) ORDER BY comment_date DESC LIMIT 40") or die (mysql_error());
//more code here
return $comments;
}
?>
Any idea how should I change my jquery code so that I will be able to pass $thisemail variable successfully into getComments() function?
When you use $.post don't need to write GET parameter in URL (action=post).
When you post data by comment name, you must get data by some name
in php ($_POST['comment']).
When you use ajax shouldn't use function in php or call function
after defintion.
When you use ajax must print or echo data in php file to display in
post result.

jQuery serialize and insert in mysql

I have this code to insert some data that comes from a while, in a db. I'm trying to use jQuery serializearray and jQuery post together. But it seems I do some errors
$query= "SELECT * FROM barcode_prodotti";
$result = mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_array($result)){
echo'
<input type="text" name="prodotto[]" class="prodotto" value="'.$row["prodotto"].'"></div>
<input type="text" name="prezzo[]" class="price" value="'.$row["prezzo"].'">
<input type="text" name="quantita[]" class="price" value="'.$row["quantita"].'">';
}
?>
<script src="js/mine.js"></script>
<button>Serialize form values</button>
</form>
<div id="results"></div>
This is my jQuery code I put in mine.js
$(document).ready(function(){
$('form').submit(function(msg) {
var mia =$(this).serialize();
$('#results').text(mia)
alert($(this).serialize()); // check to show that all form data is being submitted
$.post("testtest.php",$(this).serializeArray(),function(data){
alert(data);
});
return false; });
});
This is my php file (testtest.php)
mysql_connect("localhost","root","");
mysql_select_db("db");
$arr = $_POST;
$sql="INSERT INTO table VALUES(
'".$arr['prodotto']."',
'".$arr['quantita']."',
'".$arr['prezzo']."'
)";
$rssql = mysql_query($sql);
?>
So I the serialize is ok (i tried to assign in a div a value to see if it was ok), but I can't insert values in my db
Your INSERT query ends up looking like this after variable substitution.
INSERT INTO table VALUES( 'product', '123', '321')
If your table has exactly three columns this will work fine. Otherwise it will fail. You may wish to use this query instead.
INSERT INTO table (prodotto, prezzo, quantita ) VALUES( 'product', '123', '321')
which enumerates the columns where you want your data.
After doing an insert (and after any query) you should check for errors. This can be done with code like this.
$res = mysql_query($q);
if ($res === false) {
echo $mysql_error ();
}
Note well: The mysql_xxx() interface is being removed from PHP for a good reason: it is vulnerable to cybercriminals. Please adopt mysqli_xxx() or PDO as soon as possible.
The simplest way to do this:
<form id="myform" method="post">
<input type="text" name="prodotto" id="prodotto">
<input type="text" name="prezzo" id="prezzo">
<input type="text" name="quantita" id="quantita">
</form>
Jquery is pretty simple too:
var datastring = $("#myform").serialize();
$.ajax({
type: 'POST',
url: 'url/to/yourfile.php',
data: datastring
}).done(function(res){
var res = $.trim(res); //the ajax response. you can alert it or whatever...
});
You can parse the fields in the ajax file like that:
yourfile.php
<?php
$product = mysql_real_escape_string($_POST["prodotto"]);
$prezzo = mysql_real_escape_string($_POST["prezzo"]);
$quantity = mysql_real_escape_string($_POST["quantita"]);
//here you have the variables ready to add them as values to database
$ins = "INSERT INTO table (prodotto, prezzo, quantita ) VALUES( 'product', '123', '321')";
mysql_query($ins);
?>

How to call a PHP function within a page using AJAX

I wrote a php function which does the job perfectly if it is called standalone by PHP page. but I want to integrate this function in a program and want to call it when a button is clicked.
My PHP function is
function adddata($mobile){
// outside of this function, another database is already selected to perform different
//tasks with program's original database, These constants are defined only within this
//this function to communicate another database present at the same host
define ("HOSTNAME","localhost");
define ("USERNAME","root");
define ("PWD","");
define ("DBNAME","budgetbot");
// link to mysql server
if (!mysql_connect(HOSTNAME,USERNAME,PWD)) {
die ("Cannot connect to mysql server" . mysql_error() );
}
// selecting the database
if (!mysql_select_db(DBNAME)) {
die ("Cannot select database" . mysql_error() );
}
//inserting phone number into database
$query = "INSERT INTO `verify_bot` (phone_number) values('".$mobile."')";
if(!mysql_query($query)){
die( mysql_error() );
}
// wait for 2 seconds after adding the data into the database
sleep(2);
$query = "SELECT * FROM `verify_bot` WHERE phone_number = ".$mobile;
$result = mysql_query($query) or die( mysql_error() );
// if more than one records found for the same phone number
if(mysql_num_rows($result) > 1){
while($row = mysql_fetch_assoc($result)){
$data[] = $row['response'];
}
// return an array of names for the same phone numbers
return $data;
}else{
// if only one record found
$row = mysql_fetch_assoc($result);
$response = $row['response'];
return $response;
}
// end of function
}
HTML Code is written as
<form action="self_page_address_here" method="post" accept-charset="utf-8" class="line_item_form" autocomplete="off">
<input type="text" name="mobile_number" value="" placeholder="(000) 000-0000" class="serial_item" size="20" id="serialnumber_1" maxlength="10" />
<button id="verify" class="btn btn-primary">Verify</button>
<button id="cname" class="btn btn-primary"><!-- I want to print return value of the php function here --></button>
</form>
I want to call this function and assign the return value to a javascript variable by ajax/jquery.
My code to do this is...
<script type="text/javascript" language="javascript">
$('#verify').click(function(){
var value = $( ".serial_item" ).val();
//I have some knowledge about php but I am beginner at ajax/jquery so don't know what is happening below. but I got this code by different search but doesn't work
$.ajax({
url : "add_data.php&f="+value,
type : "GET"
success: function(data){
document.getElementById("cname").innerHTML = data;
}
});
});
</script>
I would like to share that the above javascript code is placed outside of documnet.ready(){}
scope
Any help would be much appreciated.
Thanks
Because your <button> elements have no type="button" attribute, they're supposed to submit the form using normal POST request.
You should either use type="button" attribute on your buttons, or prevent default form submission using event.preventDefault():
$('#verify').click(function(event){
event.preventDefault();
var value = $( ".serial_item" ).val();
$.ajax({
// there's a typo, should use '?' instead of '&':
url : "add_data.php?f="+value,
type : "GET",
success: function(data){
$("#cname").html(data);
}
});
});
[EDIT] Then in add_data.php (if you call AJAX to the same page, place this code at the top, so that no HTML is rendered before this):
if(isset($_GET['f'])){
// call your function:
$result = adddata(trim($_GET['f']));
// if returned value is an array, implode it:
echo is_array($result) ? implode(', ', $result) : $result;
// if this is on the same page use exit instead of echo:
// exit(is_array($result) ? implode(', ', $result) : $result);
}
Make sure you escape the value on $query.

Getting form data from both dependent drop down lists to php

I have a form on my page which includes 2 dependent drop down lists. When user selects value from 1st list, it populates the second list and user then selects value from 2nd list.
I want to submit form data to php page to insert into table in mysql, but when it submits, all data is passed EXCEPT value from 2nd list. Value from 1st list and other input fields are passed OK.
I've tried everything I know and I can't make this work. Any ideas how to implement this?
This is the form from index2.php (EDIT: simplified the form element):
<form name="part_add" method="post" action="../includes/insertpart.php" id="part_add">
<label for="parts">Choose part</label>
<select name="part_cat" id="part_cat">
<?php while($row = mysqli_fetch_array($query_parts)):?>
<option value="<?php echo $row['part_id'];?>">
<?php echo $row['part_name'];?>
</option>
<?php endwhile;?>
</select>
<br/>
<label>P/N</label>
<select name="pn_cat" id="pn_cat"></select>
<br/>
<input type="text" id="manufactured" name="manufactured" value="" placeholder="Manufactured" />
<input id="submit_data" type="submit" name="submit_data" value="Submit" />
</form>
And this is javascript:
$(document).ready(function() {
$("#part_cat").change(function() {
$(this).after('<div id="loader"><img src="img/loading.gif" alt="loading part number" /></div>');
$.get('../includes/loadpn.php?part_cat=' + $(this).val(), function(data) {
$("#pn_cat").html(data);
$('#loader').slideUp(200, function() {
$(this).remove();
});
});
});
});
And this is php to load 2nd list:
<?php
include('db_connect.php');
// connects to db
$con=mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$part_cat = $_GET['part_cat'];
$query = mysqli_query($con, "SELECT * FROM pn WHERE pn_categoryID = {$part_cat}");
while($row = mysqli_fetch_array($query)) {
echo "<option value='$row[part_id]'>$row[pn_name]</option>";
}
?>
I am getting $part_cat from 1st list to insertpart.php, but $pn_cat.
EDIT: this is insertpart.php (simplified and it just echos resuls)
<?php
//Start session
session_start();
//Include database connection details
require_once('../includes/db_details.php');
//DB connect
$con=mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
// find part name based on ID
$part_typeID = mysqli_real_escape_string($con, $_POST['part_cat']);
$part_name_result = mysqli_query($con, "SELECT part_name FROM parts WHERE part_id = $part_typeID");
$part_row = mysqli_fetch_array($part_name_result, MYSQL_NUM);
$part_type = $part_row[0];
echo"part_type='$part_type'";
//find pn value based on id
$pn_typeID = mysqli_real_escape_string($con, $_GET['pn_cat']);
$pn_name_result = mysqli_query($con, "SELECT pn_name FROM pn WHERE pn_id = $pn_typeID");
$pn_row = mysqli_fetch_array($pn_name_result, MYSQL_NUM);
$pn = $pn_row[0];
echo"pn='$pn'";
mysqli_close($con);
?>
It's still work in progress, so the code is ugly, and I know I'm mixing POST and GET that is being rectified. If I echo $pn_cat on this page there is no output, $part_type is OK.
Can you try swapping the $_GET in
$pn_typeID = mysqli_real_escape_string($con, $_GET['pn_cat']);
with $_POST?
$pn_typeID = mysqli_real_escape_string($con, $_POST['pn_cat']);
EDIT: based on asker's feedback and idea for a work-around
NOTE: This edit is based on what you suggested, even though I tested your original code and received satisfactory results (after I removed the PHP and MySQL from the code and replaced them with suitable alternatives).
The Work-Around
Here's the HTML for the hidden field:
<input type="hidden" id="test" name="test" value="" placeholder="test" />
Here's a simple Javascript function:
function setHiddenTextFieldValue(initiator, target){
$(initiator).change(function() {
$(target).val($(this).val());
});
}
You can call the above function within the function(data) { of your original code with something like:
setHiddenTextFieldValue('#pn_cat', '#test'); // note the hashes (#)
I also recommend you to hard-code the following HTML into your HTML and PHP files, right before the looping of the <option>s begin:
<option value="" disabled selected="selected">Select</option>
The above line could improve user experience, depending on how you want your code to work. Note however, that this is entirely optional.
Solved it! It was just a stupid typo, can't believe I've lost 2 days over this!
In loadpn.php instead of:
$row[part_id]
it should read:
$row[pn_id]
For some reason drop down worked, but offcourse value of pn_cat wasn't being set.
Also this works in setting 2 field values (which now I don't need but if somebody wants to know):
$(document).ready(function() {
$("#part_cat").change(function() {
$('#pn_hidden').val($(this).val());
});
$("#pn_cat").change(function() {
$('#pn_hidden2').val($(this).val());
});
});
Also changed js to post:
$(document).ready(function() {
$("#part_cat").change(function() {
$.post('../includes/loadpn.php', 'part_cat=' + $(this).val(), function(data) {
$("#pn_cat").html(data);
});
});
});
And thanks for the:
<option value="" disabled selected="selected">Select</option>
It really helps with user experience.

Categories

Resources