My javascript function (url) doesnt go to the php page - javascript

I have a question which is probably easy to solve but due to my lack of javascripting skills I find it rather hard.
I am using a function to auto-complete database info in a search bar. For that I'm using this javascript function:
<script type="text/javascript">
$(function(){
$(".search").keyup(function(){
var inputSearch = $(this).val();
var dataString = 'searchword='+ inputSearch;
if(inputSearch!=''){
$.ajax({
type: "POST",
url: "http://marceldepender.nl:2222/CMD_FILE_MANAGER/domains/marceldepender.nl/public_html/Recap/wp-content/themes/radiate/templates/search.php",
data: dataString,
cache: false,
success: function(html){
$("#divResult").html(html).show();
}
});
}
return false;
});
jQuery("#divResult").live("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find('.name').html();
var decoded = $("<div/>").html($name).text();
$('#inputSearch').val(decoded);
});
jQuery(document).live("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search")){
jQuery("#divResult").fadeOut();
}
});
$('#inputSearch').click(function(){
jQuery("#divResult").fadeIn();
});
});
</script>
As you can see in the first part of the function, there is a value called url: this url includes (at least I think that is what it does) a certain php page when the if statement is true. This php page (search.php) does a query and gives output related to the search terms.
Though for some reason, the javascript function doesn't go to that search.php page. I have done / tested several things:
IN the original document the url was just plan: url: "search.php", - I changed it to the entire link where the search.php is on though since the previous url didn't work (the new one doesn't either though).
I changed the search.php to some easy echo code just so I know the page is being included / redirected to.
For some reason (and I think it is because the search.php isn't being included) the code doesn't work.. The page where the javascript function is on, is located on a directadmin files on the net, the search.php is also located in this same map.
So the question is: why isn't my search.php included and how can I fix this?
For some better understanding of my search.php code I inserted the original code below:
<?php
include('includes/db.php');
if($_POST){
$q=$_POST['searchword'];
$sql_res=mysql_query("select uid,username,email,media,country from test_auto_complete where username like '%$q%' or email like '%$q%' order by uid LIMIT 5");
while($row=mysql_fetch_array($sql_res)){
$username=$row['username'];
$email=$row['email'];
$media=$row['media'];
$country=$row['country'];
$b_username='<b>'.$q.'</b>';
$b_email='<b>'.$q.'</b>';
$final_username = str_ireplace($q, $b_username, $username);
$final_email = str_ireplace($q, $b_email, $email);
?>
<div class="display_box" align="left">
<img src="<?php echo $media; ?>" style="width:50px; height:50px; float:left; margin-right:6px;" /><span class="name"><?php echo $final_username; ?></span> <br/><?php echo $final_email; ?><br/>
<span style="font-size:9px; color:#999999"><?php echo $country; ?></span></div>
<?php
}
}
?>

Related

Trying to print onto an html page via PHP

I'm making a custom WYSIWYG editor with a save function, and through the save function I have run some code to get everything within a certain div, save it into a data table or overwrite it. But right now, I'm trying to load the page back.
The process is as follows: you press the save button, and it runs a PHP script called save.php, which is seen below.
My issue is that I want it to load or echo the contents within a certain div on the original html page. How would I go about doing that? I need it to work like Javascript's innerHTML function, basically.
Below are the files I use, at least the relevant parts.
test.html:
<form method="post" name="blog-post" id="blog-post">
<input type="hidden" name="postID" value="1"><!--Get the post's id-->
<div class="blog-editor-bar">
<a href="#" data-command='save'
onclick="submitForm('save.php');">
<i class='fa fa-save'></i>
</a>
</div>
<div id="blog-textarea" contenteditable>
</div>
<textarea style="display:none;" id="blog-post-cont" name="post-content"></textarea>
</form>
test.js:
function submitForm(action){
var theForm = document.getElementById("blog-post");
theForm.elements("post-content").value = document.getElementById("blog-textarea").innerHTML;
theForm.action = action;
theForm.submit();
}
save.php:
$conn = mysqli_connect('localhost', 'root', '', '');
if (mysqli_connect_errno()){
echo "<p>Connection Failed:".mysqli_connect_error()."</p>\n";
}
//store stuff in database
//Get Variables
$postid = $_POST['postID'] ? $_POST['postID'] : null;
$post = $_POST['post-content'] ? $_POST['post-content'] : null;
//if exists, overwrite
if($postid != null || $postid != ""){
$sqlSave = "SELECT * FROM wysiwyg.post WHERE idpost = $postid";
$rSave = mysqli_query($conn, $sqlSave) or die(mysqli_error($conn));
if(mysqli_num_rows($rSave)){
$sqlOverwrite = "INSERT INTO wysiwyg.post(post) VALUES(?) WHERE idpost = ?";
$stmt = mysqli_prepare($conn, $sqlOverwrite);
mysqli_stmt_bind_param($stmt, "sd", $post, $postid);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
mysqli_close($conn);
} else {
newSave();
}
loadSave();
}
function newSave(){
$sqlNewSave = "INSERT INTO wysiwyg.post(post) VALUES(?)";
$stmt = mysqli_prepare($conn, $sqlNewSave);
mysqli_stmt_bind_param($stmt, "s", $post);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
function loadSave(){
$sqlLoad = "SELECT * FROM wysiwyg.post WHERE idpost = $postid";
$rLoad = mysqli_query($conn, $sqlLoad) or die(mysqli_error($conn));
//This is the part I'm stuck on
}
Thank you all in advance for helping me out! I've been stuck on it for at least a few hours!
EDIT: Before people comment on SQL Injections, I have taken it into consideration. This is me getting the code working on my localhost before I run it through a ton of anti-sql injection methods that I have already done in the past. The code i provide is only important to the functionality at this point.
EDIT #2: The anti-injection code already exists. I guess i seem to have forgotten to provide that information. I repeat, the code I have provided here is only code relating to functionality. I have escaped the strings, trimmed, etc. and more, but that code is not necessary to provide for people to get an understanding of what it is i am trying to do.
You can use an AJAX request to communicate with the server, send data and receive a response. There are many good tutorials out there, but since I first learned it in W3Schools website I am going to refer you there.
JavaScript tutorial.
jQuery tutorial.
You can use an AJAX request which is written like this:
<script>
$(document).ready(function(){
$.ajax({ //start an AJAX call
type: 'GET', //Action: GET or POST
data: {VariableName: 'GETvalue'}, //Separate each line with a comma
url: 'Destination.php', //save.php in your case
success: function(data)){ //if values send do this
//do whatever
}
}); //end ajax request
});
</script>
This allows you to send information to your php page without refreshing
So in my example you can do this on the PHP side
<?php
echo $_GET['VariableName'];
?>
Will echo out "GETvalue as specified in the data section of the Ajax call"
EDIT************
In the AJAX call you can add dataType if you want json
$.ajax({
type: 'GET',
data: {VariableName: 'GETvalue'},
dataType: 'json' // Allows Json values or you can change it to whatever you want
url: 'Destination.php',

Making AJAX show a 'result data' in correct div witoud refreshing

I'm currently into developing simple 'one score' votting system and I'm facing the problem: though php script workd fine I cant get AJAX updating the answer div without reloading page. I've tried different methods, some do nothing, other reload page, for example, I've tried adding (return: false) after AJAX or PreventDefault in it. Here is html and php index page:
<body>
<div align="center">
<h3>Voting with jQuery, Ajax and PHP</h3>
<?php
include('config.php');
$sql=mysqli_query($bd, "SELECT * FROM messages LIMIT 9");
while($row=mysqli_fetch_array($sql))
{
$msg=$row['msg'];
$mes_id=$row['mes_id'];
$total_score=$row['total_score'];
?>
<div id="main">
<div class="box1">
<img class='image'src="img/thumbsup.png">
<span class='this'><?php echo $total_score; ?></span><div class='tr'></div>
<img class='image' src="img/icon-down.png"></div>
<div class='box2' ><?php echo $msg; ?></div>
</div>
<?php
}
?>
</div>
</body>
And here is my working up_vote.php (down_vote.php is almost same, so I wont add it)
<?php
include("config.php");
$ip=$_SERVER['REMOTE_ADDR'];
if($_POST['id'])
{
$id=$_POST['id'];
$ip_sql=mysqli_query($bd,"select ip_add from Voting_IP where mes_id_fk='$id' and ip_add='$ip'");
$count=mysqli_num_rows($ip_sql);
$sql = "update Messages set total_score=total_score+1 where mes_id='$id'";
mysqli_query($bd, $sql);
$sql_in = "insert into Messages (mes_id_fk,ip_add) values ('$id','$ip')";
mysqli_query($bd, $sql_in);
$count=mysqli_num_rows($ip_sql);
}
?>
And finally, the complete JQUERY - AJAX script (this's my problem - need to show the results in (div class = 'this') without refreshing the page):
$(function() {
$(".vote").click(function()
{
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if(name=='up')
{
$.ajax({
type: "POST",
url: "up_vote.php",
data: dataString,
cache: false,
success:function(data){
$(".this").append(data);
},
complete: function() {alert('complete');};
});} else
{
$(this).fadeIn(200).html('<img src="img/icon-down.png" align="absmiddle" style="height: 10px;width:10px;">');
$.ajax({
type: "POST",
url: "down_vote.php",
data: dataString,
cache: false
}).done(function ( data ) {
$('.this').append(data);
});
}
return false;
});
});
I have spent whole my day and I know the solution is obvious, Im just really new in this all and so I would appreciate any helpful response. Thanks in advance.
I have added this code to up_vote.php at the buttom:
$result=mysqli_query($bd, "select total_score from Messages where mes_id='$id'");
$row=mysqli_fetch_array($result);
$up_value=$row['total_score'];
echo $up_value;
Thanks to all of you guyz!!! It works now! The problem was that php script didnt return anything!!! As I though - obviouse))) THANKS!
HAve NEW PROBLEM NOW - WHEN I CLICK ON ICONS IT UPDATES ALL OF THEM!! IN EVERY DIV! I VOTE FOR ONE THING - AND IT ADDS VOTES FOR EACH ONE!! whats wrong with that?

How can I send javascript values to PHP script?

this is my php code that creates a table using the results of a mysql query:
echo "<table id='table' class='selectQuery'>
while($row = mysqli_fetch_array($slctQuery)) {
// ; echo $row['id']; echo
echo "<tr class='someClass' idNumber="; echo $row['id']; echo ">
<td>";
echo $row['fname'];
echo "</td>
<td>";
echo $row['lname'];
echo "</td>;
</tr>";
}
echo "</table>";
and this part is my jquery code for changing style on click on table row:
<script>
$(document).ready(function(){
$("#table tr").click(function(){
$('.someClass').removeClass('selected');
$(this).addClass('selected');
idNum = $(this).attr('idNumber');
});
$("#table tr").click(function(){
$("#DelEdtQuestion").addClass('selected1');
});
});
</script>
and this part is for style:
<style>
tr.selected {
background-color: brown !important;
color: #FFF;
}
</style>
and this is my php code for button
if(#$_POST['Search']){
/// what should I do?
}
So, now I want have my idNum value when my search button in form was clicked.
thanks for attentions
You can use ajax. If you have a form with id="myform" and (example) input fields: firstname, lastname, username and password, the following script should send data to the php:
$(document).ready(function(){
var datastring = $("#myform").serialize();
$.ajax({
type: 'POST',
url: 'ajaxfile.php',
data: datastring
}).done(function(res){
var res = $.trim(res);
alert(res);
});
});
The ajaxfile.php can be something like that:
<?php
$firstname = mysql_real_escape_string($_POST["firstname"]);
$lastname = mysql_real_escape_string($_POST["lastname"]);
$username = mysql_real_escape_string($_POST["username"]);
$password = mysql_real_escape_string($_POST["password"]);
//here you have the variables ready to do anything you want with them...
//for example insert them in mysql database:
$ins = "INSERT INTO users (firstname, lastname, username, password ) VALUES ( '$firstname', '$lastname', '$username', '$password' )";
if(mysql_query($ins)){echo "SUCCESS";}else{echo "FAILURE";}
?>
Another example, similar to yours, is to take the row id from your table, pass it to ajax, have ajax (for example) make a query to the database and return the results:
// your script, modified for ajax:
$(document).ready(function(){
$("#table tr").click(function(){
$('.someClass').removeClass('selected');
$(this).addClass('selected');
var idNum = $(this).attr('idNumber'); //use "var" to -initially- set the variable
$.ajax({
type: 'POST',
url: 'ajaxfile.php',
data: 'id='+idNum
}).done(function(res){
var res = $.trim(res);
alert(res);
});
});
$("#table tr").click(function(){
$("#DelEdtQuestion").addClass('selected1');
});
});
Modified ajaxfile.php to suit the above example:
<?php
$id = mysql_real_escape_string($_POST["id"]);
//query database to get results:
$result = "SELECT * FROM `users` WHERE `id` = '$id' LIMIT 1";
$row = mysql_fetch_assoc($result);
echo "Username: ".$row["username"]."Password: ".$row["password"]."Firstname: ".$row["firstname"]."Lastname: ".$row["lastname"].
?>
Since your question was rather ambigious, I put more effort to give you an idea about the basics of ajax so that you work out your own solution, rather than to suggest a potential solution -that at the end could not be what you were looking for...
And since we are talking about ajax basics, it is a good practice to secure your ajax files since they are accessible from any browser:
in the very beginning of any ajax file, right below the "?php" tag, you can add these lines below, to protect the file from being accessed by browser -but remain accessible to ajax calls:
//protect the file from un-authorized access
define('AJAX_REQUEST', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
if(!AJAX_REQUEST) {die();}
Hope that helps you and others. T.
UPDATE:
It is ALWAYS a good practice to keep your php and javascript files separately... In the above examples there are ideally 3 files involved: the main php file, the scripts file and the ajax-php file.
So -preferably after the "body" tag of your "main" php file- you should include the scripts-file (after the jquery ofcourse!). Like that:
<!-- jQuery v.1.11.3-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- include scripts file -->
<?php include("scripts.php"); ?>
(notice that for jquery I use the regular "script" tags but for the scripts file I just do a "php include").
As you see above, the javascript file has also ".php" extension (not ".js"). This is a "trick" I like to do because it gives me the ability to execute php code within the js file. Of course, all javascript code in that file is included between "script" tags.
example of a hypothetical "scripts.php":
<script>
// I create a js variable that takes value from php
var phpDate = '<?php date("Y-m-d"); ?>';
alert(phpDate);
//or pass the contents of another php variable in your app to javascript:
var myPhpVar = '<?php echo $my_php_var; ?>';
//or put a php SESSION to a js variable:
var mySess = '<?php echo $_SESSION["my_session"]; ?>';
</script>
The above comes quite handy sometimes when you want to pass to javascript php variables that already exist in your application.
It is a very long answer (more like a tutorial!)... But now should be quite clear to you how to pass values not only from js to php but also vice versa!!!

How do i make my php variable accessible?

I am trying to implement a timer. I learned this idea from a SO post.
<?php
if(($_SERVER['REQUEST_METHOD'] === 'POST') && !empty($_POST['username']))
{
//secondsDiff is declared here
$remainingDay = floor($secondsDiff/60/60/24);
}
?>
This is my php code. My php,html and JS codes are in the same page. I have a button in my html. When a user clicks on the html page, It will call a Ajax function
//url:"onlinetest.php",
//dataType: 'json',
beforeSend: function()
{
$(".startMyTest").off('click');
setCountDown();
}
It will call setCountDown() method, which contains a line at the very beginning
var days = <?php echo $remainingDay; ?>;
When i run the page, it says[even before clicking the button] "expected expression, got '<'" in the above line. My doubt is
Why this php variable get replaced before i am triggering the button. Please let me know hoe to solve this or how to change my idea.
The problem is, since initial load, $_POST values aren't populated (empty on first load),
That variable you set is undefined, just make sure you initialize that variable fist.
<?php
// initialize
$remainingDay = 1;
if(($_SERVER['REQUEST_METHOD'] === 'POST') && !empty($_POST['username']))
{
//secondsDiff is declared here
$remainingDay = floor($secondsDiff/60/60/24);
echo json_encode(array('remaining_day' => $remainingDay);
exit;
}
?>
<script>
var days = <?php echo $remainingDay; ?>;
$('.your_button').on('click', function(){
$.ajax({
url: 'something.php',
dataType: 'JSON',
type: 'POST',
beforeSend: function() {
// whatever processes you need
},
success: function(response) {
alert(response.remaining_day);
}
});
});
</script>
That is just the basic idea, I just added other codes for that particular example, just add/change the rest of your logic thats needed on your side.
You can pass a php variable into JS code like
var jsvariable ="<?php echo $phpvariable ?>";
NOTE:
If you ever wanted to pass a php's json_encoded value to JS, you can do
var jsonVariable = <?php echo $json_encoded_value ?>; //Note that there is no need for quotes here
Try this,
var days = "<?php echo $remainingDay; ?>";

accordion won't work with new content loaded

I have tried to get this to work for a while now.
When I load new Ajax content into my accordion, then the new content won't work. The preloaded content works just fine, both before and after.
I have added my code here
I know you can't run the script with ajax, since my config and mysql runs local.
Here is my "update-data.php":
<?php
include('../../includes/config.inc.php');
if(isSet($_POST['content']))
{
$content=$_POST['content'];
$name=$_POST['name'];
$query = "INSERT INTO messages(msg,name) VALUES ('$content','$name')";
mysqli_query($sqlCon, $query);
//mysqli_query("insert into messages(msg) values ('$content')");
$sql_in= mysqli_query($sqlCon, "SELECT msg,msg_id,name FROM messages order by msg_id desc");
$r=mysqli_fetch_array($sql_in);
$msg=$r['msg'];
$name=$r['name'];
$msg_id=$r['msg_id'];
}
?>
<div class="accordionButton"><?php echo $msg_id; ?>:<?php echo $name; ?></div>
<div class="accordionContent" style="display: block;"><?php echo $msg; ?></div>
Thanks for your help
Here are the ajax call:
<script type="text/javascript">
$(function() {
$(".comment_button").click(function()
{
var element = $(this);
var boxval = $("#content").val();
var bval = $("#name").val();
var dataString = {content:boxval,name:bval};
if(boxval=='')
{
alert("Please Enter Some Text");
} else {
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="ajax.gif" align="absmiddle"> <span class="loading">Loading Update...</span>');
$.ajax({
type: "POST",
url: "<?php echo $total_path.'/update_data.php'; ?>",
data: dataString,
cache: false,
success: function(html){
$("div#wrapper_ac").prepend(html);
$("div#wrapper_ac .accordionButton:first").slideDown("slow");
document.getElementById('content').value='';
document.getElementById('name').value='';
$("#flash").hide();
}
});
}
return false;
});
</script>
You php is fine, just clean your inputs please and look into PDO
You can read about cleaning inputs here and PDO here
In your js I think your problem is your on statement
$('.accordionButton').on('click', function() {
// DO stuff
});
I think it's just not bubbling up the DOM far enough to capture new data, it's adding he click event onto all accordion buttons and listening for them.
Change it to this
$('#wrapper_ac').on('click', '.accordionButton', function() {
// DO stuff
});
This places the listener on #wrapper_ac so any click events that happen underneath will be caught.
Hope this helps
Edit: For more info on PDO check this site http://www.phptherightway.com/#databases

Categories