I create articles on an administration and on each article i have a button to like it, at the onclick, the javascript call the php code in an other file to fill the database, and the database should resend the number of like, but the echo on the processing file doesn't fill the reponseText of the XMLHttprequest and I don't know why and that's I'am trying to solve and understand.
I succeeded to do it but I don't want to refresh the page at each like, so i use XMLHttpRequest to display correctly the likes whithout refreshing.
I followed serevals tutoriels, but that doesn't work well.I had to miss something.
First I have a file : index.php with my javascript and php code:
<ul class="ulp">
<li class="lip">
<button class="likebutton" onclick="like('<?= $ipclient ?>','<?= $event->getID()?>')" style="color:#5B5A57">
<i id="coeur<?= $event->getID()?>" class="<?= $classlike ?>">
<span id="nblike<?= $event->getID()?>">
<?= $tableLikes->countLike($event->getID()) ?>
</span>
</i>
</button>
</li>
</ul>
<script>
function like(ipclient,eventid)
{
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200)
{
document.getElementById("nblike" +eventid).innerHTML = this.responseText;
};
xhttp.open("GET","event/" + ipclient + "-" + eventid, true);
xhttp.send();
}
</script>
When I am cliking on this button that send correctly the request.
I have a second file that processes the data:
<?php
use App\Model\Likes;
use App\Table\LikesTable;
use App\Connection;
$pdo = Connection::getPDO();
$like = new Likes();
$tableLike = new LikesTable($pdo);
$ip = $params['ip'];
$id_event = $params['id'];
if($tableLike->likeIp($ip,$id_event) === true){
$like->setId_article($id_event);
$like->setIp($ip);
$tableLike->newLike($like);
}else if($tableLike->likeIp($ip,$id_event) === false){
$tableLike->dislike($ip,$id_event);
}
echo $tableLike->countLike($id_event);
I would like to have the content of the last echo in the reponseText of my object XMLHttpRequest.
How can I do ?
Thanks you in advance .
Related
I want to build a simple program using XMLHttpRequest to calculate the area of the triangle. I used this code for client-side;
<body>
<form>
<label for="txtLength">Length</label>
<input type="text" id="txtLength" name="txtLength"><br><br>
<label for="txtWidth">Width</label>
<input type="text" id="txtWidth" name="txtWidth"><br><br>
<input type="hidden" name="submitted" value="1">
<input type="button" name="Calculate" value="Calculate" onclick="calArea();">
</form><br><br>
<div id="showArea">Enter Values and click Calculate.</div>
<script type="text/javascript">
function calArea() {
var len = document.getElementById("txtLength").value;
var wid = document.getElementById("txtWidth").value;
var sub = 1;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.readyState == 200) {
document.getElementById("showArea").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "calculate_area.php", true);
xhttp.send(len&wid&sub);
}
</script>
</body>
This code is for the server side.
<?php
print_r($_POST);
if (isset($_POST['sub'])) {
$len = $_POST['len'];
$wid = $_POST['wid'];
$area = (($len*$wid)/2);
echo $area;
}
else{
echo "Not input detected.";
}
?>
Even tried so many codes, It doesn't send the data to server side.
I found the mistake. I was sending the parameters as part of the URL, but need to send them as part of the request body.
Client-side code;
function calArea() {
var len = document.getElementById("txtLength").value;
var wid = document.getElementById("txtWidth").value;
var sub = 1;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("showArea").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "calculate_area.php", true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.send(JSON.stringify({len: len, wid: wid, sub: sub}));
}
Server-side code;
if (isset($_POST['sub'])) {
$len = $_POST['len'];
$wid = $_POST['wid'];
$area = (($len*$wid)/2);
echo $area;
}
else{
echo "Not input detected.";
}
len&wid&sub
Taking some variables and putting the Bitwise & between them is not going to give you a useful value to submit to the server.
You need to encode the data in a format that you can transmit over HTTP and which your server-side code can read.
PHP supports URL Encoded and Multipart Form Encoded data natively so pick one of those.
The URLSearchParams API will generate URL Encoded data for you.
e.g.
xhttp.send(new URLSearchParams({ len, wid, sub }));
Passing a URLSearchParams object will also let XHR automatically set the correct Content-Type request header so PHP will know what it needs to do to decode the data and populate $_POST with it.
You need to put all the parameters into a string of the form name=value with each one separated by &. And the values should be encoded in case they contain special characters.
You also need to set the content type so this data will be parsed correctly.
So change
xhttp.send(len&wid&sub);
should be:
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhttp.send(`len=${encodeURIComponent(len)}&wid=${encodeURIComponent(wid)}&sub=${encodeURIComponent(sub)}`);
I need to know what can done to display data from mysql database in cordova app.
I made a php file placed it on the server.
then i made the html with json code to fetch data from mysql database.
The data from mysql database should be displayed in the div with id="demo".
I have done this till now.
My Php file looks like this:
<?php
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);
include "../../webConfig/web.config.php";
$conn = connect();
$q = $conn->query("SELECT name FROM 'online_' ORDER BY DESC");
$rows=$conn->query($cb);
$rows=$conn->query($cb);
foreach($rows as $row){
echo $row["ID"];
echo $row["first_name"];
echo $row["middle_name"];
echo $row["last_name"];
}
echo json_encode($rows);
?>
My HTML file Looks like this.
<div data-role="content">
<div class="container-fluid">
Online Application
<p id="demo">
.....
</p>
<script>
var obj, dbParam, xmlhttp;
obj = { "table":"online", "limit":10 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "http://localhost/admin/notify/test.php?x=" + dbParam, true);
xmlhttp.send();
</script>
</div>
</div>
I have been trying to do this using json But my html file dosen't show anything apart from those dots.
I tried placing the php file on the web server as well, but still it did not show anyhing.
I am following a tutorial on W3Schools for AJAX PHP. https://www.w3schools.com/php/php_ajax_php.asp
Here is the twist: I am doing this in wordpress. The following is a method that DOES work, but it is less than ideal.
1) Create the following gethint.php in the root directory.
<?php
// Array with names
$a[] = "Anna";
$a[] = "Brittany";
...
$a[] = "Vicky";
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}
// Output "no suggestion" if no hint was found or output correct values
echo $hint === "" ? "no suggestion" : $hint;
2) Using the CSS & Javascript toolbox plugin, add this code to the header:
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "/gethint.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
3) Create a page with the following code (in plain text):
<p><b>Start typing a name in the input field below:</b></p>
<form>
First name: <input type="text" onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
While this works, having to create a php file and adding to the root directory seems like bad practice. It would be better to have this php file stored in the plugins directory. However that causes this line of the header script to fail as 404:
xmlhttp.open("GET", "/gethint.php?q=" + str, true);
Simply changing the relative path won't work, because theoretically, different users can have their plugin folder in different locations.
I figure I should be using the wp_ajax_ and wp_ajax_nopriv_ hooks, but my attempts I have failed, so I am probably doing it wrong. Please help.
Doing ajax in WordPress should all be sent to /wp-admin/admin-ajax.php,
to do that, in your plugin's main file or the index.php file,
register your ajax action like this:
// let's do the ajax thing here
add_action( 'wp_ajax_theNameOfMyCustomAjax', 'theFunctionThatMyAjaxWillCall' );
function theFunctionThatMyAjaxWillCall() {
// include your ajax file here, in this case
// I assumed that we placed the gethint.php in
// /wp-content/plugins/yourpluginname/gethint.php
include( plugin_dir_path( __FILE__ ).'gethint.php' );
// don't forget to add "die;" every time you return a response to your ajax
//Example: echo $hint ?? "no suggestion"; die;
// or you can add the termination code right here
die; // this will prevent the ajax response to have 0 in the end.
}
Now, in your javascript, instead of calling the filename of your ajax file, you can now use the global ajaxurl javascript variable like this:
xmlhttp.open("GET", ajaxurl+"?action=theNameOfMyCustomAjax&q=" + str, true);
I have a main file
index.php
in which I include four other files like
header_get_started.php,
content_main.php,
right_sec_home.php,
footer.php.
Here is my code
"index.php"
<script src="js/ajax.js"></script>
<?php include_once('header_getstarted.php'); ?>
<?php include_once('content_main.php'); ?>
<?php include_once('right_sect_home.php'); ?>
<?php include_once('footer.php'); ?>
"header_getstarted.php"
<span class="select_input">
<?php
$sqlCmd = "some query";
echo combo('cmb_command','custom-class1 custom-class2','cmd_name','cmd_id','0',$sqlCmd,'sendpostmtu()' $width="style='width:250px;cursor:pointer;'")
?>
<input type="submit" name="" class="sub_bg" value="" onclick="get_request_by_command($('#cmb_command').val());">
</span>
In header_get_started.php
When select any command from select box, I want to assign it's id to $_SESSION['id'].
Onclick of selection box I have an ajax request which can refresh the main content (content_main.php). Also I want that selected id in another page in right_sec_home.php to refresh it's content.
How can I assign the php session id in JS file for 2nd page?
My JS file is
function get_request_by_command (commandId) {
var cmdTitle=$('#cmb_command :selected').text();
if(cmdTitle=="") {
cmdTitle='ABC';
}
$("#main_wrap").hide();
if(cmdTitle=='--Select--'){
$("#cmdTitle").html("");
}else{
$("#cmdTitle").html(cmdTitle);
}
$("#cmbs_cmd").val(commandId);
document.getElementById('request_list').innerHTML='<img src="images/loader.gif" />';
var strURL="request_by_command_tbl.php?id="+commandId;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
var ret = req.responseText;
$("#requestTitle").html("<span id='cmdTitle'>"+cmdTitle+"</span>);
$('#request_list').html('');
$('#request_list').html(ret);
$('#main').show();
$("#searchDiv").show();
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
With using this jQuery function, I have created an ajax request, and send the id to the "request_by_command_tbl.php" file.
In "request_by_command_tbl.php" file i assigned,
$_SESSION['id'] = $_REQUEST['id'];
Also I want this $_SESSION['id'] in right_sec_home.php at same instant.
So is their any way to assign php $_SESSION['id'] in the jQuery script file before sending ajax request.
My other files
"content_main.php"
<div id="request_list"> </div>
<div> </div>
<div id="add_space"></div>
Right section home file in which i need session id
"right_sec_home.php"
<?php
function getRequestByMonth($month, $year, $id){
$que ="SELECT distinct(MS.date) FROM commands AS MC , ranks AS MR ,steady_tours AS MST, preferred_tours AS MPT, registration AS MMS where date_format(rm_date, '%c-%Y') = '".$month."-".$year."'
AND MMS.cmd_id ='".$_SESSION['id']."'
order by MMS.date";
$res = mysql_query($que);
while($rows[]=mysql_fetch_array($res)){}
foreach ($rows as $res):
if($res['date'] == "") continue;
$dt = date("Y-n-j", strtotime($res['date']));
$return[getDateB($dt)] = $res['date'];
endforeach;
return $return;
}
I hope that this is clear enough.
Any ideas?
Please help.
there is no way for you to access the session information with jquery ..
explanation
sessions are files stored on the server --> where is java script is only a client side language ..
there is always a work around .. but i guess you should explain more about what exactly you want to achieve
<?php $sessionId = session_id(); ?>
<input id="session_id" name="session_id" type="hidden" value="<?php echo $sessionId; ?>" />
Get the value of the hidden field using jquery.
You can use some hidden fields or script variables inside the php file.
example :
<script>
var id = <?php echo $_SESSION['id']; ?>;
</script>
varible id can be accessible using the javascript or jquery
Using that javascript ajax function I pass the content of a form, that contain
the dato value, to the PHP login.php than trought the echo pass back the content
(the insert form) that I want to be switched to the cancel form, using
the content respondText (that may take only the echo of the PHP).
BUT INSTEAD the responseText contain ALL the html code, with the old html
plus the cancella_form passed by the echo, that's also out of the div
with id=visibile.
Any ideas why? D:
//ajaxSubmit(dato)
function ajaxSubmit( url , divId , hideId ) {
//in setXmlHttpObject() I just control the user's browser
// and assign the right XmlHttp Object
var ajaxRequest = setXmlHttpObject();
var dato = 'nome='+document.getElementsByName('dato')[0].value;
ajaxRequest.open("POST", url, true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.send(dato);
ajaxRequest.onreadystatechange = function() {
//Comunication complete
if (ajaxRequest.readyState == 4 && ajaxRequest.status==200) {
//Comuncation succesfull
if(ajaxRequest.statusText === "OK"){
var str= ajaxRequest.responseText;//<<<HERE///////
$(str).replaceAll("#visibile");
}
//Comuncation failed
else{
var str= "ERROR: Ajax: "+ajaxRequest.responseText;
document.write(str);
}
}
}
}//FINE ajaxRequest();
<?php
include("prova_login_adv.php");
$conn= mysql_connect('localhost','root','');
mysql_select_db('db_prova',$conn ) or die(mysql_error());
//
if(isset($_POST['nome'])){
$dato= $_POST['nome'];
mysql_query(" INSERT INTO test (valore) VALUES ('$dato') ") or die(mysql_error());
/// NOW I declare what I want to be replaced in the div id="visibile"
echo "
<form id='form_cancella' name='form_cancella' action='' methos='POST' onSubmit=' return false;' >
<text name='dato' value='".$dato."' >Benvenuto <b>".$dato."</b></text>
<input type='submit' name='cancella' value='cancella' onClick=\" ajaxSubmit('logout.php','visibile','form_cancella');\" />
</form>
";
}
?>