sending HTMLcollection to database - javascript

so I have this table with contenteditable divs, when a user inputs something in a div they have to click a button that collects all the content of the divs and stores them into Var OBJ.
document.getElementById("done_editing").addEventListener("click", get_values);
var OBJ = [];
function get_values() {
let divobj = document.querySelectorAll('[contenteditable=true]')
for (var i = 0; i < divobj.length; i++) {
OBJ.push(divobj[i].textContent)
//console.log(OBJ)
}
OBJ = OBJ.filter(item => item)
console.log(OBJ)
I want to send the values inside of var OBJ to a Database. I cant Wrap my head around on how to do this . It is not your average form so I guess I have to use ajax but I have no experience with ajax. this is what i Have for ajax.
$.ajax({
type: "POST",
url: "test.php",
data: { arraykey: OBJ },
success: function (response) {
alert('succes')
// You will get response from your PHP page (what you echo or print)
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
})
}
Anyone can point me in the right direction on how to use ajax and how to configure the php file ?
php file :
//Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$data = isset($_POST['arraykey']);
if ($data)
{
$array = $_POST["arraykey"];
echo $array;
echo " is your array";
}
else
{
$array = null;
echo "no array supplied";
}
/*$data = isset($_POST['OBJ']);
print_r($_POST);
*/
// close connection
mysqli_close($link);
?>
the var_dump($_POST); returns a array(0) { }
update: ajax seems to succeed but no array is passed to php.
Thanks in advance !

As there are multiple divs you can use array to add mutliple values to it and send the same to ajax.
Demo Code :
document.getElementById("done_editing").addEventListener("click", get_values);
var OBJ = [];
function get_values() {
let divobj = document.querySelectorAll('[contenteditable=true]')
for (var i = 0; i < divobj.length; i++) {
OBJ.push(divobj[i].textContent); //add in array
}
console.log(OBJ)
//your ajax call
$.ajax({
type: 'POST',
url: 'test.php',
data: {
OBJ: OBJ //pass array to php
},
success: function(data) {
alert("something");
}
});
}
div {
border: 1px solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div contentEditable="true"></div>
<div contentEditable="true"></div>
<div contentEditable="true"></div>
<div contentEditable="true"></div>
<button id="done_editing">Done</button>
Your php will look like below :
<?php
// You should call this first
session_start();
$data = isset($_POST['arraykey']);
if ($data)
{
$_SESSION['arraykey'] = $_POST["arraykey"];//putting aray value in session
echo $_SESSION['arraykey'];
echo " is your array";
}
else
{
echo "no array supplied";
}
?>

Related

Ajax success need something for php JSON object

I am trying to make a user search system like facebook using ajax and php json. But i have one problem.
From the data users table have Marc Zuckerberg, Marc Zeyn, Marc Alp. I mean 3 user first name is same, so normaly when i write the Marc name then i should be get all Marc names from data. Like
<div class="ul">Marc Zuckerbert</div>
<div class="ul">Marc Zeyn</div>
<div class="ul">Marc Alp</div>
but i am not getting all Marc names just i am getting one marc result. Chrome developer console show me all Marc name but not show my within HTML. I think i need some code from ajax success.
JS
$('body').delegate('#searchkey','keyup', function(){
clearTimeout(timer);
timer = setTimeout(function(){
var box = $('#searchkey').val();
contentbox = $.trim(box);
var dataString = 'keys=' + contentbox;
if(contentbox !==''){
$.ajax({
type: "POST",
url: siteurl +"requests/search.php",
data: dataString,
dataType:"json",
cache: false,
beforeSend: function(){},
success: function(data){
$('.un').html(data.username);
$('.uf').html(data.fullname);
}
});
}
});
});
search.php
<?php
include_once 'inc.php';
if(isset($_POST['keys'])) {
$keys = mysqli_real_escape_string($db, $_POST['keys']);
$keyRestuls = $WidGet->SearchUser($keys);
if($keyRestuls) {
// If array is in data
foreach($keyRestuls as $datas) {
$dataUsername = $datas['username'];
$dataUserID = $datas['fullname'];
$data = array(
'username' => $dataUsername,
'fullname' => $dataUserID
);
echo json_encode( $data );
}
}
}
?>
SearchUser function is here
public function SearchUser($keys){
$keys = mysqli_real_escape_string($this->db, $keys);
$result = mysqli_query($this->db,"SELECT
username,
uid,
fullname FROM
users WHERE
username like '%{$keys}%' or fullname like '%{$keys}%'
ORDER BY uid LIMIT 10") or die(mysqli_error($this->db));
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)) {
$data[]=$row;
}
if(!empty($data)) {
// Store the result into array
return $data;
}
}
Your PHP script is generating a malformed JSON
{"username":"marc1","fullname":"Marc Zuckerberg"}
{"username":"marc3","fullname":"Marc Zeyn"}
{"username":"marc2","fullname":"Marc Alp"}
It shoulds generate
[
{"username":"marc1","fullname":"Marc Zuckerberg"},
{"username":"marc3","fullname":"Marc Zeyn"},
{"username":"marc2","fullname":"Marc Alp"},
]
You can fix it by appending to an array instead of writting each row independamently
foreach($keyRestuls as $datas)
{
$dataUsername = $datas['username'];
$dataUserID = $datas['fullname'];
$data[] = array(
'username' => $dataUsername,
'fullname' => $dataUserID
);
}
echo json_encode( $data );
And then you'll have to loop over $data in your JS, I suggest you use $.each
function success(data) {
$.each(data, function(key, value) {
console.log(value.username + ": " + value.fullname);
})
}

ajax jquery errors on json return value from php script

I'm having problems with this ajax/jquery programming.
I've tried many different things but nothing has worked.
Ajax posts selItem to ajaxsql.php, this works!
The sql query in ajaxsql.php works, cause it outputs this if i call the script directly in the browser: [{"forumname":"SDE forum","user":"michael","txt":"Jeg hedder Michael!"}]
The problem is that the ajax function shows an alert box with Error[object Object]
forum.php script:
<script type="text/javascript">
function ForumChat(selItem) {
$.ajax({
type: "POST",
url: 'ajaxsql.php',
data: { selectedItem : selItem.value },
dataType: "json",
success: function(data) {
alert(data);
$('#txtarea').html(data);
},
error: function(data) {
alert('Error' + data);
}
});
}
</script>
ajaxsql.php script:
<?php
if(!isset($_SESSION))
{
session_start();
}
include('class.php');
//$sel = $_POST['selectedItem'];
$sel = "SDE forum";
$sql = " SELECT * FROM forum WHERE user = '".$_SESSION['currentuser']."' AND forumname = '".$sel."' ";
$result = mysqli_query($_SESSION['con'], $sql);
while($row = mysqli_fetch_array($result))
{
$forumname = $row['forumname'];
$user = $row['user'];
$txt = $row['text'];
$return[] = array("forumname" =>$forumname, "user" =>$user, "txt" =>$txt);
}
echo json_encode($return);
?>
because ajaxsql.php returns object ..
what you can do in your ajax is
success: function(response) {
$('#txtarea').html('');
$.each(response.data, function(){
console.log(this);
$('#txtarea').append(data);
});
},

AJAX is running correctly but doesn't display fetched data

My PHP query is running fine(based on the response on firebug) but the result its giving me are [object Object] on my direct page. So I'm guessing that my problem lies on my javascript because on firebug under the response tab its retrieving all my data on my database
Here is my javascript
function AjaxRetrieve()
{
var rid = document.getElementById('trg').value,
data = {chat: uid, rid: rid, name: user};
$.ajax({
url: "includes/getChat.php",
type: "GET",
data: data,
dataType: 'json',
success: function(result){
var res = $([]);
$.each(result[0], function(key, value) {
res = res.add($('<div />', {text : value}));
});
$("#clog").html(res);
}
});
}
The php script as requested is this
$sql7 = "SELECT message_content, username , message_time, recipient FROM ".$tbpre."chat_conversation WHERE msgid=:chat";
$stmt7=$con3->prepare($sql7);
$stmt7->bindValue( 'chat', $msgd, PDO::PARAM_STR);
$stmt7->execute();
$message_query = $stmt7;
$json = array();
if($message_query->rowCount() > 0) {
while($message_array = $stmt7->fetchAll(PDO::FETCH_ASSOC)) {
$json[] = $message_array;
}
echo json_encode($json);
}
I'm not that familiar yet on JQUERY/AJAX/Javascript so I'm not actually sure if what I'm doing is correct I just based some of my codes on jquery's documentation and some
suggestions from our fellow members here
The way your constructing the json data is wrong,try this way
$json =array();
$i=0;
if($message_query->rowCount() > 0) {
while($message_array = $stmt7->fetchAll(PDO::FETCH_ASSOC)) {
$json[$i]= $message_array;
$i++;
}
echo json_encode($json);
}
Happy Coding :)
Change your success callback like below, you have an array of objects.
success: function(result){
var container = $("#clog");
$.each(result, function(i, message) {
$.each(message, function(key, value) {
container.append($('<div />').html(key + ':' + value));
});
});
}
Edit:
And you have to change fetchAll to fetch in you while loop.
while($message_array = $stmt7->fetch(PDO::FETCH_ASSOC)) {
$json[] = $message_array;
}
echo json_encode($json);
Or just use fetchAll without while loop:
$json = $stmt7->fetch(PDO::FETCH_ASSOC);
echo json_encode($json);

