How to store PHP array in MySQL? - javascript

I tried to store a JavaScript array into MySQL table using PHP, see the following script below.
I first converted the string using JSON.stringify and passed it into a PHP file via AJAX request.
I then converted it to a PHP array, and after after I inserted those arrays using serialize();.
Finally, it properly stored using localhost but it does not work on my live server.
sample.Js
$.ajax(
{
type: "POST",
url: "save_plan_ajax.php",
data: {plan: plan,totalInvesment: totalInvesment, location: JSON.stringify(locationsArr), cost: JSON.stringify(cost), personalised: JSON.stringify(personalised)},
success: function(data){
//alert(data);
}
}
)
In this above script I passed the JavaScript array into save_plan_ajax.php using JSON.stringify.
save_plan_ajax.php
<?php
session_start();
include 'config.php';
if(isset($_POST)){
$planname = $_POST['plan'];
$cost = json_decode($_POST['cost'], true);
$personalised = json_decode($_POST['personalised'], true);
$locations = json_decode($_POST['location'], true);
$userid = $_SESSION['BIID'];
$constriant = $_SESSION['CONSTRAINT'];
$created_date = date("Y-m-d H:i:s");
$total_invs = $_POST['totalInvesment'];
$query = "INSERT INTO `plans` (
`refid` ,
`userid` ,
`plan_name` ,
`cost` ,
`locations`,
`personalised` ,
`total_invs`,
`constriant` ,
`created_date` ,
`stat`
)
VALUES (
NULL , '$userid', '$planname', '".serialize($cost) ."', '".serialize($locations)."','".serialize($personalised)."', '$total_invs', '$constriant', '$created_date', 'A'
)";
$res = $GLOBALS['Db']->Insert($query);
if($res){
echo $res;
}
else{
echo "Error";
}
}
?>
In the above script, the record stores correctly at local server, but in this same script insert N; in server.. how do I fix this error, is the above way correct?
In the MySQL database table I have set the cost, location and personalized fields datatype as LONGTEXT.

Related

Convert a Ajax Json String to a JS Object for my Ajax Get Script

