convert form data using serializeArray() and sending php via .Ajax - javascript

This is my first post. I have searched for other solutions and what I've found only deals with components of this question. Basically this is what I'd like to do:
Capture form data (tested, working);
Convert form data using serializeArray() or serialize() (tested both options, working and outputs to console correctly);
Send this information to the server through Ajax (not working); and
PHP saves array as a CSV (not yet started).
Bellow is the code I'm using. But first, here are some alternatives I've tried. Usually I get this: array(0) { }
'dataType' as Json - returns error;
'GET', 'POST' and 'REQUEST' - PHP shows empty array;
use form.serialize() - PHP shows empty array;
use form.serializeArray() - PHP shows empty array; and
var_dump($_POST), var_dump($_GET), var_dump($_REQUEST).
var serialisedForm = $(form).serializeArray();
var serialisedData = JSON.stringify(serialisedForm);
console.log(serialisedData); //working
console.log(serialisedForm); //working
$.ajax({
type: "POST",
url: "datacapture.php",
data: {
serialisedForm, //tested using serialisedData as well
},
success: function() {
window.open('datacapture.php');
},
error: function() {
alert("the form data has not been sent to the server");
}
})
and here is the datacapture.php script I'm using to test the information flow.
<?php
var_dump($_POST);
?>
EDIT - and here is a sample form item, reading .text and .name from my settings.json file:
<tbody>
{
this.props.settings.schemes[0].questions.map((q, i)=> {
return <tr><td>{q.text}</td><td><div class="YesNo"><input type="radio" required name={q.name} value="yes">Yes</input><input type="radio" required name={q.name} value="no">No</input></div></td></tr>
})
}
</tbody>

just change 1seralisedForm1 to 1seralisedData1 it will return an json object to php which can be seen by doing:
echo json_decode($_POST);

Related

How to get a multidimensional array after submitting my form from javascript into PHP?

One php file with php and javascript inside. I have a multidimensional array defined in the javascript part. I can see the proper output of "key" and "value" in the console but I do no get the array into php after submitting my form.
What I am doing wrong?
<?php
echo "Postcmd: ".$_POST["postcmd"];
print_r($_POST["postcmd"]);
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
var postcmd =[];
var key;
function formsubmitplus(ele) {
postcmd.push({"key": ele.id, "value": ele.value});
for (key in postcmd) {
if (postcmd.hasOwnProperty(key)) {
console.log(postcmd[key])
}
}
request = $.ajax({
url: "/index.php",
type: "post",
data: postcmd
});
}
</script>
Not even this simple and often found script example works for me - what else might be the issue? Are there other (basic) things to know about js->PHP?
<?php
// index.php
?>
<html>
<head>
<title>Pass JS array to PHP.</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
var arrayfromjs = "123";
$.ajax({
type: "POST",
url: "index.php",
data: { testArray : arrayfromjs},
success: function() {
alert("Success");
}
});
</script>
</head>
<body>
<?php
echo "<br>Pass JS array to PHP.<br>";
$myArray = $_POST['testArray'];
print_r($myArray);
?>
</body>
</html>
Per the jQuery documentation,
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
Thus, your data field must contain an object (such as {foo: bar, foo_again: bar_again}; in PHP, this would read as $_POST['foo'] == "bar"). However, your code submits an array with one element: the object specified. In addition, PHP does not magically turn your JS array/object into a PHP array. You have to parse the string passed into PHP and turn it into the array you need.
If you print $_POST, you can see what exactly is being passed into your PHP. That might help you see what is happening.
You are creating the following structure using the push method:
[
{
"key":"first_name",
"value": "Bob"
}
]
Using your code, all you need to do is index the postcmd variable to the object. You also had some indexing issues with your loop. The key variable would just be index 0. So you would need to set it to postcmd[key] to check for the key named "key".
function formsubmitplus(ele) {
postcmd.push({"key": ele.id, "value": ele.value});
for (key in postcmd) {
if (postcmd[key].hasOwnProperty("key")) {
console.log(postcmd[key].key)
}
}
request = $.ajax({
url: "/index.php",
type: "post",
data: postcmd[0]
});
}
Using the above snippet, jQuery will then parse the data into the correct key value pairs. Without specifying the index, the data would be posted as undefined=Bob
On the PHP side you should be able to grab those values as such:
<?php
echo $_POST['key'].PHP_EOL;
echo $_POST['value'];
?>
Alternative Method - JSON Submission
You could make the following modification to post the data as JSON:
function formsubmitplus(ele) {
for (key in postcmd) {
if (postcmd[key].hasOwnProperty("key")) {
console.log(postcmd[key].key)
}
}
request = $.ajax({
url: "/index.php",
type: "post",
contentType: 'application/json',
data: JSON.stringify(postcmd)
});
}
Then on the PHP side you can grab the POST body using the following:
<?php
echo "<pre>";
$json_data = json_decode(file_get_contents('php://input'), true);
print_r($json_data);
?>
If you would rather work with a PHP Object vs an Associative array. Just change true to false.
Ad the end I found a solution without jquery which works for me the best.
It is "playing" with HIDDEN form fields.
Maybe someone finds it helpful:
function submitform() {
Object.getOwnPropertyNames(postcmd).forEach(function(val, idx, array) {
var outarrayoutput = val + ' ==== ' + postcmd[val];
console.log(outarrayoutput);
var newHidInp = document.createElement('input');
newHidInp.type = 'hidden';
newHidInp.name = 'outArray[]';
newHidInp.value = outarrayoutput;
maintable.appendChild(newHidInp);
});
document.maintable.submit();
}

