Passing of variable from Jquery to PHP - javascript

I am trying to get the server show the client's date and time, but that is not showing the correct output. Here is the relevant part of the code:
<script type="text/javascript">
$(function(){
var d = new Date();
var dateStr = d.toString()
$.post(window.location, {
dateStr: dateStr
});
alert(dateStr);
});
</script>
<div id="divMessage">
<?php
$dstr = 'nothing!';
if(isset($_POST["dateStr"]) && strlen(trim($_POST["dateStr"])) > 0)
$dstr = $_POST["dateStr"];
$v = 'current date/time is '.$dstr;
echo "<span style=\"color:green\">$v</span>";
?>
</div>
If the code is correct, I should see "current date time is <client's date/time>", but instead I see "current date time is nothing!". What mistake am I doing here?

Hope this helps, there were several things you needed to add to make it work.
Checking if the page was submitted via post and then parsing the response for the message to redisplay it.
<script type="text/javascript">
$(function(){
var d = new Date();
var dateStr = d.toString();
$.post(window.location, {
dateStr: dateStr
}).success(function(data){
var res = $(data).filter('#divMessage').text();
//console.log(res);
$('#divMessage').replaceWith(res);
});
});
</script>
<div id="divMessage">
<?php
//include "simple_html_dom.php";
//$html = new simple_html_dom();
//$html->load_file('index2.php');
//$v = $html->find('div[id=box]', 0)->plaintext;
if (!empty($_POST['dateStr'])) {
$dstr = 'nothing!';
if (isset($_POST["dateStr"]) && strlen(trim($_POST["dateStr"])) > 0) {
$dstr = $_POST["dateStr"];
}
$v2 = 'current date/time is ' . $dstr;
echo "<span style=\"color:green\">$v2</span>";
}
?>
</div>

As other said your have to use 2 file one with the js and other for php, in file.php you can make what you want for example to save in db. I tried to comment the code if you don't understand something feel free to ask.
check the path where you save the file php
file.php
<?php
$result = Array();
if (isset($_POST['action'])) {
$client_date = new Date();
// HERE YOU CAN USE FOR SAVE IN DB
$result ['result_msg'] = 'success';
$result ['client_date'] = $client_date;
} else {
$result ['result_msg'] = 'error';
}
echo json_encode($result);
?>
html
$(document).ready(function(){
$.ajax({
type: "POST",
url: "file.php",
data: {
action : 'what you want'
// IF YOU WANNA SAVE CLIENT INFORMATION HAVE TO MAKE A FORM AND PASS DATA HERE FOR EXAMPLE CLIENT ID ....
},
dataType: 'json'
}).done (function(result) {
result = JSON.parse(JSON.stringify(result));
if (result.result_msg === 'success') {
console.log(result.client_date); // YOU CAN SHOW IN HTML DIV
} else {
console.log('ERROR');
}
}).fail(function(result) {
console.log('ERROR');
});
});
Cheers!!!

Here is what you're missing, see what's data returned from server :)
<script type="text/javascript">
$(document).ready(function(){
var d = new Date();
var returnFromServer =
var dateStr = d.toString()
$.post(window.location, {
dateStr: dateStr
}).success(function(data){
//this is return from server
alert(data);
});
alert(dateStr);
});
</script>
<div id="divMessage">
<?php
$dstr = 'nothing!';
if(isset($_POST["dateStr"]) && strlen(trim($_POST["dateStr"])) > 0)
$dstr = $_POST["dateStr"];
$v = 'current date/time is '.$dstr;
echo "<span style=\"color:green\">$v</span>";
?>
</div>
Anyways you need to split files up , because I think this will return the whole page, and the span with your color :)

Related

How to make script tag work inside a div?