I ideally want the Ajax result to be converted from Jsonstring to OBJ Thank You in advance.
I know the AJAX GET script is working becuase when I alert the Ajax Post result I see the Contents in json string format as below.
alert(JSON.stringify(data));
[{"id":"1","username":"jiten","name":"Jitensingh\t","email":"jiten93mail”},{“id":"2","username":"kuldeep","name":"Kuldeep","email":"kuldeemail”}]
I want the AJAX GET result data converted to look like this in OBJ format like below.
{id:31,name:"Mary",username:"R8344",email:"wemail}];
PHP/SQL CODE with the Json encoded Array
<?php
include "../mytest/config.php";
$return_arr = array();
$sql = "SELECT * FROM users ORDER BY NAME";
$result = $conn->query($sql);
//Check database connection first
if ($conn->query($sql) === FALSE) {
echo 'database connection failed';
die();
} else {
while($row = $result->fetch_array()) {
$id = $row['id'];
$username = $row['username'];
$name = $row['name'];
$email = $row['email'];
$return_arr[] = array(
"id" => $id,
"username" => $username,
"name" => $name,
"email" => $email);
}
// Encoding array in JSON format
echo json_encode($return_arr);
}
?>
php echo _encode array above returns below Json string format
[{"id":"1","username":"jiten","name":"Jitensingh\t","email":"jiten93mail”},{“id":"2","username":"kuldeep","name":"Kuldeep","email":"kuldeemail”}]
I am looking for something like below.( top half of the script)
<script>
$(document).ready(function(){
$.ajax({
url: 'ajaxfile.php',
type: 'get',
dataType: 'JSON',
success: function(result){
var data =(JSONstring convert to OBJ(result);
//-----The top half of script -------------
$.each(data, function( i, person ) {
if(i == 0) {
$('.card').find('.person_id').text(person.id);
$('.card').find('.person_name').text(person.name);
$('.card').find('.person_username').text(person.username);
$('.card').find('.person_email').text(person.email);
} else {
var personDetailCloned = $('.card').first().clone();
personDetailCloned.find('.person_id').text(person.id);
personDetailCloned.find('.person_name').text(person.name);
personDetailCloned.find('.person_username').text(person.username);
personDetailCloned.find('.person_email').text(person.email);
$('.card-container').append(personDetailCloned);
}
});
});
</script>
I will need help with the closing tags as above is just an example
The solution is:
success: function(result){
data =(result);
There was no need o convert the data to OBJ or anything ( blush). Then the code on the 2nd half of the Ajax script will receive the data and populate. Thanks to all contributors.

Jquery/Ajax to get database using php

I have an HTML page that is too big to post on here, however I'll just post the ajax/jquery I am using to try and access the PHP file variables.
threadPage.html
<script type="text/javascript">
$.ajax({
url : '/ThreadCreation.php',
type : 'POST',
data: {'titles': titles}
crossDomain: true,
dataType : 'jsonp',
success : function (data) {
console.log(data) /
},
error : function () {
alert("error");
}
})
</script>
<!-- bunch of html -->
So essentially I am trying to get the variable from the ThreadCreation.php in JSON form. It should be in an array so that I can loop through it in the HTML file.
ThreadCreation.php
<?php
$username = 'root';
$password = '';
$db = 'main_database';
$conn = mysqli_connect('localhost', $username , $password,$db);
if (!$conn){
die("unable to connect");
}
$sql = mysqli_query($conn, "SELECT title FROM thread");
while($row = mysqli_fetch_array($sql)) {
$titles[] = $row['title'];
echo json_encode($titles);
?>
I will repeat though, that this HTML file is only getting information from the database through PHP. So there is no form submission here.
I keep getting that 'titles is not defined'. This makes sense because there is not titles defined in the HTML, however I am unsure how to construct my ajax request to collect the data, as this format is all I have seen people use.
Mention empty array first just to prevent error in case you have no data
in database then empty array will proceed.
$sql = mysqli_query($conn, "SELECT title FROM thread");
$titles = array();
while ($row = mysqli_fetch_array($sql)) {
array_push($titles,$row['title']); // Push data in empty array
}
echo json_encode($titles);

Sending data from front-end to back-end to front-end

Hi i'm a beginner in using JavaScript i have this html page with JavaScript codes that receives data from the server and display it on this current page, what i'm trying to do is use that data and sending it to another PHP page for my SQL query to get back results.
<script>
var json = sessionStorage.xhr;
var object = JSON.parse(json);
var hard = object["red-fruits"];
var string = JSON.stringify (hard);
var stringData = encodeURIComponent(string);
$.ajax({
type: "POST",
url: "http://localhost/web/main.php",
data: {"dataA" : stringData},
cache: false,
success: function(){
console.log("OK");
}
});
var user = sessionStorage.getItem('impData');
console.log(user);
</script>
This is my PHP page codes, what i'm doing here is getting the data "dataA" from that html page and sending it to this PHP page for the SQL query and getting the results which is the "$haha" array and using JavaScript session function to send it back to the HTML page. But my console only shows "null" can anyone tell me if i'm doing anything wrong or have any suggestion would be really appreciated.
<?php
$connection = mysqli_connect("localhost","root","","") or
die("Error " . mysqli_error($connection));
if (isset($_POST['dataA'])) {
echo $name = $_POST['dataA'];
}
else {
echo "Error";
}
$string = str_replace("]", "", str_replace("[", "", str_replace('"','',$falcon)));
$array = explode(',', $string);
$array2= implode("', '",$array);
$sql = // "SQL query"
$result = mysqli_query($connection, $sql) or die("Error in Selecting " .
mysqli_error($connection));
while($row = mysqli_fetch_array($result)) {
$haha[] = $row['row_name'];
}
?>
<script type="text/javascript">
var tills = <?php echo '["' . implode('", "', $haha) . '"]' ?>;
console.log (tills);
sessionStorage.setItem('impData', tills);
</script>
You are now mixing ajax and session data on a strange way. The session data used by your javascript will not be updated by the php-script till you refresh your page. The correct way to handle data is in the "success" function:
$.ajax({
type: "POST",
url: "http://localhost/web/main.php",
data: {"dataA" : stringData},
dataType : "json",
cache: false,
success: function(data){
console.log(data);
}
});
and in you PHP output the data you want to send to the browser as a json string:
echo json_encode($your_object);

converting Javascript variable to PHP variable in two different php file

Can some body help me get the current value from this option tag
to account.php as a session variable or anything ..
// loadsubcat.php This code is for dependent dropdown
$query = mysql_query("SELECT * FROM table_cmsjob WHERE VesselID= {$parent_cat}");
while($row = mysql_fetch_array($query))
{
echo "<option value='$row[jobName]'>$row[jobName]</option>";
}
var javascriptVariable = $('#sub_cat').val();
I know this can be solve using ajax but I don't know how.
I will use the javascript variable as a reference for a couple of checkboxes under it but first must be passed as a php variable.
you ajax will look like this,
$.ajax({
type: 'POST',
url: "account.php",// path to ajax file
data: {javascriptVariable:javascriptVariable},// you can pass values here in key value pairs.
success: function(data) {
alert(data);
}
});
You can send n number of key => value pairs.
like
parent_cat:100
Next:
echo $_POST['javascriptVariable']; // <--- grabbing ajax data here
$query = mysql_query("SELECT * FROM table_cmsjob WHERE VesselID= {$parent_cat}");
while($row = mysql_fetch_array($query))
{
echo "<option value='$row[jobName]'>$row[jobName]</option>";
}
what ever echoed in php file will come in ajax success data,
alert(data) will alert what you had echoed in php. you can use that in your html file.

ajax call to php to get database rows

The following is in my file.js
function mainget(){
$.ajax({
type: 'GET',
url: 'example.php',
data:json,
success:function(data){
}
});
}
example.php
<?php
$con = mysqli_connect('address','DATBASE','pass','futureday');
$result = mysql_query("SELECT * FROM $futureday");
$array = mysql_fetch_row($result);
echo json_encode($array);
?>
I have been struck with this for the past 2 days. I have tried inserting alert as first line of function mainget , which is successful, but after that I get nothing.
You are using data property in AJAX call to indicate the json data type. It is an invalid one. Use dataType to provide the data type. data property is used to pass the datas. And also put quotes to the values like:
dataType:'json'
Also change your example.php file. There you are using mysqli_connect to connect the database, then mysql_* to execute and fetch operations. It is not correct. Use either mysqli_* or mysql_*. Edit as:
<?php
$con = mysqli_connect('address','DATBASE','pass','futureday');
$result = mysqli_query("SELECT * FROM $futureday");
$response = array();
while($array = mysqli_fetch_row($result)){
$response[]=$array;
}
echo json_encode($response);
?>
Use this
$mysqli = new mysqli('address','DATBASE','pass','futureday');
$query = "SELECT * FROM $futureday";
$results=$mysqli->query($query) ;
$res=$mysqli->fetch_array(MYSQLI_ASSOC);
echo json_encode($res);

Categories

Resources