The JSON seems to load into the array ok and it loads into the plain text objects.
The checkbox shows checked ON even though the data clearly shows its a 0
The data does not load at all
The plain text works great
Here is the JSON
[{"0":"0","drscomplete":"0","1":"2016-03-12","drsremind":"2016-03-12","2":"db","drsby":"db"}]
This works:
<input name="drsby" type="text" id="drsby" readonly />
This load checked ON even though the data says 0:
<input name="drscomplete" type="checkbox" id="drscomplete" value="1" />
and this doesnt load at all:
<input name="drsremind" type="date" id="drsremind" />
Here is the php that does the load:
jQuery.ajax({
url: "dealfinalizeload.php",
data:'id='+id,
type: "POST",
success:function(data){
var data2 = $.parseJSON(data);
$('div#white_content_dealfinalize').loadJSON(data2);
alert(data);
},
error:function (){
alert("Error loading tasks");
}
});
this is the php that load the JSON
$SQL ="SELECT drscomplete, drsremind ,drsby from dealfinalize d where d.ID=" . $id;
$resultArray = array();
$result = mysqli_query($con,$SQL);
if($result->num_rows >0 )
$resultArray = mysqli_fetch_all($result,MYSQLI_BOTH);
echo json_encode($resultArray);
Any ideas what I did wrong?
Related
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 } ?>
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!
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... :)
I have an ajax call for a form submit; it works fine if I pass my sql arguments when I hard code them, however if I want to pass my sql query arguments with inputs (from View) in my model it says: Message: Undefined index: startDate and endDate.
Here is my View:
<?PHP
$formData2 = array(
'class' => 'form-horizontal',
'id' => 'frm2',
);
echo form_open('gallery/fetchAssociates', $formData2);
?>
<input id="startDate" class="span2" size="16" type="text" />
<input id="endDate" class="span2" size="16" type="text" />
<input type="submit" class="btn btn-primary"
value="Submit" id="querystartEnd" name="querystartEnd" />
<?PHP
echo form_close();
?>
and my javascript for AJAX call is as following:
$.ajax({
type: "POST",
async: false,
dataType: "json",
?>",
url: "<?php echo base_url('gallery/fetchAssociates') ?>",
success: function(data) {
html = "<table id='myTable'><thead><tr id='test'><th>ID</th><th>Start Date</th><th> LName</th></tr></thead><tbody id='contentTable'>";
for (var i = 0; i < data.length; i++)
{
html = html + "<tr id='trResponses' ><td><div >" + data[i]['id']
+ " </div></td><td><div >" + data[i]['start'] +
"</div> </td><td><div >" + data[i]['username'] +
"</div></td></tr>";
}
html = html + "</tbody></table>";
$("#resultFrm2").html(html);
},
error: function()
{
alert('error');
}
});
and here is my controller:
public function fetchAssociates() {
//echo($_POST["startDate"]);
//echo($_POST["endDate"]);
//die();
$this->load->model('user_model');
echo json_encode($this->user_model->getAll());
}
and my Model method is as following:
public function getAll()
{
$wtc = $this->load->database('wtc', TRUE);
$sql = "SELECT username, MIN(timeIn) as start
FROM tc_timecard
GROUP BY userid having MIN(timeIn) > ? and MIN(timeIN) < ?
order by MiN(timeIN);";
//$q = $wtc->query($sql, array('2013-01-08', '2013-01-23'));
$q = $wtc->query($sql, array($this->input->post('startDate'),
$this->input->post('endDate')));
if ($q->num_rows() > 0)
{
foreach ($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
}
As you see my comments in my code: if I have
//echo($_POST["startDate"]);
//echo($_POST["endDate"]);
uncommented in firebug in response it says "Message: Undefined index: startDate and endDate."
Also in my controller if I have
// $q = $wtc->query($sql, array('2013-01-08', '2013-01-23'));
un-commented it works but once I want to pass the inputs by the following line of code it does not work :
$q = $wtc->query($sql, array($this->input->post('startDate'), $this->input->post('endDate')));
What can be the reason that I cannot access my inputs in my controller or Model?
If it is not clear for you, please let me know which part you need more clarification.
EDITED:
It is worth mentioning that my ajax call is inside the following block:
$('#frm2').submit(function(e)
{
e.preventDefault();
//My AJAX call here
});
Many thanks in advance,
You are not passing any data through ajax
// Collect data from form which will be passed to controller
var data = {
start_data : $('#startDate').val(),
start_data : $('#endDate').val(),
}
$.ajax({
type: "POST",
async: false,
dataType: "json",
data : data // data here
url: "<?php echo base_url('gallery/fetchAssociates') ?>",
success : function(data){
// Success code here
},
error: function(data){
// error code here
}
})
i need all values from database if i click button(get values) how can
i ? please assist me any one
is there any way to do this ?
this is my index.php
<script type="text/javascript" src="jquery-1.10.1.js"></script>
<form>
<h1>Insert Data Into mySQL Database</h1>
Name <input name="name" type="text" id="name"> <br><br>
Lastname <input name="lastname" type="text" id="lastname"><br><br>
Email <input name="email" type="text" id="email"><br><br>
<input type="button" name="Submit" value="Submit" onclick="insertData()">
</form>
<button type="button">get values</button>
<div id="jcontent"></div>
<script type="text/javascript">
/* * Checking the Login - * */
function insertData(){
var data_get = {
'name_form': $('#name').val().trim(),
'lastname_form': $('#lastname').val().trim(),
'email_form': $('#email').val().trim()
};
$.ajax({
url : 'insert_ac.php',
type : 'POST',
data : data_get,
timeout : 30000,
success : function(response_data, text, xhrobject) {
console.log(text);
if(text == "success"){
$('#jcontent').html('Data Inserted');
}
else if(text == "ERROR"){
$('#jcontent').html('data not inserted');
}
}
});
}
</script>
/*******************************************************/
this is my insert.php
<?php
mysql_connect('localhost','root','');
mysql_select_db('loginthree');
$table_name = "test_three";
$name_form=$_POST['name_form'];
$lastname_form=$_POST['lastname_form'];
$email_form=$_POST['email_form'];
$sql="INSERT INTO $table_name(name, lastname, email)VALUES('$name_form', '$lastname_form', '$email_form')";
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Success";
} else {
echo "ERROR";
}
?>
<?php
// close connection
mysql_close();
?>
i need all values from database if i click button(get values) how can
i ? please assist me any one
is there any way to do this ?
Well firstly, insert a:
return false;
at the end of your insertData() function, in that way you prevent the refresh of the page so that the ajax call can load its data.
Second you are returning Success and you are trying to read success, it's case sensitive and your code will not reach that if.
Resolve these issues and get back to me
Make a PHP script (lets name it getvalues.php) to return the values from the database into JSON, such as:
$result = mysql_query("SELECT * FROM $you_table"); //mod query to match what you need to fetch
$array = mysql_fetch_row($result);
echo json_encode($array);
Then in your script above include jQuery and use something along the lines of the following to retrieve the data:
$(function ()
{
$.ajax({
url: 'getvalues.php',
data: "",
dataType: 'json',
success: function ( values )
{
var value1 = values[0]; //value1, value2, etc should represent the field names in your database
var value2 = values[1];
//and so on and so forth. each field in you DB should be one index in your values array
$('#output').html("<b>Value 1: </b>"+value1+"<b> Value 2: </b>"+value2);
}
});
});