I am building an edit feature of a post on a website, so i am using jquery ajax and php as the script file that makes the edit inside a database. The problem is in the return script, i have a script tag which contains some jquery and then i place the returned data inside a div, but the script tag is being printed as if it was a text. Can someone help me please to let the script tag act as an actual script and not being printed as text ?
here is my html div :
<div class="board_post_span" id="<?php echo $board_id."-".$board_user_id;?>-spanBoardEdit"><?php echo $board_post;?></div>
and here is my php script :
<?php
require_once '../includes/session.php';
require_once '../includes/functions.php';
require_once '../includes/validation_functions.php';
require_once '../includes/create_thumbnail.php';
// this to prevent from accessing this file by pasting a link to it
if(!is_ajax_request()) {
exit;
}
if(isset($_POST['board_id'], $_POST['board_textarea'])) {
$board_id = (int)$_POST['board_id'];
$board_textarea = mysql_prep($_POST['board_textarea']);
// UPDATE table
$query = "UPDATE board_table ";
$query .= "SET board_post = '$board_textarea' ";
$query .= "WHERE board_id = $board_id";
$result = mysqli_query($connection, $query);
// now we select the updated board post
$query2 = "SELECT * FROM board_table ";
$query2 .= "WHERE board_id = $board_id ";
$result2 = mysqli_query($connection, $query2);
confirm_query($result2);
$result_array = mysqli_fetch_assoc($result2);
}
?>
<?php
echo $result_array['board_post'];
?>
<script>
// This takes care of the board Continue Reading feature ---------------------------------------------------------
$(".board_post_span").each(function(){
var boardPostText = $(this).text();
var boardPostLength = boardPostText.length;
var boardIdAttribute1 = $(this).attr("id");
var boardIdAttributeArray1 = boardIdAttribute1.split("-");
var boardPostId = boardIdAttributeArray1[0];
var boardPostUserId = boardIdAttributeArray1[1];
if(boardPostLength > 250) {
var boardPostTextCut = boardPostText.substr(0, 250);
$(this).text(boardPostTextCut+"...");
$("#"+boardPostId+"-continueReading").remove();
$(this).after('Continue Reading');
} else {
$(this).text(boardPostText);
}
});
</script>
and here is my jquery and ajax :
$.ajax({
url: url_edit_board,
method: "POST",
data: {
board_id: saveBoardButtonId,
board_textarea: editBoardTextareaVal
},
beforeSend: function() {
CustomSending("Sending...");
},
success: function(data){
$("#sending_box").fadeOut("Slow");
$("#dialogoverlay").fadeOut("Slow");
// this makes the scroll feature comes back
$("body").css("overflow", "scroll");
console.log(data);
$("#"+saveBoardButtonId+"-"+editBoardButtonUserId+"-spanBoardEdit").html(data);
$("#"+saveBoardButtonId+"-formBoardEdit").hide();
$("#"+saveBoardButtonId+"-"+editBoardButtonUserId+"-spanBoardEdit").show();
}
});
The reason is that you're setting boardPostText to the text of the entire DIV, which includes the <script> tag inside the DIV. You should put the text that you want to abbreviate inside another span, and process just that.
So change:
echo $result_array["board_post"];
to:
echo "<span class='board_post_text'>" . $result_array["board_post"] . "</span>";
Then in the JavaScript you're returning you can do:
$(".board_post_text").each(function(){
var boardPostText = $(this).text();
var boardPostLength = boardPostText.length;
var boardIdAttribute1 = $(this).attr("id");
var boardIdAttributeArray1 = boardIdAttribute1.split("-");
var boardPostId = boardIdAttributeArray1[0];
var boardPostUserId = boardIdAttributeArray1[1];
if(boardPostLength > 250) {
var boardPostTextCut = boardPostText.substr(0, 250);
$(this).text(boardPostTextCut+"...");
$("#"+boardPostId+"-continueReading").remove();
$(this).after('Continue Reading');
} else {
$(this).text(boardPostText);
}
});
First of all, it seems you don't need else part:
else {
$(this).text(boardPostText);
}
Then, before do anything, make sure that your return data from PHP file, the text has not become encrypted in some way. if < becomes < then the text never consider as JS code.
You can create a script tag then place your JS script into it as a function then call it yourself right after injecting.
replace your script in PHP file with this:
<script>
var scriptText = `function editPost() {
$(".board_post_span").each(function(){
var boardPostText = $(this).text();
var boardPostLength = boardPostText.length;
var boardIdAttribute1 = $(this).attr("id");
var boardIdAttributeArray1 = boardIdAttribute1.split("-");
var boardPostId = boardIdAttributeArray1[0];
var boardPostUserId = boardIdAttributeArray1[1];
if (boardPostLength > 250) {
var boardPostTextCut = boardPostText.substr(0, 250);
$(this).text(boardPostTextCut+"...");
$("#"+boardPostId+"-continueReading").remove();
$(this).after('<a href="board_comment.php?
user_id='+boardPostUserId+'&board_id='+boardPostId+'" class="board_continue_reading" target="_blank" id="'+boardPostId+'-continueReading">Continue Reading</a>');
}
});
}`
</script>
then change your js file to:
$.ajax({
// ...
success: function(data) {
// ...
var container = $("#"+saveBoardButtonId+"-"+editBoardButtonUserId+"-spanBoardEdit")
container.html(data)
var scriptEl = $('<script></script>').html(scriptText).appendTo(container)
// now call the editPost function
editPost()
$("#"+saveBoardButtonId+"-formBoardEdit").hide();
container.show();
}
});

