Ajax Post 500 server error - php

I am trying to write some data to a MySQL Table however the .post call is returning with a 500 server error. Any help in the right direction would be great.
I think it's something to do with the _POST variables not sending right.
Here is the code:
JS:
function write_table(response) {
var data = {
'user_id' : response.id,
'user_email' : response.email,
'user_first' : response.first_name,
'user_last' : response.last_name
};
console.log(data);
$.ajax({
'url': './includes/php/login_facebook.php',
'data': data,
'type': 'POST',
'beforeSend': function(xhr, settings) {
console.log('ABOUT TO SEND');
},
'success': function(result, status_code, xhr) {
console.log('SUCCESS!');
},
'complete': function(xhr, text_status) {
console.log('Done.');
},
'error': function(xhr, text_status, error_thrown) {
console.log('ERROR!', text_status, error_thrown);
}
});
}
PHP:
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
$host = 'localhost';
$un = 'root';
$pw = 'root';
$db = 'bikelouis';
$user_id = $_POST['user_id'];
$user_email = $_POST['user_email'];
$user_first = $_POST['user_first'];
$user_last = $_POST['user_last'];
$conn = mysql_connect($host, $un, $pw) or die(mysql_error());
if ($conn) {
echo '<script> alert("connected!");</script>';
mysql_select_db($db) or die(mysql_error());
$sql = "INSERT INTO users (user_id, user_email, user_first, user_last) VALUES ($user_id, $user_email, $user_first, $user_last)";
} else {
echo 'Connection failed.';
}
?>
I am using facebook connect, that is where 'response' is coming from. That works perfectly.

