How to store div content to DB? - javascript

In my project, sheet processing data will be append to a timeTagDiv div(just like A and B are talking, and the content will show in the dialog).The new message send to dialog will append to timeTagDiv div. After that I want the whole timeTagDiv html content stores in the DB with ajax. Next time, these dialogue content will show in the div, So I konw what is going on.
Here is my js code:
var newCnt="<span class='dlgRsp'><label id='dlgRspTime'></label> <label id='dlgCharge'></label> accept sheet</span><br />";
$('#timeTagDiv').append(newCnt);
//var tmTgDvHtml=$('#timeTagDiv').innerHTML;
var tmTgDvHtml=document.getElementById("timeTagDiv").innerHTML;
var slcId = 2;
$.ajax({
dataType:'json',
type:"POST",
url:"get_ajax_csc.php",
data: {slcId:slcId,htmlCnt:tmTgDvHtml},
success:function (data)
{}
});
Here is my html code:
<div class="timeTag" id="timeTagDiv">
<span class="dlgDate" id="firDlgDate"></span><br />
<span class="dlgStTrl"><label id="dlgTime1"></label> <label id="dlgPrpsr"></label> create new sheet</span><br />
<div id="dlgDiv1"></div><br />
</div>
Here is get_ajax_csc.php code:
<?php
include ("DB.php");
if(isset($_POST['htmlCnt']))
{
$sql="update IDC SET shProcess='".$_POST['htmlCnt']."' where id='".$_POST['slcId']."';";
$sel = $conn->exec($sql);
}
?>
But unfortnately, these date of timeTagDiv can not be updated. I have tested that tmTgDvHtml=document.getElementById("timeTagDiv").innerHTML can get the div html content.But i have no idea about that. Who can help me ?

The div contect of htmlCnt should be formatted by stripslashes()
$htcnt=stripslashes(".$_POST['htmlCnt'].");
It works fine.

Related

jQuery / Ajax properly sending "data-" value in an alert, but unable to append it into a specific div inside a php for

I currently have an html button which right below has a div where I want to post certain data.
Both of those elements are inside a php for loop.
<?php for($i = 0 ; $i < 10; $i++){ ?>
<div class="form-group">
<label class="col-md-4 control-label" for="ver"></label>
<div class="col-md-4">
<button data-dnipass="<?= $dni?>" class="ver" name="ver" class="btn btn-primary">
Ver lĂ­neas
</button>
</div>
</div>
<div id ="<?= $i?>" class="table userInfo" data-formpost="<?= $dni?>"></div>
<? } ?>
$dni is a value I take from my databae and is unique for each iteration.
Then I have an ajax script doing the following
$(document).ready(function(){
$(".ver").click(function(event){
var pulsado = $(this).data("dnipass"); //this is properly asigning the data
alert(pulsado); //this properly launches an alert with my desired value
$(this).data("formpost").append(pulsado); //im trying to append my variable to my ".userinfo" div but im unable to do so, since I dont know how to identify so
});
})
How can I append the var pulsado to my div with the class ."userinfo"? The content of the var pulsado is a simple string, like "x1234" or "x4321"....
Try the following code
$(".ver").click(function(event){
var pulsado = $(this).data("dnipass"); //this is properly asigning the data
$(this).closest('.form-group').next('.userInfo').append(pulsado);
});
The closest finds the div under which your button is wrapped. next then finds the immediate div with userInfo class.
Just make use of append() like this :
$(document).ready(function()
{
$(".ver").on('click',function(event)
{
var pulsado = $(this).data("dnipass");
$(".userinfo").append(pulsado);
});
});

Reload specific Selection tag without reloading the whole page

