AJAX How to use key:value - php

My form:
<form action="html_post.php" method="post" id="myform">
<textarea id="textarea" placeholder="Add your comment" name="posting"> </textarea>
<input class="button" type="button" name="send" value="Send">
</form>
I have such code
$(".button").click(function () {
var content = $("#myform").serialize();
$.ajax({
url: "add_post.php",
type: "POST",
data: {
text: content,
action: "add_post"
},
success: function () {
$('#comment_block').load('list_post.php');
document.getElementById('textarea').value = "";
}
})
});
And such php:
echo mysqli_error($connection);
if (strlen($_POST['posting']) >= 5) {
$text = htmlspecialchars($_POST['posting']);
$insert = "INSERT INTO post(content) VALUE ('$text')";
mysqli_query($connection, $insert);
}
But it does not add text to db. I'm just learning ajax and it's my first experience with key:value so can you help me?
And yep, there is no shown errors

The way you've written it, there is no $_POST['posting']. Instead, $_POST['text'] contains a URL-encoded string containing all the inputs in the form, i.e. a string like "posting=blah blah blah".
What you probably want is:
$(".button").click(function () {
var content = $("#myform").serialize();
$.ajax({
url: "add_post.php",
type: "POST",
data: content + '&action=add_post',
success: function () {
$('#comment_block').load('list_post.php');
document.getElementById('textarea').value = "";
}
})
});

Based on your posted code, on the server there will be two keys set in the $_POST variable. These are the ones that you define at your ajax request in javascript: text and action.
So while you check $_POST['posting'] it does not exists, but there are $_POST['text'] and $_POST['action']. $_POST['text'] will contain all the form fields as an URL-encoded string, like "posting=xyz". In order to access these values, you could use the parse_str() php function that parses this string as it were a query string.
So the condition at the server side could be something like as follows.
if (isset($_POST['text'])) {
// $formdata passed in by reference, it will contain all the form fields
parse_str($_POST['text'], $formdata);
}
if (isset($formdata['posting']) && strlen($formdata['posting']) >= 5) {
// Perform db operation
}

Related

jQuery - send multidimensional form data to PHP script