How to bring a json result into PHP

I have some results from a fetch.php using json and I successfully brought all results to my bootstrap modal HTML screen.
When the Modal is being shown, I would like to run a MYSQL query using a value coming from the same json I used for the modal, however I can't put this value into a PHP variable to run the SQL query.
How can I get this?
I am trying to bring the same value I input into the HTML textbox (modal), but it is not working. I also tried to use the value from json '$('#PCR').val(data.PCRNo);)', but nothing happen.
This is the script to collect information from database using fetch.php file:
<script>
$(document).ready(function(){
$('#table').on('click', '.fetch_data', function(){
var pcr_number = $(this).attr('id');
$.ajax({
url:'fetch.php',
method:'post',
data:{pcr_number:pcr_number},
dataType:"json",
success:function(data){
$('#PCR').val(data.PCRNo);
$('#PCC').val(data.PCC);
$('#PCR_Creation').val(data.Creation_Date);
$('#PCR_Status').val(data.Stage);
$('#Required_Completion').val(data.Required_Completion);
}
});
});
});
</script>
This is the PHP code
<?php
//trying to get the value I have included on #PCR (textbox) which has ID='PCR' and name ='PCR' **
$PCR= $_POST['PCR'];
//running now the code to check if the database has the value and return the desired response to be shown **
$sql1 = mysqli_query($dbConnected,"SELECT * FROM change_management.tPCN");
while ($row1 = mysqli_fetch_array($sql1)) {
if ($row1['PCRNo']==$PCR){
echo $row1['PCNNo'];
echo "<br/>";
}else{
}
}
?>
I would like include value from this val(data.PCRNo) json return into the $PCR variable, so the MYSQL query is going to work
There are a number of quite basic logical issues with your code which are preventing it from working.
1) data: { pcr_number: pcr_number}- the name pcr_number doesn't match the value PCR which the server is searching for using $_POST['PCR'];. The names must match up. When making an AJAX request, the name you gave to the form field in the HTML does not matter (unless you use .serialize()) because you are specifying new names in the data parameter.
2) Your SQL query doesn't make sense. You seem to be wanting to read a single row relating to a PCR number, yet your query makes no usage of the input PCR value to try and restrict the results to that row. You need to use a SQL WHERE clause to get it to select only the row with that ID, otherwise you'll fetch all the rows and won't know which one is correct. (Fetching them all and then using an if in a PHP loop to check the correct one is very inefficient.) I wrote you a version which uses the WHERE clause properly, and passes the PCR value to the query securely using prepared statements and parameters (to project against SQL injection attacks).
3) Your output from the PHP also makes no sense. You've told jQuery (via dataType: "json" to expect a JSON response, and then your code inside the "success" function is based on the assumption you'll receive a single object containing all the fields from the table. But echo $row1['PCNNo']; echo "<br/>"; only outputs one field, and it outputs it with HTML next to it. This is not JSON, it's not even close to being JSON. You need to output the whole row, and then use json_encode() function to turn the object into a JSON string which jQuery can parse when it receives it.
Here's a version of the code containing all the above changes:
JavaScript:
$(document).ready(function(){
$('#table').on('click', '.fetch_data', function(){
$.ajax({
url: 'fetch.php',
method: 'post',
data: { pcr: $(this).attr('id'); },
dataType: "json",
success: function(data){
$('#PCR').val(data.PCRNo);
$('#PCC').val(data.PCC);
$('#PCR_Creation').val(data.Creation_Date);
$('#PCR_Status').val(data.Stage);
$('#Required_Completion').val(data.Required_Completion);
}
});
});
});
PHP:
<?php
$PCR = $_POST['pcr'];
$stmt = $dbConnected->prepare("SELECT * FROM change_management.tPCN WHERE PCRNo = ?");
$stmt->bind_param('s', $PCR);
$stmt->execute();
$result = $stmt->get_result();
//an "if" here will cause a single row to be read
if ($row = $result->fetch_assoc()) {
$output = $row;
}
else
{
$output = new StdClass();
}
$stmt->free_result();
$stmt->close();
//output the result
echo json_encode($output);
?>
N.B. I would potentially suggest studying some tutorials on this kind of subject, since this is a fairly standard use case for AJAX/JSON, and you should be able to find samples which would improve your understanding of all the different parts.
P.S. Currently the PHP code above will return an empty object if there is no matching row in the database. However, this is probably an error condition (and will cause your JavaScript code to crash due to trying to read nonexistent properties), so you should consider how you want to handle such an error and what response to return (e.g. 400, or 404, and a suitable message).
You need to first return json from php by using json_encode.
Inside this loop
while ($row1 = mysqli_fetch_array($sql1)) {
$data = array('PCRNo' => 'itsvalue', 'PCC' => 'itsvalue', 'Creation_Date' => 'itsvalue')
}
print json_encode($data)
store all the data in an associative array and then convert it into json using json_encode and return the json.
Use json data in you ajax file
$.ajax({
url:'fetch.php',
method:'post',
data:{pcr_number:pcr_number},
dataType:"json",
success:function(data){
var data = JSON.parse(data);
$('#PCR').val(data.PCRNo);
$('#PCC').val(data.PCC);
$('#PCR_Creation').val(data.Creation_Date);
$('#PCR_Status').val(data.Stage);
$('#Required_Completion').val(data.Required_Completion);
}
});
Below is the changed script to store different values in $PCR variable
<script>
$(document).ready(function(){
var i = 1;
$('#table').on('click', '.fetch_data', function(){
if(i == 1) {
var pcr_number = $(this).attr('id');
} else {
var pcr_number = $('#PCR').val();
}
$.ajax({
url:'fetch.php',
method:'post',
data:{pcr_number:pcr_number},
dataType:"json",
success:function(data){
$('#PCR').val(data.PCRNo);
$('#PCC').val(data.PCC);
$('#PCR_Creation').val(data.Creation_Date);
$('#PCR_Status').val(data.Stage);
$('#Required_Completion').val(data.Required_Completion);
i++;
}
});
});
});
</script>