jQuery Side
$.post() is simply a wrapper for $.ajax() so if you want a little more control and visibility into what's going on, I'd highly suggest using $.ajax() instead.
The data argument for $.post() should be an object of key/value pairs and not a list. That said, I'm not sure what throwing the data object into the user_info list accomplishes, and this may be the root of your problem.
Try this and let me know how it works out for you:
function write_table(response) {
var data = { // This is the format $.post() expects.
'user_email' : response.email,
'user_id' : response.id,
'user_first' : response.first_name,
'user_last' : response.last_name
};
console.log(data);
$.post('./includes/php/login_facebook.php', data, function(result, status, xhr) {
console.log(status, result);
});
}
The same request, performed through $.ajax():
function write_table(response) {
var data = {
'user_email' : response.email,
'user_id' : response.id,
'user_first' : response.first_name,
'user_last' : response.last_name
};
$.ajax({
'url': './includes/php/login_facebook.php',
'data': data,
'type': 'POST',
'beforeSend': function(xhr, settings) {
console.log('ABOUT TO SEND');
},
'success': function(result, status_code, xhr) {
console.log('SUCCESS!',
},
'complete': function(xhr, text_status) {
console.log('Done.');
},
'error': function(xhr, text_status, error_thrown) {
console.log('ERROR!', text_status, error_thrown);
}
});
}
PHP Side
First off, I'd highly recommend opening PHP with <?php rather than <?, as the later is not enabled on all set ups.
Secondly, instead of receiving an Internal Server Error, actually displaying the errors in the browser is so much cleaner. At the beginning of any PHP script you wish to display potential errors on, include the following:
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
As for the 500 Internal Server Error you're receiving, it's most likely because you're missing a $ in front of $_POST on line 8.
Instead of:
$user_id = _POST['user_id'];
It should read:
$user_id = $_POST['user_id'];
Inserting
All variables should be encapsulated in ticks / apostrophes.
It's also a great idea to escape the values, to prevent SQL injection attacks:
Try this:
$sql = "
INSERT INTO users
(user_id, user_email, user_first, user_last) VALUES (
'" . mysql_real_escape_string($user_id) . "',
'" . mysql_real_escape_string($user_email) . "',
'" . mysql_real_escape_string($user_first) . "',
'" . mysql_real_escape_string($user_last) . "'
)
";

Related

ajax jquery , query not getting called

Made something simple like a follow system using ajax jquery on my own, thats the function:
function follow(name){
jQuery.ajax({
type: "POST",
url: "../include/follow.inc.php",
data: "name",
cache: false,
});
}
and that is the button which calls that function
<button onClick="follow('.$nome.');"></button>
This is how i call the button.
$my_name = $_SESSION['account_name'];
$user = $_POST['name'];
if (isset($_POST['name'])){
$query = "INSERT INTO followed (follower, followed) VALUES ('$my_name', '$user')";
$result = $database->query($query);
}
At the end of the day, it all looks alright until the query is not getting called.
basically what it does is, gets the name (of the user you wish to follow) , it adds the name in follow(name) and proceeds adding it in a query (this is where it fails).
your codes has two problem
1 - you create your variable $name before checking that the name exists or not and in debugging mode you see the notice of php
2 - your codes is open to XSS or SQL Injection Attacks as riggsfolly said in comments
and for your problem: try this and let us known the result
php file:
if(isset($_POST['name'])){
$my_name = $_SESSION['account_name'];
$user = $_POST['name'];
$result = $database->query("INSERT INTO followed (follower, followed) VALUES ('" . $my_name . "', '" . $user . "')");
if($result){
echo('ok');
}else{
echo('error');
}
}
function:
function follow(n){
jQuery.ajax({
type: 'POST',
url: '../include/follow.inc.php',
data: { name: n },
cache: false,
success: function(response){
alert(response);
},
error: function(error){
alert('Error in AJAX request !');
}
});
}
dont forget to use a xss cleaning function for getting your data from clients in methods
$user = your_any_xss_clean_function($_POST['name']);

AJAX jQuery & PHP issue

What I'm looking is that when the button is clicked then the values are taken and put into variables. The variables are then used in the AJAX call, so I can post them.
function addTask(){
$("#add_task_button").click(function(){
var task_title = $('#add_task_title').val();
var task_description = $('#add_task_desc').val();
var task_member = $( "#task_member option:selected" ).text();
var task_status = $( "#task_status option:selected" ).text();
$.ajax({
url: '../php_scripts/add_task.php',
type: 'POST',
data: {'title': task_title, 'description': task_description, 'member': task_member, 'status': task_status},
success: function() {
alert("SUCCESS");
},
error: function(jqXHR,textStatus,errorThrown) {
alert("FAILURE");
}
});
});
}
This is the jQuery and AJAX call
<?php
require_once "cdbconnect.php";
$taskTitle = $_POST['title'];
$taskDescription = $_POST['description'];
$memberName = $_POST['member'];
$groupName = "test";
$status = $_POST['status'];
$query = "INSERT INTO task_tbl (Task_title, Task_description, Member_Name, Group_Name, Status) values('$taskTitle', '$taskDescription', '$memberName', '$groupName', '$status')";
$result = $conn -> query($query);
if(!$result)
{
$conn -> error;
}
mysqli_close($conn);
?>
This Is the PHP file. I always receive the failure alert as the data is not submitted to the table.
Am I missing something here?
A failing ajax request does not mean there is a logical error in your php script, but rather that the request could not be executed in the first place. Think "Server could not be reached", so your php code wasn't even executed.
Possible reasons are:
Network problems
Wrong url
In your case the url looks suspicious...

Ajax data function that should work but doesn't

Within my application I have an Ajax function that adds information to a database. Everything worked perfectly until I added in 2 more parameters which was location and username.
It still works with everything else but it doesn't add those last 2 into the database. The names of within the database is location and username. assignedUsername and storeLocation are set else where in the code.
Ajax:
$("#send").click(function(){
$.ajax({
type: 'POST',
contentType: "application/json",
data: orderFood(),
url: rootURL + "/orderFood",
dataType: "json",
success: function(data)
{
alert(assignedUsername);
alert("Data Added");
$.mobile.changePage("#mainMenu");
},
error: function(data)
{
alert(assignedUsername);
alert("Data NOT Added");
$.mobile.changePage("#mainMenu");
}
});
});
function orderFood()
{
alert(storeLocation + ", " + assignedUsername);
return JSON.stringify({
"food1": food1,
"food2": food2,
"food3": food3,
"food4": food4,
"food5": food5,
"food6": food6,
"food7": food7,
"food8": food8,
"food9": food9,
"location": storeLocation,
"username": assignedUsername
});
}
PHP:
$app->post('/orderFood/', 'orderFood');
function orderFood()
{
$request = \Slim\Slim::getInstance()->request();
$q = json_decode($request->getBody());
$sql = "INSERT INTO subsordered(food1, food2, food3, food4, food5, food6, food7, food8, food9, location, username) VALUES (:food1, :food2, :food3, :food4, :food5, :food6, :food7, :food8, :food9, :location, :username)";
try
{
$db = getConnection();
$stmt=$db->prepare($sql);
$stmt->bindParam("food1",$q->food1);
$stmt->bindParam("food2",$q->food2);
$stmt->bindParam("food3",$q->food3);
$stmt->bindParam("food4",$q->food4);
$stmt->bindParam("food5",$q->food5);
$stmt->bindParam("food6",$q->food6);
$stmt->bindParam("food7",$q->food7);
$stmt->bindParam("food8",$q->food8);
$stmt->bindParam("food9",$q->food9);
$stmt->bindParam("location",$q->location);
$stmt->bindParam("username",$q->username);
$stmt->execute();
$db = null;
}
catch(PDOException $e){
echo $e->getMessage();
}
}
I know the PHP is correct though testing with cURL but I thought I'd include it just to get the whole picture
I am extremely stuck with this, from what I can see it SHOULD work but it just doesn't

Phonegap, AJAX - PHP Array Issue

I am in trouble while pass user's input value via array from HTML (Using AJAX) To php page (In fetching Array) .
Is method I use is correct ? I didn't get value in my PHP page.
First I assign user's value to variable
var first_name = $("[name='first_name']").val();
var last_name = $("[name='last_name']").val();
Then Create Its array.
var MyArray = {"firstname": first_name, "lastname": last_name};
And Here How I pass value to external server's php file
$.ajax({
type: "POST",
url: GolbalURL+"updategeneralinformation.php",
data: "userarray="+ MyArray,
dataType:'json',
success: function(response){
if(response.success) {
navigator.notification.alert(
'Ok',
// No need for Callback function
'Ok',
'Ok'
)
}
else {
navigator.notification.alert(
'Something went wrong while attempting update',
// No need for Callback function
'Atempt Fail',
'Try Again'
)
}
},
error: function(error){
navigator.notification.alert(
error,
// No need for Callback function
'Something wrong',
'Try Again'
)
}
});
return false;
Now PHP File code for retrieve Requested array from HTML page and run PHP-MySQL Update Query
$get_array = $_REQUEST['userarray'];
$query = mysql_query("UPDATE ".$db.".users SET first_name='$get_array["firstname"]', last_name='$get_array["lastname"]' ");
mysql_query($query);
if (!mysql_query($query, $con)) {
//die('Error: ' . mysql_error());
$response['success'] = false;
} else {
$response['success'] = true;
}
Use
data: MyArray,
or
data: {firstname: first_name, lastname: last_name},
instead of
data: "userarray="+ MyArray,
at server side
$get_array = $_POST;
and
$query = mysql_query("UPDATE ".$db.".users SET first_name='" . $get_array["firstname"] . "', last_name='" . $get_array["lastname"] . "'");
Note: the mysql_query is deprecated, use pdo or mysqli, and its unsecure in this form (mysql_real_escape_string() missing)
You've convert your javascript array into a string when you do this:
data: "userarray="+ MyArray,
So basically, php just gets a string.
You may want to do this in your javascript:
var MyArray = {"firstname": first_name, "lastname": last_name};
data: MyArray,
Or
data: {"firstname": first_name, "lastname": last_name},
And in your php script:
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
var MyArray = {"firstname": first_name, "lastname": last_name};
data: MyArray,

LONG POLLING (in php) starts hanging after 5 requests to database

I'm developing live auction site, with real-time bidding system. I'm using LONG POLLING when user bids on item. I've chose long polling because WebSockets are not yet very supported and NODEJS is to complicated for me to implement right now. So I'm stuck with this simle ajax long polling, which works great for about five bids.
So the problem is: Bidding works great for 5-6 item bids in 1 second intervals (I get instant response from server-ajax), but the 7th (click) on bid button this response-long polling hangs for about 16-22 seconds and then completes the request. At the end everything is updated in database and completed but after every 5-6 bids response/ajax call hangss for about 16-22 seconds.
How could I reduce this time, that everything should go smoothly no matter how many times user bids, without lag...
I'm using Apache/PHP/MySql on localhost/wamp
My code:
index.php
<script type="text/javascript" charset="utf-8">
var old_timestamp = <?php echo $old_timestamp;?>; //here i'm echoing last timestamp of auction
function waitForMsg(){
jq.ajax({
type: "POST",
url: "http://localhost/bid/comet/poll.php",
data: {"old_timestamp" : old_timestamp},
async: true,
cache: false,
success: function(data){
var json = eval('(' + data + ')');
if(json['msg'] != "") {
jq('#comet_display').html(json['msg']); //here I show ID of which auction item was bidded
}
old_timestamp = json['old_timestamp'];
setTimeout('waitForMsg()',100);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
setTimeout('waitForMsg()',1000);
}
});
}
jq(window).load(function(){
waitForMsg();
jq("#a_loader").show();
var url = "http://localhost/bid/auctions-ajax"; // the script where you handle the form input.
jq.ajax({
type: "POST",
url: url,
data: {au978 : true},
async:false, //to sem dodal za Ĩasovni zamik
success: function(data)
{
jq("#a_loader").hide();
jq("#show-category").html(data); // show response from the php script.
},
error: function(result) {
jq("#show-category").html("Sorry, something went wrong. Please try again later.");
}
});
});
function bid(id){
var url = "http://localhost/bid/comet/update-auction.php"; // the script where you handle the form input.
var user_id=<?php echo $user_id;?>; //user id from session
jq.ajax({
type: "POST",
url: url,
data: {"auct_id" : id, "user_id" : user_id}, // serializes the form's elements.
success: function(data)
{
//it updates in user table its remaining number of bids
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert("Something went wrong. Click OK to refresh.");
}
});
}
</script>
poll.php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
require_once($_SERVER['DOCUMENT_ROOT'] . 'bid/include/DEFINES.php');
require_once(CLASS_AUCTION);
require_once(CLASS_DB);
$a=new Auction();
$old_timestamp = $_POST['old_timestamp'];
$bidded_id=0;
$db=DB::getInstance();
$sql="SELECT timestamp, id FROM auction ORDER BY timestamp DESC LIMIT 1"; //desno doda tabelo kategorija
$stmt=$db->db->prepare($sql) or die("Prepare Error");
$stmt->execute();
$result2=$stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($result2 as $rez){
$current_timestamp=$rez['timestamp'];
$bidded_id=$rez['id'];
}
$stmt->closeCursor();
while($current_timestamp <= $old_timestamp){
usleep(1000);
clearstatcache();
$db=DB::getInstance();
$sql="SELECT timestamp, id FROM auction ORDER BY timestamp DESC LIMIT 1";
$stmt=$db->db->prepare($sql) or die("Prepare Error");
$stmt->execute();
$result=$stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $rez){
$current_timestamp=$rez['timestamp'];
$bidded_id=$rez['id'];
}
$stmt->closeCursor();
}
$response = array();
$response['msg'] = 'BID na avkciji: '.$bidded_id;
$response['old_timestamp'] = $current_timestamp;
echo json_encode($response);
}else{
require_once($_SERVER['DOCUMENT_ROOT'] . 'bid/errors/404.html');
}
?>
and the update-auction.php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
require_once($_SERVER['DOCUMENT_ROOT'] . 'bid/include/DEFINES.php');
require_once(CLASS_AUCTION);
require_once(CLASS_USER);
require_once(CLASS_DB);
$u=new User();
$a=new Auction();
$auction_id=$_POST['auct_id'];
$user_id=$_POST['user_id'];
$date = new DateTime();
$timestamp=$date->getTimestamp();
$a->updateAuction($auction_id,$user_id,$timestamp/*,$bid_price,$bids_spent,$total_paid*/);
$u->updateUserBids($user_id);
}else{
require_once($_SERVER['DOCUMENT_ROOT'] . 'bid/errors/404.html');
}
?>
Thank you for viewing my problem!
Consider switching to WebSockets. It was designed to fix the long polling issue.
Ok, I have find a solution which fixes this 17-22 seconds LAG-HANGING problem. Now it's almost instant, regardless how many times you click. But I'm still not sure, if this is the best solution of long polling.
I'm posting it, if someone would have the same problem.
I've changed LONG POLLING function in my poll.php to this:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
require_once($_SERVER['DOCUMENT_ROOT'] . 'bid/include/DEFINES.php');
require_once(CLASS_AUCTION);
require_once(CLASS_DB);
$a=new Auction();
$db=DB::getInstance();
$sql="SELECT timestamp, id, last_username FROM auction ORDER BY timestamp DESC LIMIT 1";
$response = array();
while(1)
{
$stmt=$db->db->prepare($sql) or die("Prepare Error");
$stmt->execute();
$result=$stmt->fetch(PDO::FETCH_ASSOC);
if (!empty($result)){
$current_timestamp=$result['timestamp'];
$response['msg'] = 'New BID';
$response['old_timestamp'] = $current_timestamp;
echo json_encode($response);
break;
}
sleep(3000);
clearstatcache();
}
}else{
require_once($_SERVER['DOCUMENT_ROOT'] . 'bid/errors/404.html');
}
?>
and now i'm polling in my index.php like this:
<?php
$db=DB::getInstance();
$sql="SELECT timestamp FROM auction ORDER BY timestamp DESC LIMIT 1";
$stmt=$db->db->prepare($sql) or die("Prepare Error");
$stmt->execute();
$result2=$stmt->fetch(PDO::FETCH_ASSOC);
$old_id=0;
$last_timestamp=$result2['timestamp'];
?>
<script type="text/javascript" charset="utf-8">
var last_timestamp = <?php echo $last_timestamp;?>;
var old_timestamp=0;
function waitForMsg(){
jq.ajax({
type: "POST",
url: "http://localhost/bid/comet/poll.php",
async: true,
cache: false,
success: function(data){
var json = eval('(' + data + ')');
if(old_timestamp==0 || last_timestamp==old_timestamp){
}else{
if(json['msg'] != "") {
jq('#comet_display').html(json['msg']);
}
}
old_timestamp = json['old_timestamp'];
setTimeout('waitForMsg()',500);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
setTimeout('waitForMsg()',1000);
}
});
}
jq(window).load(function(){
waitForMsg();
});
function bid(id){
var url = "http://localhost/bid/comet/update-auction.php"; //here I update auction and user's bids
var user_id=<?php echo json_encode($user_id);?>;
var user_name=<?php echo json_encode($user_name); ?>;
jq.ajax({
type: "POST",
async: true,
cache: false,
url: url,
data: {"auct_id" : id, "user_id" : user_id, "username" : user_name}, // serializes the form's elements.
success: function(data)
{
setTimeout('waitForMsg()',100);
var cnt = parseInt(jq(".db_bids").text());
if (!isNaN(cnt))
{
cnt--;
jq(".db_bids").text(String(cnt));
}
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert("Something went wrong. Click OK to refresh.");
}
});
}
</script>
I'm still developing this on localhost & will see how this behaves on real server with 100+ users.
If anyone have better and faster solution with LONG POLLING from databases, please let me know :)

Categories