I have seen many other posts like this, but I cannot see anything I have done wrong. I also read it could be a problem with the hosting (Heroku) so I have created a ticket, but no answer after 3 days.
Below is the code which sends the info:
(discuss.php)
<script type="text/javascript">
$(function() {
$('#ideasubmit').click(function() {
console.log();
$('#ideacontainer').append('<img src="images/loading.gif" alt="Please Wait" id="idealoading" />');
var ideatitle = $('#ideatitle').val();
var ideafbid = $('#ideafbid').val();
var idea = $('#idea').val();
$.ajax({
url: 'ajaxsqli.php',
type: 'POST',
data: 'ideatitle=' + ideatitle + '&ideafbid=' + ideafbid + '&idea=' + idea,
success: function(result) {
$('#idearesponse').remove();
$('#ideacontainer').append('<p id="idearesponse">' + result + '</p>');
$('#idealoading').fadeOut(500, function() {
$(this).remove();
});
}
});
return false;
});
});
Below here is the code file which gets the error when it sent the info:
(ajaxsqli.php)
$db = new db;
$query = "INSERT into comments(user_fbid, discuss_type, discuss_post_title, discuss_post, date) VALUES (?, ?, ?, ?, )";
$stmt = $db->stmt_init();
if($stmt->prepare($query)) {
$stmt->bind_param('iissi', $_POST['ideafbid'], 1, $_POST['ideatitle'], $_POST['idea'], date('Ymd'));
$stmt->execute();
}
if($stmt) {
echo "Thank you. We'll be in touch with you shortly!";
} else {
echo "There was a problem. Please try again later.";
}
?>
Whats odd is I had it working 3 days ago, and I went to improve some of the code and now I am unable to make it work, even if I restore the back up.
This is the full error message:
Failed to load resource: the server responded with a status of 500 (Internal Server Error) and points to ajaxsqli.php
Using Chrome Inspect Elements I can see the POST is posting the information, but no response information.
Is there anything wrong with this code ?
A 500 error usually refers to a problem in the php. Load ajaxsqli.php in the browser with the paramaters (change $_POST to $_REQUEST and then you can use the querystring. EG
$db = new db;
$query = "INSERT into comments(user_fbid, discuss_type, discuss_post_title, discuss_post, date) VALUES (?, ?, ?, ?, )";
$stmt = $db->stmt_init();
if($stmt->prepare($query)) {
$stmt->bind_param('iissi', $_REQUEST['ideafbid'], 1, $_REQUEST['ideatitle'], $_REQUEST['idea'], date('Ymd'));
$stmt->execute();
}
if($stmt) {
echo "Thank you. We'll be in touch with you shortly!";
} else {
echo "There was a problem. Please try again later.";
}
?>
Then go to http://yourhost/ajaxsqli.php?ideafbid=data&ideatitle=data&idea=data and see what the PHP error is
Related
I have a react app that makes a post request to the following code.
<?php
require_once('dbSURL.php');
$stm = $db->prepare("INSERT INTO urlshortener (longUrl, shortId, userIp, userCountry, userCity, userOS, userAgent, createDate) VALUES (:longUrl, :shortId, :userIp, :userCountry, :userCity, :userOS, :userAgent, :createDate)");
$stm->bindParam(':longUrl', $_POST['longUrl']);
$stm->bindParam(':shortId', $_POST['shortId']);
$stm->bindParam(':userIp', $_POST['userIp']);
$stm->bindParam(':userCountry', $_POST['userCountry']);
$stm->bindParam(':userCity', $_POST['userCity']);
$stm->bindParam(':userOS', $_POST['userOS']);
$stm->bindParam(':userAgent', $_POST['userAgent']);
$stm->bindParam(':createDate', $_POST['createDate']);
if ($stm->execute()) {
echo "success";
} else {
echo "failure: ".$stm->errorInfo()[2];
};
// $stm->execute();
// echo 'Error: %s.\n', $stm->errorCode(), $stm->errorInfo();
?>
After checking the request from dev tools I can see that the data are sent but when I get the data from the database all the fields are null.
Any help?
Here is my ajax code.
I cannot see any error in my code, but AJAX doesn't work.
It doesn't return anything from that page...
function addCash(){
var cash =$('#cash_amount').val();
var date =$('#cash_date').val();
var debiter =$('#debiter').val();
if(cash == '' || date =='' ){
alert("Please Fill All Fields");
}
else{
$.ajax({
type: 'POST',
dataType:'JSON',
url: 'getCustomers.php',
data: 'type=cash_received&cash='+cash+'&date='+date+'& debiter='+debiter,
success:function(data){
console.log(data);
alert("Cash Added Successfully");
}
});
}
}
PHP Code "getCustomers.php"...inside a function using ajax is an issue?
$cash= $_REQUEST['cash'];
$date= $_REQUEST['date'];
$debiter= $_REQUEST['debiter'];
$query="INSERT INTO `received_payment`(`debiter`, `amount`, `date`) VALUES ('".$debiter."', '".$cash."', '".$date."')";
$result = $mysqli->query($query) or ($error=$mysqli->error.LINE);
$arr = array();
if(!$result){
$arr['result'] = isset($error) ? $error : 'error';
}
else{
$arr['result'] ="ok";
}
$json_response = json_encode($arr);
ob_clean();
echo $json_response;`
Because, you are using die anf if your query fails then your script will die and hence no response will be made. So change the below line,
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
to
$result = $mysqli->query($query) or ($error=$mysqli->error.__LINE__);
and you can return this error in response like,
if(!$result){
$arr['result'] = isset($error) ? $error : 'error';
}
Also in your insert query, fields and their values are not matching, you should use it like,
$query="INSERT INTO `received_payment` (`debiter`, `amount`, `date`)
VALUES ('".$debiter."', ".$cash."', '".$date."')";
And try to pass data from AJAX (you have space before debiter key in your data string) like,
data: {type:'cash_received',cash:cash,date:date,debiter:debiter},
An extra comma in INSERT query.
$query="INSERT INTO `received_payment`(`debiter`, `amount`, `date`,) VALUES ('".$cash."', '".$date."', '".$debiter."')";
Change to:
$query="INSERT INTO `received_payment`(`debiter`, `amount`, `date`) VALUES ('".$cash."', '".$date."', '".$debiter."')";
It is giving an error actually, but since you gave die() the code is getting exited. So you are not getting anything from Server.
in AJAX request you have mentioned accept only JSON data content. So in some case it may happens server returns response with Warning and Error if PHP error is on.
So in server side PHP script before echo response in json format you can use ob_clean() for flushing all unexpected output which is sent by error or warning.
$json_response = json_encode($arr);
ob_clean();
echo $json_response;
Please remove quotes at the end of the line
echo $json_response;`
<script type="text/javascript">
function signup() {
var url = "process/sign-up-process.php?" + $("#signup-form").serialize();
// alert(url);
$.get(url, function (data, status) {
alert(data);
});
}
</script>
Page: process/sign-up-process.php code goes below
<?php
require_once('connection.php');
$full_name = filter_input(INPUT_GET, 'full_name', FILTER_SANITIZE_STRING);
$email = $_GET['email'];
$email = filter_var($email, FILTER_VALIDATE_EMAIL);
$user_password = filter_input(INPUT_GET, 'user_password', FILTER_SANITIZE_STRING);
$query = "INSERT INTO registered_users_list (full_name, email, user_password) VALUES ('$full_name', '$email', '$user_password')";
$query1 = mysqli_query($conn, $query);
$count = mysqli_affected_rows($conn);
if($count == 1){
echo "Signed up";
}else{
echo "Sorry";
}
?>
The problem is in "process/sign-up-process.php" page, when I comment out the query code and
echo "Some Random Text"
then the
alert(data)
works. But when I tried to run INSERT query it doesn't work. I think the error must be in PHP improved i.e mysqli string.
I can bet $10 that the page you are requesting returns an error instead of text. In chrome, before sending the AJAX request press F12 and go to Network tab. Click on the () Clear sign to clear all entries if needed. Then when the ajax call proceeds check out the response. It's most probably a mysqli error page (Chrome dev console screenshot: http://image.prntscr.com/image/84e59bfb9caf4c9b9dcf8b5f79844176.png )
Probably even better: Request Monitoring in Chrome
A great tutorial if you don't know what I am talking about: https://www.youtube.com/watch?v=AXGB4tIRNgM
I have sendlike.php that handled liking, and works so far!
<?php
//include db configuration file
include_once("config.php");
//Include functions
include_once("functions.php");
// http://stackoverflow.com/questions/21065502/ajax-a-href-onclick-get-php-variable-and-execute-php-file
// For practice
$uid_fk = 1;
//check $_POST["content_txt"] is not empty
if(isset($_GET["like"]) && strlen($_GET["like"])>0)
{
//Add IP, date. Set the Foreign key
$ip = $_SERVER['REMOTE_ADDR'];
$date = date("Y-m-d H:i:s");
$comment_id_fk = $_GET["like"]; // '".$comment_id_fk."', What comment has been liked?
// $_SESSION["user_id"] '".$uid_fk."', What user has liked it? Get the users uid
// Insert sanitize string in record
$insert_row = $mysqli->query("INSERT INTO comment_likes (comment_id_fk, uid_fk,date,ip)
VALUES('".$comment_id_fk."','".$uid_fk."','".$date."','".$ip."')");
if($insert_row)
{
//Count the amount of likes again
$count_likes=$mysqli->query("SELECT COUNT(*) as TOTAL_COMMENT_LIKES FROM `comment_likes`
WHERE comment_id_fk='".$comment_id_fk."'");
$row_array=$count_likes->fetch_array(MYSQLI_ASSOC);
//Record was successfully inserted, respond result back to index page
// This should probably in the fute go thruh functions.php comment_func_bar
$my_id = $mysqli->insert_id; //Get ID of last inserted row from MySQL. Will this cause problems when alot of ppl liking / posting / commenting etc??
echo '' . $row_array['TOTAL_COMMENT_LIKES'] .' Unlike';
$mysqli->close(); //close db connection
}else{
//header('HTTP/1.1 500 '.mysql_error()); //display sql errors.. must not output sql errors in live mode.
header('HTTP/1.1 500 Looks like mysql error, could not insert record!');
exit();
}
}
elseif(isset($_GET["delike"]) && strlen($_GET["delike"])>0 && is_numeric($_GET["delike"]))
{ //do we have a delete request? $_POST["recordToDelete"]
//sanitize post value, PHP filter FILTER_SANITIZE_NUMBER_INT removes all characters except digits, plus and minus sign.
$idToDelete = filter_var($_GET["delike"],FILTER_SANITIZE_NUMBER_INT);
//try deleting record using the record ID we received from POST
$delete_row = $mysqli->query("DELETE FROM comment_likes WHERE comment_id_fk='".$idToDelete."' AND uid_fk ='".$uid_fk."'"); //uid_fk is $_SESSION[user_id] actually
if(!$delete_row)
{
//If mysql delete query was unsuccessful, output error
header('HTTP/1.1 500 Could not delete record!');
exit();
}
$mysqli->close(); //close db connection
}
else
{
//Output error
header('HTTP/1.1 500 Error occurred, Could not process request!');
exit();
}
?>
If you have a look at the echoing line, the class of the href is class="clickable". and sandlike.php has changed to delike.
I'am not able to do a AJAX script that will send the and update the "clickable" href to <a href="sendlike.php?delike='.$comment_id_fk.'" class="clickable">' . $row_array['TOTAL_COMMENT_LIKES'] .' Unlike'
This is asfar i have come
<script type="text/javascript">
$('.clickable').on('click', function() {
var data = {
mode: "like",
rating: $(this).data('rating'),
id: $(this).data('id')
};
$.ajax({
type: 'GET',
url: 'sendlike.php',
data: data,
success: function(response) {
console.log(response);
}
});
});
</script>
And is not even close to work.
And how about the class="clickable", i have multipel comments on page. Will all get liked/deliked. Or do i need something like class="item_$number_clickable" ?
Thanks in advance!
Add event.preventDefault() and delegate the event to the static parent:
$(document).on('click', '.clickable', function(e) {
e.preventDefault(); // to stop the page navigation
So I decided to start using prototype and here's my first question. I'm trying to send out an ajax request to a php page which updates s single record. When I do this by hand (ie: typing the address + parameters it works fine but when I use this code from javascript:
var pars = 'trackname=' + track + '&tracktime=' + time;
new Ajax.Request('php/setSongTime.php', {
method: 'get',
parameters: pars,
onSuccess: function(transport){
var response = transport.responseText || "no response text";
alert("Success! \n\n" + response);
},
onFailure: function(){ alert('Something went wrong...') }
The onSuccess fires and displays the correct information from php, but the update is not made. What the php returns is the UPDATE string, so I'm checking the parameters and they look fine. Does anyone see a problem? Thanks...
Total javascript:
/*This file handles all the user-based computations*/
//variable declarations to be used throughout the session
var untimedSongArray = [];
function beginProcess(){
new Ajax.Request('php/getUntimed.php', {
method: 'get',
onSuccess: function(transport){
var response = transport.responseText || "no response text";
untimedSongArray = response.split("+");
alert(response);
getFlashMovie("trackTimer").timeThisTrack(untimedSongArray[0]);
//alert("Success! \n\n" + response);
//var html = response;
},
onFailure: function(){ alert('Something went wrong...') }
});
}
function getFlashMovie(movieName) {
var isIE = navigator.appName.indexOf("Microsoft") != -1;
return (isIE) ? window[movieName] : document[movieName]; }
function setSongTime(track, time){
alert("track " + track + " has a time of " + time);
//$.get("php/setSongTime.php", { trackname: track, tracktime: time } );
var pars = 'trackname=' + track + '&tracktime=' + time;
new Ajax.Request('php/setSongTime.php', {
method: 'get',
parameters: pars,
onSuccess: function(transport){
var response = transport.responseText || "no response text";
alert("Success! \n\n" + response);
},
onFailure: function(){ alert('Something went wrong...') }
});
}
Total php code:
<?php
//turn on error reporting
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
//header('Content-Type: text/xml');
/////////////Main script
//pull variables
//need to do some error checking here
$trackname = ($_GET['trackname']);
$tracktime = ($_GET['tracktime']);
//remove leading track information
$trackname = str_replace('../music_directory/moe/moe2009-07-18/', '', $trackname);
$trackname = str_replace('.mp3', '', $trackname);
//echo $trackname;
//connect with database
$con = mysql_connect("localhost","root","");
if(!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("musicneverstopped", $con);
//end connecting to database
//////////////////////////////////////////
//update given song time
$sql = "UPDATE songs SET length = ".$tracktime." WHERE unique_song_id = ".$trackname;
echo $sql;
mysql_query("UPDATE songs SET length = '$tracktime' WHERE unique_song_id = '$trackname'");
//error check
//if(!$attempt){
//die(mysql_error());
//}
//////////////////////////////////////////
//close database connection
mysql_close($con);//close mysql connection
?>
Anyone see any failing errors?
Try echoing the exact same SQL you actually run in mysql_query (store it in $sql then pass that into the query, instead of writing out the query twice).
Then try running the query that gets echoed out in the response directly in the mysql command line on your server and see what happens.
Also, just to echo Max on the importance of escaping your SQL queries, I would add to the input sanitisation that you should use bind variables in your query, rather than just concatenating your user input with the rest of the SQL.
Something like this would ensure your variables are suitably escaped to avoid an SQL injection attack.
$sql = "UPDATE songs SET length = '%s' WHERE unique_song_id = '%s'";
$query = sprintf(
$sql,
mysql_real_escape_string($tracktime),
mysql_real_escape_string($trackname)
);
mysql_query($query);
Found it! Somehow I was getting an extra space before the finalized $trackname. ltrim fixed it right up. Thanks to everyone and thanks to those that mentioned security features. I'll definitely implement those. Dan