How to visualize a codeigniter array from a query on my view?

On my model I have the following function which is a query to inner join 3 tables
function get_all_listaproveedorfamilia($clave)
{
$this->db->select('proveedor.razonSocial, proveedor.nombre1, proveedor.telefonoFijo1, proveedor.telefonoMovil1, proveedor.correoElectronico1, proveedor.tipo, familia.clave');
$this->db->from('proveedor');
$this->db->join('relacionproveedorfamilia', 'relacionproveedorfamilia.idProveedor = proveedor.id', 'inner');
$this->db->join('familia', 'familia.id = relacionproveedorfamilia.idFamilia', 'inner');
$this->db->where('familia.clave', $clave);
$this->db->order_by('proveedor.razonSocial');
$query = $this->db->get();
if($query->num_rows() > 0){
return $query->result_array();
}
}
The $clave value is a string retrieved from a select dropdown, and I send it to my controller using ajax
Jquery function in my view to send $clave value
$('#idFamilia').change(function(){
var clave = $("#idFamilia option:selected").text();
if (clave != "Seleccione"){
$.ajax({
url: '<?php echo base_url(); ?>index.php/Proveedor/obtenerListaProveedorFamilia',
method: 'POST',
data: {
clave: clave
}
});
}
});
Here is the code from my controller, where I use the clave value and call the function in my controller
function obtenerListaProveedorFamilia(){
$this->load->model('Proveedormodel');
$clave = $_POST['clave'];
$data['listaproveedorfamilia'] = $this->Proveedormodel->get_all_listaproveedorfamilia($clave);
$data['_view'] = 'proveedor/index';
$this->load->view('layouts/main',$data);
}
I want to visualize the array returned by the function to check if the query is working and getting the values i want to retrieve. I have already tried the following methods to visualize the array adding addtional code to my jquery function $('#idFamilia').change(function(){});
-Get the array from the view and check it on the browser's console
var test = <?php echo json_encode($listaproveedorfamilia); ?>;
console.log(test);
-Trying to append print_r to a pre tag
$('#prueba').append('<?php print_r($listaproveedorfamilia) ?>');
With both options I get the following PHP error on my view
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: listaproveedorfamilia
Filename: proveedor/index.php
This error appears as soon as the page loads, but it should wait for the user to select an option from the select dropdown and then use that option to build the query. How can I fix this and check the content of my array?
You need to add the success method to your ajax call. This is where the data created at the server will be sent.
$('#idFamilia').change(function () {
var clave = $("#idFamilia option:selected").text();
if (clave != "Seleccione") {
$.ajax({
url: '<?php echo base_url(); ?>index.php/Proveedor/obtenerListaProveedorFamilia',
method: 'POST',
data: {
clave: clave
},
success: function (returned) {
console.log(returned);
}
});
}
});
You can use your browser's web dev tool to see what the javascript console has logged.
Because we don't know what the view file contains it's hard to comment on what to expect.
Typically ajax calls are used to return html that return is put into the DOM using $("some_selector").html() or a variety of other DOM manipulation methods to update the current browser screen.
Another way to "visualize" the return would be to simply append it to what is already on the screen. This is not likely what you'll eventually want. But you'll be able to see what came back.
Change the success function to this
success: function (returned) {
$('body').append(returned);
}

