AJAX POST of multidimensional array- writing to MYSQL database with PHP - php

With thanks to Elf Sternberg (I couldn't get your solution working, sorry), I think I am heading in the right direction, but I am having trouble writing the php to the mysql database.
The original post: jQuery AJAX POST to mysql table for dynamic table data- Am I doing this in anything like the right way?
Firstly, the dynamic table form on my webpage has multiple user input data, and I am using this jQuery function and the AJAX call to send to a php file. Am I correctly creating the multidimensional array here? Firebug shows dataString to have all the data I want, but the POST parameters and source just say dataString. Also the alert function shows the data is all there:
EDIT: With thanks to Jancha and Andrew, I have changed the data source for the AJAX post. The database is being written to now, but only BLANK data gets written, for as many entries as were in the table. The firebug console is showing all the data as it should look in the post. I just don't know how to structure the php loop now.
jQuery(function() {
jQuery(".button1").click(function() {
// process form here
var rowCount = jQuery('#dataTable tr').length;
var dataString = [];
dataString.length = rowCount - 2;
for(var i=2; i<rowCount; i++) {
var txtRow1 = jQuery('#txtRow' + (i-1)).val();
var tickerRow1 = jQuery('#tickerRow' + (i-1)).val();
var quantRow1 = jQuery('#quantRow' + (i-1)).val();
var valueRow1 = jQuery('#valueRow' + (i-1)).val();
// previous code: dataString[i-2] = 'txtRow1='+ txtRow1 + '&tickerRow1=' + tickerRow1 + '&quantRow1=' + quantRow1 + '&valueRow1=' + valueRow1;
// new code:
dataString[i-2] = [txtRow1, tickerRow1, quantRow1, valueRow1];
}
//alert (dataString);return false;
jQuery.ajax({
type: "POST",
url: "form_action2.php",
data: { 'data': dataString }
});
return false;
});
});
If this is sending the data okay then I am thinking that the php function needs to look something like this:
Could I have help with the php function please. Thankyou for your time.
$data = $_POST['data'];
foreach ($data as $key => $value){
$txtRow1 = $data['txtRow1'];
$tickerRow1 = $data['tickerRow1'];
$quantRow1 = $data['quantRow1'];
$valueRow1 = $data['valueRow1'];
$sqlinsert = "INSERT INTO stock_port (name, ticker, quantity, value) VALUES ('$txtRow1', '$tickerRow1', '$quantRow1', '$valueRow1')";
mysql_query($sqlinsert, $conn);
}
FINAL EDIT: Ok so this works to enter the data into the database:
$data = $_POST['data'];
foreach ($data as $value){
$txtRow1 = $value[0];
$tickerRow1 = $value[1];
$quantRow1 = $value[2];
$valueRow1 = $value[3];
$sqlinsert = "INSERT INTO stock_port (name, ticker, quantity, value) VALUES ('$txtRow1', '$tickerRow1', '$quantRow1', '$valueRow1')";
mysql_query($sqlinsert, $conn);
}
It seems using data: {'data':dataString} in the AJAX jQuery call means I lost all the variable names of the data sent in the array to POST. Even though this is working, it doesn't feel like the way it should have been done. I have seen others use array structure in their id or names for input on forms, and that seems like it should have been the way to go.

change data: "dataString" to data: dataString or else you are not passing variable but a 'string'.

there is a problem with your foreach statement try this
$data = $_POST['datastring'];
foreach($data as $key => $value){
$txtRow1 = $data['txtRow1'];
}
It is not tested still you try once

Related

Multiple AJAX calls - 1st to fetch data and turn into JSON object & 2nd to update $_SESSION info

I have an ajax call which pulls data from the table and then transforms into a JSON object
Because I am also doing a lot with PHP as well I need to have a 2nd AJAX call
immediately after the first that will update $_SESSION info
I have tried putting
$_SESSION['company_id'] = $_POST['companyid'];
in the same file that handles the 1st AJAX call but it then doesn't process the data from the first call, hence I need to do the 2nd call
Here is my jQuery Code for the 1st and 2nd AJAX query
$(".showcompinfo").click(function(){
$("#comptable").hide();
$("#showcomptable").show();
var id = $(this).attr('id');
$("#comp_info").toggle();
var companyid = id;
var dataString = "companyid="+companyid;
$.ajax({ /* THEN THE AJAX CALL */
type: "POST",
url: "../inc/dataforms/complist.php",
data: dataString,
success: function(result){
var jsonObject = JSON.parse(result);
// here you can do your magic
var approved = jsonObject.customer_approved;
$("#showcompname").text(jsonObject.name);
// Get Reg Address Details - Check if any field is empty
var regoffice_2 = '';
var regoffice_3 = '';
var regoffice_city = '';
console.log(jsonObject.regoffice_city);
if(jsonObject.regoffice_2)
{
regoffice_2 = ', ' + jsonObject.regoffice_2;
};
if(jsonObject.regoffice_3)
{
regoffice_3 = ', ' + jsonObject.regoffice_3;
};
if(jsonObject.regoffice_city)
{
var regoffice_city = ', ' + jsonObject.regoffice_city;
};
var addlne1 = jsonObject.regoffice_1;
var regaddress = jsonObject.regoffice_1 + regoffice_2 + regoffice_3 + regoffice_city;
$("#addline1").val(jsonObject.regoffice_1);
$("#addline2").val(jsonObject.regoffice_2);
$("#addline3").val(jsonObject.regoffice_3);
$("#addcity").val(jsonObject.regoffice_city);
$("#addcounty").val(jsonObject.regoffice_county);
$("#countryselected").val(jsonObject.regoffice_country);
$("#countryselected").text(jsonObject.regoffice_country);
$("#addpostcode").val(jsonObject.regoffice_postcode);
console.log(regaddress);
if(approved == '1')
{
$("#approvedcust").text('Yes');
} else {
$("#approvedcust").text('Customer but Not Approved');
};
}
});
// 2nd Ajax
var companyid2 = jsonObject.company_id;
var dataString2 = "companyid="+companyid2;
$.ajax({ /* THEN THE AJAX CALL */
type: "POST",
url: "../inc/updatesession.php",
data: dataString2,
success: function(){
}
});
//
Here is the PHP code for complist.php
if(!empty($_POST['companyid']))
{
$companyid = $_POST['companyid'];
$query = mysqli_query($dbc,"SELECT * FROM `comp_companies` WHERE `company_id` = '$companyid'");
$result = mysqli_fetch_assoc($query);
if($result){
$newdata = json_encode($result);
}
}
print_r($newdata);
If anyone can help even consolidate this into 1 ajax query or help me get 2 calls
working correctly it would be much appreciated
** EDIT **
OK I now have it displaying the Company ID in the session variable however when the user clicks to view a different company info result the session company_id does not update
I have changed the complist.php to the following
if(!empty($_POST['companyid']))
{
unset($_SESSION['company_id']);
$companyid = $_POST['companyid'];
$query = mysqli_query($dbc,"SELECT * FROM `comp_companies` WHERE `company_id` = '$companyid'");
$result = mysqli_fetch_assoc($query);
if($result){
$_SESSION['company_id'] = $_POST['companyid'];
$newdata = json_encode($result);
}
}
print_r($newdata);
My thinking behind the above was that once the ajax call is made it immediately unsets the session variable company info
then once a result is found for the selected company it resets the session var company_id with the new value, however its not updating the session variable
Screenshots showing what I mean
Your code updates your session variable successfully. However, since you're making an AJAX call, only the code in the PHP script directly called by the AJAX ("complist.php" in this case) is executed on the server. None of the PHP code which originally used to create your page is run again - this is why you have to use JavaScript to populate the rest of your newly selected company details.
To update the ID on screen following the AJAX call, all you need to do is follow the pattern you've used to update the rest of the fields
Change your HTML so the element which contains the company ID has an ID which lets JavaScript identify it:
<span id="showcompname"></span><span id="showcompid"><?php echo $_SESSION['company_id'];?></span>
and then in the "success" callback of your AJAX code, write
$("#showcompid").text(jsonObject.company_id);
This is exactly the same concept as the other JavaScript code you've got e.g. to update the "showcompname" element.
Meanwhile, the value stored in your PHP session will be used next time you run the PHP code which updates the whole page (e.g. by refreshing the page).

Trying to build a json object to send to laravel. Problems with key name

I am trying to make a key and value array to send to my laravel backend.
this is my current code
$http.post('../survey/'+$scope.clientID+'/getSurvey', {client: $scope.clientID }).
success(function(data, status, headers, config) {
console.log(data);
$scope.survey_id = data[0];
$scope.questions = data;
//$scope.dLength = data.length;
$scope.dLength = 5;
console.log($scope.questions);
// When an answer button is clicked
$scope.clicky = function(value) {
// Add a class to hide the div cntainng the question
$scope.class = "hideit";
//Set a timeout function so the question can fadeOut before we proces anything
var callAtTimeout = function() {
// Check to see if this is the last question
if($scope.qid >= $scope.dLength -1){
// All questions have been answered. AJAX the data back to Laravel
alert("complete")
$http.post('../survey/'+$scope.survey_id.survey_id+'/submitSurvey', {data: angular.fromJson($scope.answers)}).
success(function(data, status, headers, config) {
console.log(data);
})
//})
//console.log($scope.answers)
}else{
//Build up the Array of answeres
// Get Question name - this will be the key
var questionName = $scope.questions[$scope.qid].name;
// This is the value
var questionAnswer = value
//build the aray element
var line = { questionName : value };
//Push it to the array
$scope.answers.push({questionName: questionAnswer});
//console.log($scope.answers)
//add to the count variable
$scope.qid += 1;
// Animate the question div back up to display the next question
$scope.class = "showit";
}
}
$timeout(callAtTimeout, 1000)
}
}).
When I look at the data I am building it is showing questionname as the key instead of the data that is in the variable question name.
When I alert the variable question name it shows the correct data, but the array is just showing the key as "questionname", Am I building the array wrong, if so how should I be building it?
If I understand you right, you may try to build it like that:
var question = {};
question[questionName] = questionAnswer;
$scope.answers.push(question);
Also, it looks like with ECMAScript 6 it will be possible to achieve the same thing in a slightly prettier manner:
$scope.answers.push({ [questionName]: questionAnswer});
UPD:
According to the comments, you don't need to create an array, but build an object instead. It might be something like this:
$scope.answers = {};
// loop through the questions:
$scope.answers[questionName] = questionAnswer;
After that you'll be able to access answers like this:
var answer = $scope.answers["MyQuestionName"];

jquery each loop into a multi array, check for duplicates

I think what I want to do is really simple but can't get it to work. I'm looping through a table and getting some values from the existing rows, that part works. Then I'm using AJAX to try and make a multidimensional array without duplicates but something isn't working. What I really want to do is delete the duplicate part, reorder the array and array_push new values. Here's what I have:
AJAX:
function getData(){
$("#table .mainTR").each(function(){
var key = $(this).find(".key").text();
var sel = $(this).find(".s").val();
var q = $(this).find(".q").val();
$.ajax({
type: "POST",
async: false,
data: {key: key, s: sel, q: q}
});
});
}
PHP:
if(isset($_POST['key'])){
$title = $_POST['key'];
$s = $_POST['s'];
$q = $_POST['q'];
if(!empty($_SESSION['check'])){
foreach ($_SESSION['check'] as $key=>$value){
if(in_array($title, $value)){
unset ($_SESSION['check'][$title]);
$_SESSION['check'] = array_values($_SESSION['check']);
array_push($_SESSION['check'], array("key"=>$title, "s"=>$s, "q"=>$q));
}
}
}else{
$_SESSION['check'] = array(array("key"=>$title, "s"=>$s, "q"=>$q));
}
}
Is there something wrong with the logic? It seems like it should work. The same foreach loop works when trying to delete a table row. It finds the correct KEY and deletes it. Why doesn't it work here?
Here's the answer I got by hours and hours of searching. I avoided using serialize since...well I don't understand how to use it. In JS I'm looping to find values in the table and making an array like this:
function getData(){
var checkArray = new Array();
$("#shopCart .mainTR").each(function(){
var key = $(this).find(".key").text();
var sel = $(this).find(".s").val();
var q = $(this).find(".q").val();
checkArray.push(key);
checkArray.push(sel);
checkArray.push(q);
});
$.ajax({
type: "POST",
data: {ch: checkArray}
});
}
In my PHP is where I found a cool trick. Since I'm controlling the data in the array, I know how many values will be in it. The trick I found is "array_chunk" so for the 3 values I'm doing this:
if(isset($_POST['ch']) && (!empty($_POST['ch']))){
unset($_SESSION['check']);
$_SESSION['check'] = array_chunk($_POST['ch'], 3);
}
So I'm just clearing the session variable and adding the new values. That eliminates all the checking and clearing and all that. I'm sure there are better ways to do this but this method is short and works and that's what I'm looking for. Hope this helps someone!

Get all Form values - working with jquery ajax in PHP

I'm using this jquery to serialize my form and pass it to a PHP script called write.php;
$("form").submit(function(){
var_form_data = $(this).serialize();
$.ajax({
type: "POST",
url: "write.php",
data: var_form_data,
success: function(msg){
alert( "Data Saved: " + msg );
}
});
});
Normally, lets say I had a form with the fields Address F_name and S_name, I'd do something like this to get the values into PHP vars;
$Address = $_POST["Address"];
$F_name = $_POST["F_name"];
$S_name = $_POST["S_name"];
I'd then go onto persist these to the DB
However, this particular form is liable to change on a regular basis. Therefore, I'd like to be able to get at all of the data that was passed through the ajax request in the form of a string that I can explode or an array.
I can then loop through the items in the array and persist them to the DB one by one (i think!).
I hope this makes sense, if I have missed anything or you would like me to explain further please let me know.
As always - all help is very much appreciated.
foreach($_POST as $form_key => $form_val){ }
you will not want to query each time inside this loop, however. Instead append each time to a string that you will query with afterwards.
var $results = '';
foreach ($_POST as $key => $value) {
echo $results .= "$key = $value;";
}
// $results holds the posted values
foreach($_POST as $k => $v)
but this is pretty risky as malicious user could manually add post values to the request and do crappy stuff with your code. Make a list of allowed value maybe ;)

Building dynamic poll with jquery, php and html

Okey, this is what I've got.
<?php
$options[1] = 'jQuery';
$options[2] = 'Ext JS';
$options[3] = 'Dojo';
$options[4] = 'Prototype';
$options[5] = 'YUI';
$options[6] = 'mootools';
That is my array, but I'd like to make it a bit more dynamic so that the array is built according to input id, so he won't have to change the php-code whenever he want's another poll. How would I import those input id's and push them into an array?
To the extent I can understand your question, you could use JSON to pass the data from the client to the server like this:
JAVASCRIPT (using jQuery):
var arr = [];
arr.push("option1");
arr.push("option2"); // and so on..
//Use AJAX to send the data across ..
$.ajax({
url: 'poll.php?jsondata=' + encodeURIComponent(JSON.stringify(arr)),
success: function(data) {
// response..
}
});
});
I think that PHP script will put those options into a database or something for using it later on.
Now, in PHP(poll.php):
<?php
$options = json_decode($_GET['jsondata']);
//...
?>

Categories