I have a jQuery script that adds hidden inputs into a form whenever a certain .class input undergoes a change. Depending on user input, it generates values for other uneditable columns which also get pushed into a form as hidden inputs.
The form output looks like this:
<input type="hidden" name="[1008016BSTL][1][part]" value="1008016BSTL" />
<input type="hidden" name="[1008016BSTL][1][price]" value="123" />
<input type="hidden" name="[1008016BSTL][1][priceExVat]" value="102.50" />
<input type="hidden" name="[1008016BSTL][1][fee]" value="10.53" />
<input type="hidden" name="[1008016BSTL][1][profit]" value="68.41" />
This is just one set of data I'm trying to capture, but it's the same for the others, save the original key and sub-key.
My form wrapper looks like this:
<form method="post" id="submit-form" enctype="multipart/form-data">
<input type="submit" value="Save" />
</form>
With my AJAX looking like:
$('form#submit-form').submit(function(e)
{
e.preventDefault();
let data = $('form#submit-form').serializeArray();
$.ajax({
url: '/save-pricing.php',
data: {data: JSON.stringify(data)},
type: 'post',
success: function(res)
{
console.log(res)
},
error: function(res)
{
alert('Error! I won\'t tell you what it is. But, I\'ll give you a clue: 21');
console.log(res)
}
})
})
I've also tried (for setting data):
let data = $('form#submit-form').serialize();
data = JSON.stringify(data);
$.ajax({
...
data: {data: data}
...
})
As well as omitting the .stringify() function.
This comes through to PHP like this:
<?php
echo '<pre>'. print_r($_POST, 1) .'</pre>';
/**
* Below is for .serialize() -> output is an empty array
*
* parse_str($_POST['data'], $postData)
* echo '<pre>'. print_r($postData, 1) .'</pre>';
*/
simplified output (just removing the other sets) with .serializeArray():
Array
(
[data] => [
{"name":"[1008016BSTL][1][part]","value":"1008016BSTL"},
{"name":"[1008016BSTL][1][price]","value":"123"},
{"name":"[1008016BSTL][1][priceExVat]","value":"102.50"},
{"name":"[1008016BSTL][1][fee]","value":"10.53"},
{"name":"[1008016BSTL][1][profit]","value":"68.41"}
]
)
This is OK I guess, I could probably group by name and merge into an array, but there feels like it should already do this with .serialize() on jQuery-side and then parse_str() on the PHP side.
However, as I've mentioned, parse_str() and .serialize() yield an empty array, which I can't use.
so my question is: How do I successfully send multi-dimensional form data to PHP via jQuery?
Edit
Added:
dataType: 'json'
with .serialize() and then JSON.stringify(data), removed parse_str() and it outputs:
Array
(
[\"] => Array
(
[1008016BSTL] => Array
(
[1] => Array
(
[part] => 1008016BSTL
)
)
)
)
Input fields names with brackets are not treated nicely by serializeArray. This below code will create a proper multidimentional array you can send back to the server.
$('form#submit-form').submit(function(event)
{
event.preventDefault();
//Prevent the form from submitting
var fields = {};
//This is where you're gonna store your form fields
$.each($('form#submit-form').serializeArray(), function(i, field) {
//Get values, even from multiple-selects
if (Array.isArray(fields[field.name])) {
fields[field.name].push(field.value);
} else if (typeof fields[field.name] !== 'undefined') {
var val = fields[field.name];
fields[field.name] = new Array();
fields[field.name].push(val);
fields[field.name].push(field.value);
} else {
fields[field.name] = field.value;
}
});
//Now all the fields are in the fields object
//You're now going to translate "key[subkey]" string to key[subkey] object
for (var key in fields) {
var parts = key.split(/[[\]]{1,2}/);
parts.length--;
if (parts.length) {
var val = fields[key];
delete fields[key];
addToTree(fields, parts);
setToValue(fields, val, parts);
}
//input field array names (with brackets) are mistakenly treated as strings, this fixes it
}
$.ajax({
url: '/save-pricing.php',
data: JSON.stringify(fields),
contentType: 'application/json',
type: 'post',
success: function(res) {
console.log(res)
},
error: function(res) {
alert('Error! I won\'t tell you what it is. But, I\'ll give you a clue: 21');
console.log(res)
}
})
});
/**
* Adds values to a tree.
* #link https://stackoverflow.com/questions/3663096/how-to-convert-array-to-tree
*/
function addToTree(tree, array) {
for (var i = 0, length = array.length; i < length; i++) {
tree = tree[array[i]] = tree[array[i]] || {}
}
}
/**
* Sets object values.
* #link https://stackoverflow.com/questions/13719593/how-to-set-object-property-of-object-property-of-given-its-string-name-in-ja
*/
function setToValue(obj, value, path) {
for (i = 0; i < path.length - 1; i++) {
obj = obj[path[i]];
}
obj[path[i]] = value;
}
with the PHP side using json_decode:
$data = json_decode(file_get_contents('php://input'), true);
echo '<pre>'. print_r($data, 1) .'</pre>';
For your particular issue you can the jquery.serializeJSON
Here is the link of their github https://github.com/marioizquierdo/jquery.serializeJSON
This will create the correct json object.
This is simplest solution I have for this case.
<?php if(isset($_POST["data"])) {
$post_data = urldecode($_POST["data"]);
parse_str($post_data, $form_data);
// this will give you first element of array by eliminating double quote key ('') in post data array, which is also desired
$form_data = reset($form_data);
echo '<pre>'; print_r($form_data); echo '</pre>'; exit;
} else { ?>
<form method="post" id="submit-form">
<input type="hidden" name="[1008016BSTL][1][part]" value="1008016BSTL" />
<input type="hidden" name="[1008016BSTL][1][price]" value="123" />
<input type="hidden" name="[1008016BSTL][1][priceExVat]" value="102.50" />
<input type="hidden" name="[1008016BSTL][1][fee]" value="10.53" />
<input type="hidden" name="[1008016BSTL][1][profit]" value="68.41" />
<input type="submit" value="Save" />
</form>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$("#submit-form").on('submit', function(e){
e.preventDefault();
var form_data = $("#submit-form").serialize();
$.ajax({
type: "POST",
data: {data: JSON.stringify(form_data)},
success: function(res){
console.log(res);
}
});
});
</script>
<?php } ?>

store JSON values in input fields

hi i'm looking for some help
I'm learning how to use Ajax and PHP and what I want to do is to run a query in PHP and store the results in a JSON.
Then I want to echo the JSON and set it's values into text fields.
Is this possible?
Since I'm pretty new to Ajax and jQuery I'm not sure how to do this.
I attempted to do it, but I'm only getting the first value of the array.
This is my code:
<input type="text" id="text1">
<button type="button" class="btn btn-success" id="send">Success Button</button>
<input type="text" id="text2">
<input type="text" id="text3">
<input type="text" id="text4">
<script type="text/javascript">
$(document).ready(function(){
$("#send").click(function(event){
event.preventDefault();
var Rfc=$("#text1").val();
$.ajax({
type: 'POST',
url: 'search.php',
data: 'Rfc='+Rfc,
dataType : 'json',
success: function(msg){
var datashow = JSON.parse(msg);
$("#text2").val(msg[0].id_person); ///this is the only value that i get
$("#text3").val([1].person_name); ///i want to get the person's name here
$("#text4").val([2].person_address);///i want to get the person's address here
},
error : function () {
alert("error");
}
});
});
});
</script>
And this is my PHP file:
<?php
$rfc=$_POST['Rfc'];
$connection = mysqli_connect("localhost","root","","transferorders");
$query = mysqli_query($connection,"SELECT * FROM person where rfc_number ='$rfc'");
$Data = array();
while($row = mysqli_fetch_assoc($query)){
$Data[]=$row;
echo json_encode($Data);
}
?>
this is what i get in console
Uncaught TypeError: Cannot read property 'person_name' of undefined
at Object.success (test ajax1.php:40)
bro in the PHP file try to identify every variable in the array to catch them in the script, take a look at this:
<?php
$rfc=$_POST['Rfc'];
$connection = mysqli_connect("localhost","root","","transferorders");
$query = mysqli_query($connection,"SELECT * FROM person where rfc_number ='$rfc'");
$row = mysqli_fetch_array($query)
$Data = '{"id":"'.$row['id_person'].'", "name":"'.$row['person_name'].'", "address":"'.$row['person_address'].'"}';
echo json_encode($Data);
?>
and the script:
success: function(msg){
var datashow = JSON.parse(msg);
$("#text2").val(datashow["id"]); ///this is the only value that i get
$("#text3").val(datashow["name"]); ///i want to get the person's name here
$("#text4").val(datashow["address"]);///i want to get the person's address here
},
I hope it helps!

jQuery - Check user input with php array

PHP function
function getSerialNumber(){
$upload_dir = wp_upload_dir();
$csvFile = $upload_dir['baseurl'].'/sample.csv';
$csv = $this->csv_to_array($csvFile); //read csv
foreach ($csv as $serialnum){
$serial_num_array[] = $serialnum['product_serial'];
}
$json_array = json_encode($serial_num_array);
return $json_array;
}
Return Value
["123456","789012"]
User input
<input name="product_serial" type="text" class="form-control login-field"
value="<?php echo(isset($_POST['reg_product_serial']) ? $_POST['reg_product_serial'] : null); ?>"
placeholder="Product serial number *" id="reg-product-serial" required/>
JS Code:
<script>
jQuery(document).ready(function($){
$.ajax({
url: "registration-form.php&f=getSerialNumber",
type: "GET"
success: function(data){
console.log('eureka');
}
});
$('input#reg-product-serial').on('blur', function() {
alert($(this).val()); //alerts user input
});
});
</script>
I am unable to call PHP function and pass json values in JS code to compare user input value for reg_product_serial.
How to fetch user input entered for product_serial and validate it
with php array returned ?
If that user input does not exists in array validate user by alert
message.
I didn't quite understand why do you have an ajax request to the form and why it's on the document ready event.
As far as I understood, the following is the code I came up with.
I haven't tested it but it should be enough for understanding the direction and main idea.
If you'd need further help add a comment.
validSerials.php
function compareSerialNumber($userSerial){
$validSerial = 0;
#Consider sanitizing the $userSerial variable (!!)
$upload_dir = wp_upload_dir();
$csvFile = $upload_dir['baseurl'].'/sample.csv';
$csv = $this->csv_to_array($csvFile); //read csv
foreach ($csv as $serialnum){
if($userSerial == $serialnum['product_serial'])
$validSerial = 1;
}
echo $validSerial;
}
echo compareSerialNumber($_GET['userSerial']);
die();
JS
<script>
jQuery(document).ready(function($){
$('input#reg-product-serial').on('blur', function() {
$.ajax({
url: "validSerials.php",
data: {userSerial: $(this).val() },
type: "GET"
success: function(res){
if(res == 1)
alert('Valid Serial');
else
alert('Invalid Serial');
}
});
});
});
</script>

Displaying different data in different table columns by switching options in a select

My problem is the following:
I have an ajax function that, according to the option (of a select) selected, associate a record in a database and populate another input, i.e. a p tag.
I have two td tags that have to be populated. Different data has to be displayed, so i want that, according to the input on the first select, on the second td there will be input y, in the third input z and so on... how can it be possible? If i try to append data to more than one tag, the same data is displayed in all the td columns.
Here i attach my code
Main.php
$(document).ready(function() {
$('#L_NAME0').change(function() {
var L_NAME0 = $("#L_NAME0").val();
$.ajax({
type: "POST",
url: "elaborazione_dati.php",
data: "L_NAME0=" + L_NAME0,
dataType: "html",
success: function(msg) {
$("#L_AMT0").html(msg);
$("#L_DESSERV").html(msg);
},
error: function() {
alert("Call failed");
}
});
});
});
Form.php
<label for="L_DESSERV">Descrizione del servizio</label>
<p class="L_DESSERV" id="L_DESSERV"></p>
</td
<td class="h4">
<label for="L_AMT0">Costo del servizio</label>
<p class="L_AMT0" id="L_AMT0"></p>
</td>
elaborazione_dati.php
$tipologia_selezionata = $_POST['L_NAME0'];
$sql = "SELECT * FROM acquisti WHERE durata = '$tipologia_selezionata' ";
$q = $db->prepare($sql);
$q->execute();
$q->setFetchMode(PDO::FETCH_ASSOC);
while($caratt = $q->fetch()) {
echo '<input readonly="readonly" type="hidden" name="L_NAME0" value="'.$caratt['durata'].'"/>';
echo '<input readonly="readonly" type="hidden" name="L_AMT0" value="'.$caratt['prezzi'].'"/>';
echo $caratt['prezzi']; ?> € <?php
}
Any suggestions?
Thanks a lot!
You need to split the results and the easiest way is to return JSON from PHP and then process it on your js code to generate the fields and text.
So in PHP something like:
while($caratt = $q->fetch()) {
$result->durata = $caratt[duratta];
$result->prezzi = $caratt[prezzi];
}
echo json_encode($result);
then in your js something like:
$('#L_NAME0').change(function() {
var L_NAME0 = $("#L_NAME0").val();
$.ajax({
type: "POST",
url: "elaborazione_dati.php",
data: "L_NAME0=" + L_NAME0,
dataType: "json",
success: function(data) {
$("#L_AMT0").html("<input type='hidden' name='L_NAME0' value='"+data.duratta+"'/>"+data.duratta);
$("#L_DESSERV").html("<input type='hidden' name='L_DESSERV' value='"+data.prezzi+"'/>"+data.prezzi+"€");
},
error: function() {
alert("Call failed");
}
});
However it seems confusing that you put another input named L_NAME0 - the id of your select control, but hey, it's your code... :)

Jquery Serialization not working

Have a simple form (only extract fields here) but for some reason the JQserilization is not working; looks fine in alert() but only the first form field gets posts. Suggestions please - thanks in advance
Form:
<form id="neweventform" method="post" action="">
<div class="grid_4 alpha">Setup date *</div>
<div class="grid_7 omega">
<select name="setup_day" id="setup_day"><?php days_list(); ?></select>
<select name="setup_month" id="setup_month"><?php month_list(); ?></select>
<select name="setup_year" id="setup_year"><?php year_list(); ?></select>
<div class="grid_11">
<input type="submit" name="createevent" value="Create" id="createevent" />
</div>
</form>
Jquery
$j(document).ready(function(){
$j('#neweventform').live('submit',function () {
var data= $j('#neweventform').serialize();
alert(data);
$j.ajax({type: "POST", url: "scripts/process.php",data: "newevent=newevent&event_options=" + data, cache: false, complete: function(data){
$j('#neweventform').fadeOut(2000),loading.fadeOut('slow'),$j('#content').fadeIn(2000), $j('#content').load('scripts/events.php #eventslist');
}
});
return false;
});
});
And the PHP processing
if(isset($_POST['newevent'])) :
$insert = mysql_query("INSERT INTO events (event_options) VALUES ('".$_POST['event_options']."')");
endif;
Any suggestions?
Have a look how serialize() works. It creates a string that, in your case, should look like this:
"setup_day=foo&setup_month=bar&setup_year=baz"
Then you concat this string with another (as data), which results in an invalid parameter string:
data: "newevent=newevent&event_options=" + data
// gets
"newevent=newevent&event_options=setup_day=foo&setup_month=bar&setup_year=baz"
Depending what type event_options is in your database (from the data in your form I assume it is a field containing a date), you might want to do this:
Javascript:
data: "newevent=newevent&" + data
PHP (sanitize the user input!):
if(isset($_POST['newevent'])) :
$date = $_POST['setup_year']. '-' . $_POST['setup_month'] . '-' . $_POST['setup_day'];
$insert = mysql_query("INSERT INTO events (event_options) VALUES ('". $date . "')");
endif;
first. Try doing a simple
<?php
print_r($_POST);
?>
to see what are you getting on the post var.
Second. Rename your parameter
var data
to something more "exclusive"
I don't recall at the moment if you can have a conflict with the "data" symbol used to make the call but at least you can start debugging from here.
Your data will be serialized into something like this:
setup_day=1&setup_month=2&setup_year=2010
You then construct your data like this:
newevent=newevent&event_options=setup_day=1&setup_month=2&setup_year=2010
This query string is wrong (two '=' without an '&') and probably this the root of your problem.
Try this:
$j.ajax({
type: "POST",
url: "scripts/process.php",
data: { newevent: newevent, event_options: $j('#neweventform').serialize() },
cache: false,
complete: function(data) {
...
}
});
OK, tried a mix of, but eventually got this to work:
$j(document).ready(function(){
$j('#neweventform').live('submit',function () {
var optdata= $j('#neweventform').serialize();
$j.ajax({
type: "POST",
url: "scripts/process.php",
data: "newevent=" + $j('#neweventform').serialize(),
cache: false,
complete: function(data) {
$j('#neweventform').fadeOut(2000),
loading.fadeOut('slow'),
$j('#content').fadeIn(2000),
$j('#content').load('scripts/events.php #eventslist');
}
});
return false;
});
});
then in the PHP
if(isset($_POST['newevent'])) :
$tryit = serialize($_POST);
$insert = mysql_query("INSERT INTO events (event_options) VALUES ('".$tryit."')");
endif;

Categories