display ajax called data in an UI

i have been able to fetch data with an ajax call from active directory .
the php file used to make the ajax call to active directory :http://pastebin.com/tSRxwQL8
The browser console shows that an ajax call returns this :
<p> sn: xxxxxx<br/>givenname: xxxxx<br/>
employeeID: 0050<br/
>distinguishedName: CN=xxxx xxxxx,OU=Employees,OU=Accounts,OU=India,DC=asia,DC=xxxxxxx,DC=com<br/>
displayName: Mark Hewettk<br/>sAMAccountName: xxxxxxx<br/>
department: xxxxx<br/>manager: CN=xxxxxx xxxxxxx,OU=Employees,OU=Accounts,OU=India,DC=asia,DC=xxxx,DC=com
<br/>
mail: mhewettk#abc.com<br/>
title: xyz<br/>
I want to take only some attributes above like mail,displayname etc and display in my HTML :
<h2 class="profile__name" id="emailOfUser">Email : </h2>
Now the problem is the jquery that I have used here :
$('.leaderboard li').on('click', function() {
$.ajax({
url: "../popupData/activedirectory.php", // your script above a little adjusted
type: "POST",
data: {
id: $(this).find('.parent-div').data('name')
},
success: function(data) {
console.log(data);
$('#popup').fadeIn();
$('#emailOfUser').html(data); //this line displays all data whereas I want to select only email,displayname from the above console data
//whatever you want to fetch ......
// etc ..
},
error: function() {
alert('failed, possible script does not exist');
}
});
});
problem is this :
$('#emailOfUser').html(data);
this line displays all data whereas I want to select only email,displayname from the above console data
kindly help me how to select only desired attribute data from the above browser console data.
Ideally you should return JSON from PHP file, however if it is not possible for you to make changes to PHP file then you can use split("mail:") and split("title:") to extract data
success: function(data) {
console.log(data);
$('#popup').fadeIn();
var email=(data.split("mail:")[1]).split("title:")[0];
$('#emailOfUser').html(email); //this line displays all data whereas I want to select only email,displayname from the above console data
//whatever you want to fetch ......
// etc ..
},
You are getting response in HTML which makes difficult for you to extract mail, displayname, etc.
You should get the response in JSON which will make it easy for you to extract the required info.
Ask your back-end team to send response in JSON format.
Working Fiddle
Try :
var lines = 'sn: xxxxxx<br/>givenname: xxxxx<br/>employeeID: 0050<br/>distinguishedName: CN=xxxxxxxxx,OU=Employees,OU=Accounts,OU=India,DC=asia,DC=xxxxxxx,DC=com<br/>displayName: Mark Hewettk<br/>sAMAccountName: xxxxxxx<br/>department: xxxxx<br/>manager: CN=xxxxxx xxxxxxx,OU=Employees,OU=Accounts,OU=India,DC=asia,DC=xxxx,DC=com<br/>mail:mhewettk#abc.com<br/>title:xyz<br/>'.split('<br/>');
jQuery.each(lines, function() {
var val = this;
if (val.indexOf('mail') > -1)
// alert(val.split(':')[1]); //Only for test
$('#emailOfUser').html(val.split(':')[1]);
});