moment.js:423 Uncaught TypeError: Cannot read property '_calendar' of undefined

I am using fullcalendar, and what I want to make is when user click the event, then ask if user want to extend the class time. If user canceled the course(which is in my DB) before, then user can extend the class time for 15minutes. So, if user can extend the class, then send the information to mysqlDB by using ajax and php. However, the problem is all the information, which is endDate, startDate, and canceledCourseDate, and end(endDate before extend), is correctly sended to ajax, but I got error.
Uncaught TypeError: Cannot read property '_calendar' of undefined
Thus, I searched some information, and I added .format("YYYY-MM_DD HH:mm"), but still have problem.
Here is js code
var canceledList = <?php echo $json_array4; ?>; //not newlyBooked canceled Date List
var canceledListNum = canceledList.length;
var extensionList = <?php echo $json_array10; ?>;
var extendedListNum = extensionList.length;
var canceledDate = '';
var extensionStatus = 'going';
if(extendedListNum > 0)
{
canceledDate = extensionList[0]['canceledCourseDate']; //get canceledDate that is alreay in extension
}
else if(canceledListNum > 0)
{
canceledDate = canceledList[0]['canceledCourseDate']; //if there is no course that is in extension, then get new canceledDate that isn't done yet.
extensionStatus = 'new';
}
var id = calEvent.id;
var teacher = calEvent.resourceId;
var extendedDate = moment(calEvent.start.format("YYYY-MM-DD HH:mm"));
var end = moment(calEvent.end.format("YYYY-MM-DD HH:mm"));
var endDate = moment(end).add(15, 'minutes');
console.log(start);
console.log(extendedDate);
console.log(end);
console.log(endDate);
console.log(canceledDate);
var limit = 2;
var userDuration = '<?php echo $userDuration; ?>';
if(userDuration == '60')
{
limit = 4;
}
if(id == '<?php echo $userID; ?>')
{
}
else // extend lesson
{
if(new Date(start) < new Date(today))
{
alert("cannot extend the class");
}
else{
if(canceledDate == '')
{
alert("cannot extend the class");
}else
{
$.ajax({
url:"extend.php",
type:"POST",
data:{userName: '<?php echo $name; ?>' , canceledCourseDate: canceledDate, extendedDate: extendedDate , endDate: endDate ,courseTeacher : teacher, userBranch:'<?php echo $userBranch; ?>', userID: '<?php echo $userID; ?>', duration : '<?php echo $userDuration; ?>', originalEnd : end, extensionStatus: extensionStatus},
success:function(response)
{
console.log(response);
$("#calendar").fullCalendar('refetchEvents');
alert("Successfully extended.");
location.reload();
}
});
}
}
}
}
Then here is the image of console,
var end = moment(calEvent.end.format("YYYY-MM-DD HH:mm"));
this is not working. However,
var endDateForAdd = moment(endDate).format("YYYY-MM-DD HH:mm");
this is working.

Form submit variables are lost when dealing with jquery variables in PHP

