jQuery $.get() not running php script - javascript

I'm unable to run my php script at the click of the button.
If I run the script via the terminal, 'php get_funny_status.php' it returns the correct output. However, I'm not able to do this via AJAX. The beginning ajax alert shows up, but I'm not getting any responseText.
Am I missing something?
EDIT: I am testing this application view Preview Browser in Adobe Dreamweaver (I'm not sure if this has anything to do with the issue)
<script>
$( document ).ready(function() {
$( ".nextStatus" ).click(function() {
alert('beginning ajax');
var statusNumber = '5';
$.get('get_funny_status.php?' + statusNumber, function(responseText) {
alert(responseText);
});
});
});
</script>
Here's my php script:
<?php
//initialize DB stuff
$status_text_query = "SELECT * FROM funny_status WHERE STATUS_NUM = '". $_GET['statusNumber']."'";
$result = mysql_query($status_text_query);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo 'num likes: ' . $row['NUM_LIKES'];
echo 'num dislikes: ' . $row['NUM_DISLIKES'];
echo 'status text: ' . $row['STATUS_TEXT'];
echo 'status num: ' . $row['STATUS_NUM'];
}
?>

Fix this from:
$.get('get_funny_status.php?statusNumber', function(responseText) {
alert(responseText);
});
to
$.get('get_funny_status.php?statusNumber='+statusNumber, function(responseText) {
alert(responseText);
});