how to put condition alert box in ajax

can anyone help me...how do i put an conditional alert dialog box in ajax that if the data in a query is successfully saved or the data already been saved.
I want to do is if the query is saved an alert box will pop-op same goes to if the data is already been saved.
script code:
<script type="text/javascript">
$(document).ready(function () {
$('#updates').click(function (e) {
e.preventDefault();
var data = {};
data.region_text = $('#t_region').val();
data.town_text = $('#t_town').val();
data.uniq_id_text = $('#t_uniq_id').val();
data.position_text = $('#t_position').val();
data.salary_grade_text = $('#t_salary_grade').val();
data.salary_text = $('#t_salary').val();
for(var $x=1;$x<=15;$x++) {
data['id'+$x+'_text'] = $('#id'+$x).val();
data['aic'+$x+'_text'] = $('#aic'+$x).val();
data['name'+$x+'_text'] = $('#name'+$x).val();
data['optA'+$x+'_text'] = $('#optA'+$x).val();
data['optB'+$x+'_text'] = $('#optB'+$x).val();
data['optC'+$x+'_text'] = $('#optC'+$x).val();
data['optD'+$x+'_text'] = $('#optD'+$x).val();
data['other_qual'+$x+'_text'] = $('#other_qual'+$x).val();
data['interview'+$x+'_text'] = $('#interview'+$x).val();
data['total'+$x+'_text'] = $('#total'+$x).val();
}
$.ajax({
type: "POST",
url: "insert.php",
data: data,
cache: false,
success: function (response) {
// We are using response to distinguish our outer data variable here from the response
}
});
});
});
</script>
insert.php code:
<?php
include('../connection.php');
date_default_timezone_set('Asia/Manila');
$region = #$_POST['region_text'];
$town = #$_POST['town_text'];
$uniq_id = #$_POST['uniq_id_text'];
$position = #$_POST['position_text'];
$salary_grade = #$_POST['salary_grade_text'];
$salary = #$_POST['salary_text'];
$dupesql = "SELECT * FROM afnup_worksheet WHERE funiq_id = '$uniq_id'";
$duperow = mysql_query($dupesql);
if(mysql_num_rows($duperow) > 0){
exit;
}else{
for($n=1;$n<=15;$n++) {
$id = #$_POST['id'.$n.'_text'];
$aic = #$_POST['aic'.$n.'_text'];
$name = #$_POST['name'.$n.'_text'];
$optA = #$_POST['optA'.$n.'_text'];
$optB = #$_POST['optB'.$n.'_text'];
$optC = #$_POST['optC'.$n.'_text'];
$optD = #$_POST['optD'.$n.'_text'];
$other_qual = #$_POST['other_qual'.$n.'_text'];
$interview = #$_POST['interview'.$n.'_text'];
$total = #$_POST['total'.$n.'_text'];
if(!empty($name)){
$query = "INSERT INTO afnup_worksheet (faic,fregion,ftown,funiq_id,fposition,fsalary_grade,fsalary,fnl_name,edu_attain,experience,seminars,eligibility,other_qual,interview,ftotal,dateinputed)
VALUES
('$aic','$region','$town','$uniq_id','$position','$salary_grade','$salary','$name','$optA','$optB','$optC','$optD','$other_qual','$interview','$total',CURRENT_TIMESTAMP)";
$resource = mysql_query($query) or die(mysql_error());
}
}
}
?>
Just return that status from PHP:
if(mysql_num_rows($duperow) > 0){
echo "1"; // Dup status
exit;
}else{
// All your else code.. echo must be the last thing inside your else block
echo "2"; // Saved status
}
Then in your ajax success callback you check it:
$.ajax({
type: "POST",
url: "insert.php",
data: data,
cache: false,
success: function (response) {
if (Number(response) == 1)
{
alert("Dup message");
}
else
{
alert("Saved message");
}
}
});
Instead of exit; in your conditinal for dupes, you could echo "duplicate". Also you should remove die() after your $resource and add if ($resource) echo "ok"; else echo "error";
Then in your success function(response) in javascript you can do if (response=="...") echo duplicate; else if ...
This is just basic explanation, but it should be enough to point you in the right direction.