I am trying to make a form page in adding new client in a database. The form consist of a selection tag that has options for adding house number. But there are circumstances like house number is not yet placed on the database, so I decided to create a button for adding new house no (using modals).
Form:
<div class="col-md-3 form-group" id="autoload">
<label>
Household: <a data-toggle="modal" data-target="#addHousehold"
style="cursor: pointer; text-decoration: none;">
<i class="fa fa-plus" >Add</i></a>
</label>
<select class="form-control select2" style="width: 100%;">
<option selected="selected">Select Household</option>
<?php foreach($result3 as $row): ?>
<option><?=$row['house_no']?></option>
<?php endforeach ?>
</select>
</div>
Script for adding new house number, and refresh the selection when new house number is successfully added:
$('#addHouseholder').click(function(){
var householder = $('.householder').val()
var street = $('.strsel1').val();
$.ajax({
method: "POST",
url: "insert.php",
data: {householder:householder,street1:street}
}).then(()=>{
$("#autoload").load(" #autoload");
alert('Household Added')
})
This function successfully, the only problem is the division of the selection is deformed. I also forgot to say that I reload the div, but I wonder if it is possible to just reload the selection. I am not sure how to execute this. Looking forward for your help. Thank you very much!
Are you using select2 (https://select2.org/)?
If so, you can use the ability to programmatic control the select.
https://select2.org/programmatic-control/add-select-clear-items
By using:
var data = {
id: 1,
text: 'Barn owl'
};
var newOption = new Option(data.text, data.id, false, false);
$('#mySelect2').append(newOption).trigger('change');
You could return the option in the ajax response and populate the select.
You just need to echo json format of your data in insert.php file then modify your js script to
$.ajax({
type: "POST",
url: "path/insert.php",
data: {householder:householder,street1:street},
success: function(data){
// Parse the returned json data
var opts = $.parseJSON(data);
// Use jQuery's each to iterate over the opts value
$.each(opts, function(i, d) {
// You will need to alter the below to get the right values from your json object. Guessing that d.no / d.anyOtherInfo are columns in your data
$('#autoload').children(".orm-control.select2").append('<option value="' + d.no + '">' + d.anyOtherInfo + '</option>');
});
}
});
Good luck.
Edit 1: adding source.
check Populate Select box options on click with Javascript/Jquery with Json data

Update dynamically generated list item (generated using PHP) after ajax call

The following HTML code is being echoed using a while loop in PHP which is adding a list item after fetching data from database.
PHP:
echo '
<li>
<div class="collapsible-header">
<div class = "left">
<div class = "issueStatusIcon" style = "background-color:'.$smallCircleColor.';">'.$smallMsg.'</div>
<span class = "issueTitle" style = "font-family: robotoBold">'.$issueTitle.'</span>
</div>
<div class = "issueButtonsGroup">
<form id = "archiveIssueForm'.$i.'" issue-name = "'.$issueTitle.'" action = "archiveIssue.php">
<input type = "hidden" value = "'.$issueID.'" name = "issueID"/>
</form>
<a class = "right archiveIconButton" onclick = "ajaxIssueArchive('.$i.')" href = "#">
<i class="material-icons black-text issueOptions archiveIcon">archive</i>
</a>
<a class = "right"><i class="material-icons black-text issueOptions">edit</i></a>
</div>
</div>
</li>
';
This is the preview image of the generated list:
Notice the cursor over the archive button which archives the list item. The class for that button is archiveIconButton (you can find it in the above code). When the button is clicked, archiveIssueForm is submitted via AJAX (each form has a unique identifier variable $i appended to its id).
Following is the JQuery AJAX code:
JQuery:
<script>
function ajaxIssueArchive($num){
$.ajax({
type: "post",
url: "archiveIssue.php",
data: $('#archiveIssueForm' + $num).serialize(),
success: function(data){
$fetchIssueName = $('#archiveIssueForm' + $num).attr("issue-name");
$toastText = $fetchIssueName + " has been archived";
Materialize.toast($toastText, 3000);
$('#archiveIssueForm' + $num).html(data);
}
});
}
</script>
After archiving any list item, it gets deleted from the database. I want to update the ul element which contains these list items so that the list item which gets deleted doesn't gets displayed after the AJAX form submission.
Assume the id of ul to be issueListUL.
What i'm currently getting is the whole code of the html page displayed in the li item. I am certainly doing something wrong, any help would be appreciated!
After archiving a list item:
I was able to solve this issue in the following way, The JQuery script in the question should be changed like this:
JQuery:
<script>
function ajaxIssueArchive($num){
$.ajax({
type: "post",
url: "archiveIssue.php",
data: $('#archiveIssueForm' + $num).serialize(),
success: function(data){
//assigning the updated ul's html to a variable
$afterIssueArchival = $(data).find("#issueListContainer").html();
//toast
$fetchIssueName = $('#archiveIssueForm' + $num).attr("issue-name");
$toastText = $fetchIssueName + " has been archived";
Materialize.toast($toastText, 3000);
//updation of ul's html, ID of the ul which contains all the list items is assumed to be 'listContainer'
$("#issueListContainer").html($afterIssueArchival);
}
});
}
</script>
When updating an element's html, just extract the element's updated html code from data attribute in the ajax code (as show in the above code) and update the existing element's html with it!
Hope this helps people with the same problem as mine! :D

How can I improve my Ajax?

I'm trying to figure out if what I'm doing is the right way. I have a comment form and when it gets clicked I'm appending the comment into a div element through Ajax. When the page is refreshed then of course that would disappear and instead of it I have a foreach loop that runs and echos the comments. Since they both have the same CSS attributes they look the same to the user. The reason I'm doing it this way is because the foreach loop gets updated only after a refresh. Is there a better way? Can I update the page directly from the database without refresh? I basically need that every time a user clicks on the comment button that the foreach loop will run again but I couldn't find how to do it. I feel like I'm covering a gun shot with bandage the way I do it at the moment.
Loop:
#foreach($comment as $comments)
#if($comments->image_id == $image->id)
<div id="{{$comments->id}}" class="col-md-5 ajaxrules">
<div class="deletecomment">
<i class="fa fa-trash-o"></i>
</div>
<div class="col-md-2">
<img src="{{$comments->user_avatar}}" class="img-circle buddy">
</div>
<div class="hello col-md-10">
<h4>{!! $image->user_name !!}</h4>
<p class="left">{!!$comments->body!!} </p>
</div>
</div>
#endif
#endforeach
//Where I append the comments through Ajax until the refresh that replaces it with the loop
<div class="man">
</div>
Ajax:
<script>
$(document).ready(function(){
$('.send-form').click(function(e){
e.preventDefault();
var username = "{{ $username }}";
var one = $('textarea[id="{{$image->id}}"]').val();
var value = "{{$image->id}}";
var begin = '<div class="col-md-5 addavatar">'+'<div class="deletecomment">'+'<i class="fa fa-trash-o">'+'</i>'+'</div>'+'<div class="col-md-2">'+'<img src="{{$profile}}" class="img-circle">'+'</div>'+'<div class="hello col-md-10">'+'<h4>' + username +'</h4>'+'<p>'+one+'</p>'+'</div>'+'</div>';
if(one.length > 0){
console.log(username);
$('textarea[id="{{$image->id}}"]').val('');
$.ajax({
url: 'comment',
type: "post",
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
data: {'id': value, 'comment': one},
success:function(data){
$( ".man" ).append([begin]);
},error:function(){
console.log("error!!!!");
}
});
}
});
});
</script>
You are killing yourself.
Manipulate the DOM via javascript code like you do it's really hard work!
You are not suppose to write html inside javascript strings, there must be another way!
And there is... Welcome to AngularJS!
In angular you can write your html and assign a javascript controller to it, perform ajax request and after the ajax complete you can bind the returned data to the html automatically! That means the angular refresh your html and do all the work for you. Even perform loop of let's say, row in a table, etc...

Ajax posted php content not read by javascript

GET-variable called brand.
A few hours ago when I had not implemented the ajax search box, everything worked fine.
The js part looks like this:
$('.mutliSelect input:checkbox').change(function() {
var brand = $("#brand_select input:checkbox:checked").map(function() {
return this.value;
}).get().join(',');
$(".submit_checkboxes").find("a").attr('href', 'index.php?brand=' + brand);
}).change();
Now, having implemented the ajax search box, the var brand does not seem to get filled with any value anymore.
This is the corresponding part of index.php:
<div class="mutliSelect" id="brand_select">
<ul>
<div class="search_view">
<section class="drop_search">
<input type="text" placeholder="Suche" id="search_brand" name="search_brand">
</section>
</div>
<div id="results">
//ajax-php result gets posted in here
</div>
<div class="button submit_checkboxes_button submit_checkboxes">
<a href""><span>Anwenden</span></a>
</div>
</ul>
</div>
and this is a part of search.php (this is the script that is called by ajax and posts the results):
$result = mysql_query($query);
while($brand = mysql_fetch_array($result)){
echo
'<li><input type="checkbox" id="'.$brand['Brand'].'" value="'.$brand['Brand'].'"'; if(strpos($_SESSION['brand'],''.$brand['Brand'].'') !== false){ echo 'checked="checked"';} echo' />
<label for="'.$brand['Brand'].'" class="checkbox_title">'.$brand['Brand'].'</label></li>';
It seems like the very last two lines (everything between <li></li> tags) does not get "noticed" by the upper js-function. When I put exactly these <li></li> tags into index.php - along with all php parts - however, it works fine.
Please let me know if this is clear.
Does anybody have an idea on how to fix this issue?
Thank you!
ajax call:
$(document).ready(function() {
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#search_brand').val();
$('b#search-string').text(query_value);
$.ajax({
type: "POST",
url: "php/search_brand.php",
data: { query: query_value },
cache: false,
success: function(html){
$("div#results").html(html);
}
});
}
[...]

Categories