There are a few issues that I see:
In your PHP, _GET should be $_GET.
$status_text_query = "SELECT * FROM funny_status WHERE STATUS_NUM = '"
. $_GET['statusNumber']."'";
In your AJAX call, you need to send your parameter ?statusNumber=' + statusNumber, ...
$.get('get_funny_status.php?statusNumber=' + statusNumber,
function(responseText) {
Not necessarily a syntax error: I noticed that you're using mysql_* to access the database. This is a bad idea; I'd advise switching to either the mysqli_* functions or to the PDO class. Related to this issue, if I were to set statusNumber to something like "'; DELETE FROM funny_status;--", I would be able to delete all of the data in that table. This is called SQL Injection, and it is a serious security issue.

Related

Update MYSQL Table On Div Click using Ajax - No Page Refresh?

I have a MYSQL Table called users.
I also have a column called online_status.
On my page I want a user to be able to toggle their status as 'Online' or 'Offline' and have this updated in the database when they click on the div using Ajax, without refreshing the page.
Here's my PHP/HTML code:
<?php if ($profile['online_status'] == "Online") {
$status = "Offline";
}else{
$status = "Online";
} ?>
<div id="one"><li class="far fa-circle" onClick="UpdateRecord(<? echo $profile['online_status']; ?>);"/></li><? echo 'Show as ' .$status; ?></div>
My Ajax:
<script type="text/javascript" src="/js/jquery.js"></script>
<script>
function UpdateRecord(id)
{
jQuery.ajax({
type: "POST",
url: "update_status.php",
data: 'id='+id,
cache: false,
success: function(response)
{
alert("Record successfully updated");
}
});
}
</script>
update_status.php
<?php
$var = #$_POST['id'] ;
$sql = "UPDATE users SET online_status = 'Offline' WHERE user_id = 1";
$result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
//added for testing
echo 'var = '.$var;
?>
I am currently getting no alert, nothing is being updated in my database either. Please can someone help me improve/fix the code to get it to work? Also, if there's a way of eradicating the need for the update_status.php file and have the ajax self post then this would be preferred.
Thank you in advance.
From what i see, the reason why no alert pops up nor nothing gets updated is because of the onclick() on button you have. Add quotes around the parameter to the update function. As you have it, javascript sees the parameter as a javascript variable as $profile['online_status']; is a string.
If you had debugged your code, you should see an error pointing towards the onclick() line
Change this
onClick="UpdateRecord(<? echo $profile['online_status']; ?>);"
To
onClick="UpdateRecord('<? echo $profile['online_status']; ?>');"
Also you are hardcoding the where clause in your update statement. You should be using the $_POST['id'] variable via prepared statements
pass data to PHP file
data: { id: id },
add a database connection to your PHP file
<?php
$var = $_POST['id'] ;
$sql = "UPDATE users SET online_status = 'Offline' WHERE user_id = '$var'";
$result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
?>
If you still see any errors then press F12 and go to network tab, then click on that div, network tab will record your ajax file returns, you can check there on by selecting your php file's response, hope it helps

Ajax call to alter MySQL SELECT query

I'm working on a web app to keep track of recent expenses. I'd like the user to be able to select 4 different time periods which displays different data. When a user first lands on the page, the "overall" data would show by default. When a range is selected by the user, i'd like to use an ajax call to take the data-range and alter the mysql query. My experience with ajax is low, and i'm curious as to how this would be done.
Here is my HTML (echoed in PHP):
echo "<section class='range-container'>" .
"<ul class='overview-range'>" .
"<li data-range='overall'>Overall</li>" .
"<li data-range='$currentYear'>Year</li>" .
"<li data-range='$currentMonth'>Month</li>" .
"<li data-range='$currentDay'>Day</li>" .
"</ul>" .
"</section>";
include $_SERVER['DOCUMENT_ROOT'] . '/ajax/overview.php';
The overview.php file: For this example I only have the DAY(date) option in the query.
<?php
if ($_POST['range']) {
$currentTime = $_POST['range'];
} else {
$currentTime = '0';
}
//Overview Query
$sqloverview = $db->prepare('SELECT SUM(amount), trans_type
FROM transactions
WHERE (amount > 0 AND DAY(date) = :currentTime) OR
amount > 0
GROUP BY trans_type
ORDER BY trans_type DESC');
$sqloverview->execute(array(':currentTime' => sanitizeString($currentTime)));
$overviewRows = $sqloverview->num_rows;
?>
And the jQuery file:
$('.overview-range li').click(function() {
var range = $(this).attr('data-range');
$.ajax({
type: 'POST',
url: '/ajax/overview.php',
data: { range: range },
error: function() { alert("Unable to process this request."); },
success: function() {
alert('It was successful');
}
});
});
Would this be the correct way to go about this process? Or is there a better way other than ajax? Any help would be greatly appreciated!

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!!!

if(condition fails in jascript)

I have following code which is working in localhost in windows. But in the server same code fails.
It's the if condition which is not getting executed write even if data==found; I checked the returned data value which is found but cant figure out why the code is not executing properly
function checkAvailability() {
$("#loaderIcon").show();
jQuery.ajax({
url: "ajaxcheck.php",
data:'tran_id='+$("#tran_id").val(),
type: "POST",
success:function(data){
console.log(data);
//var x=data;
$("#loaderIcon").hide();
//console.log((data=="found"));
if(data=="found")
{
$("#singlebutton").prop('disabled', false);
console.log("fail");
$("#tran_id-status").html("Found");
}
else
{
console.log(data);
$("#singlebutton").prop('disabled', true);
$("#tran_id-status").html("");
console.log("ss");
}
},
error:function (){}
});
}
Here is ajaxcheck.php
<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
$space=" ";
if(!empty($_POST["tran_id"])) {
$result = mysql_query("SELECT count(*) FROM bank WHERE tran_id ='" . $space.$_POST["tran_id"] . "'");
$row = mysql_fetch_row($result);
$user_count = $row[0];
if($user_count>0) {
// echo "<span class='status-not-available' id=\"stat\"name=\"stat\" value=\"ok\"> Transaction Details Found.</span>";
echo"found";
}else{
//echo "<span class='status-available' id = \"stat\" name =\"stat\"value=\"not\"> (Enter Valid transaction id to submit)</span>";
echo"notfound";
}
}
?>
The issue is that your data variable is coming back with a new line character. There are two solutions to this 1. trim the returned value. 2. figure out why the php is serving a new line.
Solution 1:
if(data.trim()=="found")
This uses the JS trim function, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim.
Solution 2:
Try removing the ?> from the end of your PHP file (the PHP file will still be valid). This way if there are extra lines after it they won't be served as output and the JS wont receive them.
From the manual:
If a file is pure PHP code, it is preferable to omit the PHP closing tag at the end of the file. This prevents accidental whitespace or new lines being added after the PHP closing tag, which may cause unwanted effects because PHP will start output buffering when there is no intention from the programmer to send any output at that point in the script.

To pass argument from a php file to javascript file

I am facing some trouble in passing a simple variable from a php to javascript file.
I have a form which submits through a php file which basically updates the record at the server end. And if the updation is succesful, I just want to pass the message back to the javascript where I can update it on a certain section of the page.
My codes are:
Javascript code - abc.js
function expand_cards(project, SlNo)
{
name = project['project_name'];
j = "ShowForm-"+SlNo+"";
s = "<div class='edit_project_card'>";
s += "<form method='post' action='Edit_Project.php'><div class='project_form'>
// Form Contents
s += "<div class='Form_button'> <input type='submit'> </div>";
s += "</form></div>";
$("#"+j+"").html(s);
response = $.parseJSON(data);
$("#"+j+"").html(response);
}
PHP file - Edit_Project.php
<?php
//The updation stuff at the server end
if (!mysqli_query($connection,$sqlquery)) {
$response = "'Error in your code: ' . mysqli_error($connection)";
}
else {
$response = "1 record updated";
}
echo json_encode($response);
mysqli_close($connection);
?>
But the problem is the screen is printing $response variable as it is and not exactly passing it back to the javascript function as wished. I know I can use a $.post function which can can receive argument but it's a long form and passing parameters would be difficult in that.
Can anybody help me out here ?
Thanks
Dirty, but it will work:
<script type="text/javascript">
var my_var = <?php echo $some_variable; ?>
// Do something with the new my_var
some_func(my_var);
</script>
I wouldn't do too much detailed stuff with this though, if you can use AJAX that is better.
Note, this can only work on a .php file or one being read as such.
you'll want to do some variable handling in your php side because if the string is empty you'll end up with a
var my_var = ;
which will break the script. so something like:
var my_var = <?php echo "'" . $some_variable . "'";?>
if it's a string or if it's a number:
var my_var = <?php echo (empty($some_variable) ? null : $some_variable);
This is int specific, I'm sure you can come up with a function that will handle it better.
References:
empty function http://php.net/manual/en/function.empty.php
shorthand if http://davidwalsh.name/php-ternary-examples
Since you're submitting the form to the PHP file directly the browser loads the Edit_Project.php file as it would a normal page. If you want a json response to the already loaded page you'll have to use $.post or $.ajax
You can post the whole form simply by using serialize() like this:
$('#form_id').on('submit', function(e) {
// Stop the browser from posting the form
e.preventDefault();
// Post the form via Ajax
$.ajax({
url : 'Edit_Project.php',
type : 'POST',
data : $(this).serialize(),
success : function(response) {
// Here you do the HTML update
$("#"+j+"").html(response.reply);
}
});
});
The Edit_Project.php needs to be changed as well:
//The updation stuff at the server end
if (!mysqli_query($connection,$sqlquery)) {
$response = "'Error in your code: ' . mysqli_error($connection)";
}
else {
$response = "1 record updated";
}
mysqli_close($connection);
/*
* As SuperDJ suggested, you need to tell the browser that it's
* receiving a JSON ojbect although he did use the wrong content type:
*/
header('Content-Type: application/json');
/*
* According to php.net most decoders should handle a simple string as
* json object but to be safe always encode an array or an object since
* you can't know how the decoder will respond.
*/
echo json_encode(array('reply' => $response));

Categories