AJAX call working on local server but not online

When a user goes to one of the pages (let's call it page1), the PHP loads the HTML content for an array containing data about the users.
Once the page is loaded (DOM ready), I use jQuery to perform an AJAX call to retrieve the HTML for that array of data. I do this to get the benefit of using separate PHP template files. In this way, PHP will call the PHP template for every array in the bi-dimensionnal array and return the HTML.
page1.php:
<script type="text/javascript">
var globalArray = <?php echo json_encode($freres); ?>;
jQuery(function($) {
liste(); // Ajax call to get HTML for the data in "globalArray"
});
</script>
AJAX call:
function liste() {
$.ajax({
data : {
array : globalArray,
dataName : 'someName',
file : 'templates/t_item_file'
},
dataType : 'html',
success : function(data, textStatus, jqXHR) {
var table = $('table');
var rows = $('<table>' + data + '</table>').find('tr');
rows.each(function(i, e) { // insert with fade-in animations
var row = $(e);
row.hide();
table.append(row);
row.delay(i * 15).fadeIn(250);
});
},
type : 'GET',
url : config.site + 'ajax/view' // configured in header
});
}
Somewhere in t_header.php:
<script type="text/javascript">
var config = {
base : "<?php echo base_url(); ?>",
site : "<?php echo site_url(); ?>"
};
</script>
The config route that redirects to ajax/view/...
$route['ajax/(:any)'] = 'c_ajax/$1';
The method of the controller c_ajax that handles the AJAX call:
public function view() {
$file = $this->input->get('file');
$array = $this->input->get('array');
$dataName = $this->input->get('dataName');
foreach ($array as $vars) {
$data[$dataName] = $vars;
$this->load->view($file, $data);
}
}
When I do this using EasyPHP on localhost, everything works fine, and I receive the HTML as expected, something like :
<TR>
<TD>...</TD>
//...
</TR>
<TR>
//...
And then I insert it into a table. But, when I try to do it on my website in FireBug, I can see that the AJAX response is not 200, but 302 Moved Temporarily.
Can anyone help me to figure out what to do to get it to work, because I spend almost the last four days learning jQuery and AJAX, and it doesn't work (online only).
Instead of
file : 'templates/t_item_file'
give full path of the controller
eg:"http://www.yourdomain.com/---/templates/t_item_file"
Problem solved. I load the HTML data in PHP and pass it to JavaScript, and then use jQuery to animate DOM Elements.
Previously, I didn't pass HTML but raw data in a PHP array, and then tried to get the HTML for all the elements of thie array via Ajax (HTML for all elements in only one call). I think there was too many parameters in the request and that's probably was caused the error.

Categories