Ajax separate data which came from mysql

I am doing an ajax call like this:
function myCall() {
var request = $.ajax({
url: "ajax.php",
type: "GET",
dataType: "html"
});
request.done(function(data) {
$("image").attr('src',data);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
This is my ajax.php:
<?php
$connection = mysql_connect ("",
"", "");
mysql_select_db("");
// QUERY NEW ONE
$myquery = "SELECT * FROM mytable ORDER BY rand() LIMIT 1";
$result = mysql_query($myquery);
while($row = mysql_fetch_object($result))
{
$currentid = "$row->id";
$currentname = "$row->name";
$currenturl = "$row->url";
$currentimage = "$row->image";
echo $currenturl,$currentnam, $currenturl,$currentimage;
}
mysql_close($connection);
?>
My data variable from the ajax call now contains all variables at once:
($currenturl,$currentnam, $currenturl,$currentimage)
How can I separate them so I can do something like:
request.done(function(data) {
$("id").attr('src',data1);
$("name").attr('src',data2);
$("url").attr('src',data3);
$("image").attr('src',data4);
});
jQuery :
$.ajax({
type:"POST",
url:"ajax.php",
dataType:"json",
success:function(response){
var url = response['url'];
var name = response['name'];
var image = response['image'];
// Now do with the three variables
// $("id").attr('src',data1);
// $("name").attr('src',data2);
// $("url").attr('src',data3);
// $("image").attr('src',data4);
},
error:function(response){
alert("error occurred");
}
});
From your code:
echo $currenturl,$currentnam, $currenturl,$currentimage;
Replace the above line with the code below:
$array = array('url'=>$currenturl, 'name'=>$currentname, 'image'=>$currentimage);
echo json_encode($array);
instead of string return an array i.e. use json type for returning value
i.e instead of
echo $currenturl,$currentnam, $currenturl,$currentimage;
use
echo json_encode array('current' => $currenturl,'currentnam' => $currentnam, 'currenturl' => $currenturl,'currentimage' => $currentimage);
and also write 'dataType' as 'json' in ajax

Categories