I have a starting page, where the user gives some information (Email and Name) and press submit. When the second page is entered, jquery sends some variables (dateStr) to that second page from within that second page. However, I notice that doing so makes the form submit variables disappear. I have shown the relevant part of the code here. YourEMail and YourName turn out to be empty strings here. What mistake am I doing?
<?php
$YourEMail = $_REQUEST['YourEMail'];
$InputName = $_REQUEST['YourName'];
$dateAndTime = '';
if(isset($_POST["dateStr"]) && strlen(trim($_POST["dateStr"])) > 0)
{
$dateAndTime = $_POST["dateStr"];
// $dateAndTime is fine, but $YourEMail and $InputName are empty here!
......
}
?>
The jquery code to post $dateStr from within the second page is shown below.
<script type="text/javascript">
$(function(){
var d = new Date();
var dateStr = d.toLocaleString();
$.post(window.location, {
dateStr: dateStr
}).success(function(data){
$('#divMessage').replaceWith("<span style=\"color:yellow\">" + dateStr + "</span>");
});
});
</script>
</head>
I just changed your Jquery code a bit. Try it:-
<script type="text/javascript">
$(function(){
var d = new Date();
var dateStr = d.toLocaleString();
var data ={ dateStr: d.toLocaleString(),YourEmail :'<?=$_POST['YourEMail']?>',YourName : '<?=$_POST['YourName']?>'}
$.post(window.location, data ).success(function(data){
$('#divMessage').replaceWith("<br /><span style=\"color:yellow\">dateStr = "
+ dateStr + "</span>");
});
});
</script>
</head>
OK, I solved the problem. For anybody interested, here is the solution. I would like to thank ADyson for his advice on session variables.
<?php
// Start the session
session_start();
?>
....
<?php
if (isset($_POST['submit']))
{
$YourEMail = $_REQUEST['YourEMail'];
$InputName = $_REQUEST['YourName'];
$_SESSION["email"] = $YourEMail;
$_SESSION["name"] = $InputName;
}
$dateAndTime = '';
if(isset($_POST["dateStr"]) && strlen(trim($_POST["dateStr"])) > 0)
{
$YourEMail = $_SESSION['email'];
$InpuName = $_SESSION['name'];
$dateAndTime = $_POST["dateStr"];
......
}
?>

How to return JS value using AJAX

I have a code like this
$(document).ready(function() {
$('#myHref').change(function(){
var value = $('#myHref').val();
$.get('get_projectName.php',{id:value},function(data)
{
.....
.....
if(condition here){}
});
});
});
I need to check a condition according to the value returned from get_projectName.php. Let get_projectName.php have $abc = 1; and according to this value I need to use if condition.
Your jquery condition will be totally depend on the type of data returned from the php function. Let's check for the example:-
Example 1 :-
If your php code is :-
<?php
if(isset($_GET['id'])){ // check id coming from `ajax` or not
$data = 1; // as you said
}
echo $data;
?>
Then jquery will be:-
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script><!-- library needed-->
<script type = "text/javascript">
$(document).ready(function() {
$('#myHref').change(function(){ // you need to check that it is working or not because i don't know from where it is coming
var value = $('#myHref').val(); // same as above check yourself.
$.get('get_sales_price.php','',function(data){
if(data ==1){
alert('hello');
}else{
alert('hi');
}
});
});
});
</script>
Example 2:-
But if your php code is like below:-
<?php
if(isset($_GET['id'])){ // check id coming from `ajax` or not
$data = Array('a'=>1,'b'=>2);
}
echo json_encode($data);
?>
then jquery will be like below:-
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script type = "text/javascript">
$(document).ready(function() {
$('#myHref').change(function(){
var value = $('#myHref').val();
$.get('get_sales_price.php','',function(data){
var newdata = $.parseJSON(data);//parse JSON
if(newdata.a ==1 && newdata.b !== 1){
alert('hello');
}else{
alert('hi');
}
});
});
});
</script>
Note:- these are simple examples, but conditions will vary in jquery, based on returned response from php. thanks.
Forgot the .done
$.get('get_projectName.php',
{id:value}
).done(function(data) {
console.log(data)
var data2 = JSON.parse(data);
if(data2.abc === 1)
{
//Do something
}else{
//Else Do something
}
});
You can write code as below -
//At javscript end
$.get( "get_projectName.php", function( data ) {
if(data == "1"){
// do your work
}
});
// At php end
<?php
$abc = 1;
echo $abc;
?>
Hope this will help you.
In main-php-file On change of value, Fetch the value pass it a php file sub-php-file via ajax
In sub-php-file, echo the ouput in json format
Retrieve the output and do the calculation
jQuery library, if never included
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
ajax
<script type="text/javascript">
$(document).ready(function(){
$('#myHref').on('change', function(){
var value = $('#myHref').val();
$.ajax({
type: "POST",
url: "get_projectName.php",
data: { id:value },
dataType: "json",
success: function(theResponse) {
var abc = theResponse['abc'];
if (abc == 1) {
//Do something
} else {
//Else Do something
}
}
});
});
});
</script>
get_projectName.php
<?php
$id = isset($_POST['id']) ? $_POST['id'] : '';
$ReturnArray['abc'] = 1;
echo json_encode( $ReturnArray );
?>

Set interval with AJAX

The purpose is to display a DIV when you click on a button and then display text inside that DIV that comes from my database. Thing is that data in databse changes, so text inside that div also. I would need a setInterval... with AJAX
I'm new in javascript and don't know the good way to go...
HTML:
<div onClick="showDiv();"> click </div>
<div style="display: none;" id="div">
Info from database:
<span style="display: hidden;" id="data1"> DATA 1 </span>
<span style="display: hidden;" id="data2"> DATA 2 </span>
</div>
javascript:
function showDiv()
{
document.querySelector("#div").style.display = "block";
setInterval(function () {getData()}, 1000);
}
function getData()
{
$.post(
'process.php',
{
},
function(data){
if(data == '1'){
document.querySelector("#data1").style.display = "inline";
}
else if(data == '2'){
document.querySelector("#data2").style.display = "inline";
}
},
'text'
);
return false;
}
//don't know how to just take data from database without sending by POST or GET.
php:
<?php
SELECT x FROM database
if(x == 1)
{echo '1';}
else if(x == 2)
{echo '2';}
?>
Get data using AJAX : Learn here. Your code to setInterval() is correct or you can do this : setInterval(getData,1000);
Display data in spans :
document.getElementById("data1").innerHTML = "your content from database";
document.getElementById("data2").innerHTML = "your content from database";
You're not giving a lot of info so I will give you a basic example of getting data from a mySQL database with jQuery, Ajax and PHP.
First you need to include jQuery to the head of your document
<script src="http://code.jquery.com/jquery-latest.js"></script>
And then use Ajax
function showDiv(){
document.getElementById("div").style.display = "";
setInterval(function (){ getData('something'); }, 1000);
}
jQuery.noConflict();
jQuery(document).ready(function($){
getData = function(variable){
var postVar = variable;
var postVar2 = "exemple";
$.ajax({
type: "POST",
url: "php/file.php",
data: 'variable=' + postVar + "&" +
'variable2=' + postVar2,
success: function(data){
data = $.trim(data);
var dataSplit = data.split("++==09s27d8fd350--b7d32n0-97bn235==++");
if(dataSplit[0] == "1"){
document.getElementById("data1").innerHTML = dataSplit[1];
}
if(dataSplit[0] == "2"){
document.getElementById("data2").innerHTML = dataSplit[1];
}
}
});
}
});
Finally, you need to create an external php file (in this example "file.php" in the folder "php") to get the data from your database with mysqli
<?php
// to prevent error, I check if the post variable is set and
// if it's not only full of spaces
if(isset($_POST['variable']) && preg_replace("/\s+/", "", $_POST['variable']) != ""){
$con = mysqli_connect("hostname", "username", "password", "database_name");
$query = mysqli_query($con, "SELECT * FROM `table_name` WHERE `column_name` = '".$_POST['variable']."'");
$results = array(); $row = 0;
while($info = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$results[$row] = array();
$results[$row]['column_name1'] = $info['column_name1'];
$results[$row]['column_name2'] = $info['column_name2'];
$row++;
}
foreach($results as $result => $data){
echo "1" . "++==09s27d8fd350--b7d32n0-97bn235==++" .
'<div>'.$data['column_name1'].'</div>'.
'<div>'.$data['column_name2'].'</div>';
}
}
?>
Hope it helps!

Categories

Resources