Ajax to update on database not work - ajax

I have a code that is supposed to receive from other apps an ajax call with points variable to update this variable on Database, but something is wrong.
This Is My Code:
The variable should work in points.
I have insert it on the query but it seems there is something wrong because it's not updated the database.
<?php
header('Access-Control-Allow-Origin: *');
session_start();
include_once 'dbconnect.php';
if(!isset($_SESSION['user']))
{
header("Location: index.php");
}
if(isset($_GET['points'])){
//Lightly sanitize the GET's to prevent SQL injections and possible XSS attacks
$points = strip_tags(mysql_real_escape_string($_GET['points']));
//$sql = mysql_query("INSERT INTO `$db`.`scores` (`id`,`name`,`score`) VALUES ('','$name','$score');");
$sql = mysql_query("UPDATE `users` SET user_points = '$points' WHERE user_id = " . $_SESSION['user']);
}
if($sql){
//The query returned true - now do whatever you like here.
echo 'Your score was saved. Congrats!';
}else{
//The query returned false - you might want to put some sort of error reporting here. Even logging the error to a text file is fine.
echo 'There was a problem saving your score. Please try again later.';
}
}else{
echo 'Your name or score wasnt passed in the request. Make sure you add ?name=NAME_HERE&score=1337 to the tags.';
}
mysql_close();//Close off the MySQL connection to save resources.
?>
enter image description here
enter image description here

I Finally Solve The Problem...
<?php
header('Access-Control-Allow-Origin: *');
error_reporting(E_ALL);
ini_set('display_errors',1);
session_start();
include_once 'dbconnect.php';
if(!isset($_SESSION['user']))
{
header("Location: index.php");
}
if(isset($_GET['points'])){
//Lightly sanitize the GET's to prevent SQL injections and possible XSS attacks
$points = strip_tags(mysql_real_escape_string($_GET['points']));
//$sql = mysql_query("INSERT INTO `publiadd_loginsx`.`users` (`points`) VALUES ('points');");
$sql = mysql_query("UPDATE `users` SET user_points = user_points +'$points' WHERE user_id = " . $_SESSION['user']);
if($sql){
//The query returned true - now do whatever you like here.
echo 'Your Points was saved. Congrats!';
}else{
//The query returned false - you might want to put some sort of error reporting here. Even logging the error to a text file is fine.
echo 'There was a problem saving your points. Please try again later.';
}
}else{
echo 'Your points wasnt passed in the request. Make sure you add ?name=NAME_HERE&score=1337 to the tags.';
}
// close MySQL connection
mysql_close();
?>
<html>
<head>
</head>
<body>
<body bgcolor="#ffffff">
</body>
</html>
And This is work now really work

Related

php/mysql comments duplicating automatically on pages reload

I have created a commenting system for my website. The problem I have is that, the old comments duplicate themselves anytime the webpage is refreshed or reloaded.
How can I stop this and only show original comments?
I have added the entire code here below:
<pre>
require 'data/connect.php';
if(isset($_POST['name'])&& isset($_POST['comment'])){
$name = trim($_POST['name']);
$comment = trim($_POST['comment']);
if(!empty($name) && !empty($comment)){
$insert = $connect->query("INSERT INTO
comments(name,comment)VALUES('$name','$comment')");
if($insert){
echo "Success";
}else{
echo "Sorry";
}
}
}
?>
</pre>
form here
<pre>
<?php
if(isset($_POST['name'])&& isset($_POST['comment'])){
$name = trim($_POST['name']);
$comment = trim($_POST['comment']);
if(!empty($name) && !empty($comment)){
$query = $connect->query("SELECT name,comment FROM comments WHERE name='$name' AND comment='$comment'");
while($row = $query->fetch_object()){
echo "<b>",$row->name,"</b><br/>",$row->comment;
}
}
}
?>
</pre>
Your help will be appreciated.
Send out a unique value (created with php's uniqid() for example) in a hidden field in the form. Every time you send the form to a browser, change the value. If you get the same value twice from the same browser, you know it was a double post.
You could also compute a hash of the posted information and compare that against hashes of what's already in the database, for speed, you could store the hash for each comment in the database.
You may also be able to restrict this at the database level, for example by using replace instead of insert (for mySQL).

How to redirect WORDPRESS hotlinked image ( for exp : Image.jpg) to post/page where it is?

Recently google change image search and as a result most of the traffic click over view original image and it send them to direct image file.
I have changed my .htaccess and stop all hot linking and redirect to my homepage if they click over image file.
Recently I've also tried if it is possible to redirect to post or page where image is.
By the following code
<?php
require('../wp-blog-header.php');
$imageURL = strip_tags( $_GET['id'] );
if imageURL!== "") {
$query = "SELECT ID FROM $wpdb->posts WHERE post_type = 'attachment'AND post_parent > '0' AND guid = '$imageURL'";
$linkedImage = $wpdb-get_row($query);
$attachmentUrl = get_attachment_link($linkedImage->ID);
if($attachmentUrl !== "" && !is_numeric(stripos($attachmentUrl, "attachment_id=0"))) {
header("HTTP/1.1 302 Found");
header("Location: ". $attachmentUrl);
exit;
}
}
$newUrl = get_site_url() . "/image-not-found";
header("HTTP/1.0 404 Not Found");
header("Location: " . $newUrl);
exit;
?>
But it redirect to http://www.mydomain.com/?attachment_id=
id is nil or can't fetch the proper id
My website in Wordpress CMS version 3.5.1
can anyone help how to redirect to proper attachment page for .jpg file direct request.
Thanks in advance
Your code would only work if there was an ID parameter on the requested URL that would be an exact match with the image URL, for instance http://www.example.com/?id=http://www.example.com/uploads/Some-Image.jpg
Is this the case? Even so, you shouldn't use id since it's a reserved parameter for other things in WP. In your .htaccess, you should redirect http://www.example.com/uploads/Some-Image.jpg to, for example, http://www.example.com/?image_redirect=http://www.example.com/uploads/Some-Image.jpg. Then use $imageURL = $_GET['image_redirect'].
Other notes: strip_tags doesn't make a string safe to use as a SQL query. In WordPress, you have esc_sql($string) for that. Also, you should rather use if ( $imageUrl != '' ), not with !==. And there's an error on line 5, it should say $wpdb->get_row, you currently have a minus sign. I assume these are typos. And finally, you shouldn't use Location: header with a status code 404.

PHP Session doesn't get read in next page after login validation, Why?

I have a web site and when my users login it takes them to
verify.php
(where it connects to the DataBase and matches email and password to the user input and if OK puts client data into sessions and take the client to /memberarea/index.php ELSE back to login page with message "Invalid Email or password!")
<?php
ob_start();
session_start();
$email=$_POST['email'];
$pass=md5($_POST['pass']);
include("conn.php"); // connects to Database
$sql="SELECT * FROM `user` WHERE email='$email' AND pass='$pass'";
$result=mysql_query($sql);
$new=mysql_fetch_array($result);
$_SESSION['fname']=$new['fname'];
$_SESSION['lname']=$new['lname'];
$_SESSION['email']=$new['email'];
$_SESSION['passwrd']=$new['passwrd'];
$no=mysql_num_rows($result);
if ($no==1){
header('Location:memberarea/index.php');
}else {
header("Location:login.php?m=$msg"); //msg="Invalid Login"
}
?>
then after email id and password is verified it takes them to `
/memberarea/index.php
(This is where the problem happens.)
where in index.php it checks if a session has been created in-order to block hackers to enter member area and sends them back to the login page.
<?
session_start();
isset($_SESSION['email'])` && `isset($_SESSION['passwrd'])`
The problem is the client gets verified in verify.php (the code is above)
In varify.php only after I put
ob_start(); ontop of session_start();
It moves on to /memberarea/index.php ,
If I remove ob_start()
It keeps the client on the verify.php page and displays error header is alredy SENT.
after I put ob_start() it goes in to /memberarea/index.php but the session is blank,
so it goes back to the login page and displays the error ($msg) "Invalid Login" which I programed to display.
Can anyone tell me why the session cant pass values from verify.php to /memberarea/index.php
It seems that some white space is getting from conn.php. If the ?> is at the end of conn.php , please remove it ( There may be some white space after it) and make sure that there is no white space before <? in conn.php. Then you won't get header is alredy SENT error.
And you should set the session data after making sure there is result as given below:
<?php
ob_start();
session_start();
$email=$_POST['email'];
$pass=md5($_POST['pass']);
include("conn.php"); // connects to Database
$sql="SELECT * FROM `user` WHERE email='$email' AND pass='$pass'";
$result=mysql_query($sql);
$no=mysql_num_rows($result);
if ($no==1){
// Set the session data here.
$new=mysql_fetch_array($result);
$_SESSION['fname']=$new['fname'];
$_SESSION['lname']=$new['lname'];
$_SESSION['email1']=$new['email1'];
$_SESSION['passwrd']=$new['passwrd'];
header('Location:memberarea/index.php');
}
else {
header("Location:login.php?m=$msg"); //msg="Invalid Login"
}
and one more thing; you are using two index for email data $_SESSION['email1'] and $_SESSION['email']. first one (email1) is wrong.

codeigniter : using flash data but no new page load?

Usually, I just set a $feedback var or array and then check for that to display in my views.
However, it occurred to me I should perhaps use flashdata instead.
The problem is sometimes - for say an edit record form, I may simply want to reload the form and display feedback - not redirect. when i use flashdata, it shows but then it shows on the next request as well.
What would be the best practice to use here?
CodeIgniter supports "flashdata", or session data that will only be available for the next server request, and are then automatically cleared.
u use hidden field for that
I would use the validation errors from the Form validation class and load those directly to the view in its 2nd argument.
$this->form_validation->set_error_delimiters('<p>', '</p>');
$content_data = array();
if (!$this->form_validation->run()) {
$content_data['errors'] = validation_errors();
}
$this->load->view('output_page', $content_data);
Then check in your view whether $errors isset.
Controller:
$data['message'] = 'some message you want to see on the form';
$this->load->view('yourView', $data);
View:
if (isset ($message)) : echo $message; endif;
...

Magento custom add to cart process not working

REVISED QUESTION: We have tracked this down to a custom add to cart method. I have completely revised the question.
I am working on a site that is using Magento ver. 1.3.2.4 as its eCommerce platform. We have built a custom "Add To Cart" process which adds multiple items to the cart via an AJAX request. After this request, some postprocessing is done viw JavaScript in the browser before redirecting to the "View Cart" page. 99% of the time this process seems to function properly in Firefox and Safari but in IE8, the process fails. When adding an item to the cart, after being redirected to the "Your Cart" page, the shopping cart is empty.
Not all items on the site are added via this AJAX process. This issue only happens only when the cart is empty before adding the items via AJAX. That is to say, if an item that is added via the normal Magento process is added to the cat first, then the AJAX add to cart requests always succeed. Blu clearing cookies and then attempting to add via AJAX will fail consistently on IE8.
Server is an Apache/PHP server with PHP 5.2.9, eAccelerator and Suhosin. Please request any additional information and I'll be happy to provide it. We are storing sessions in a MySQL Database.
Here is the code for our custom add to cart method. This code is located in /app/code/core/Mage/Checkout/controllers/CartController.php:
public function ajaxaddAction()
{
$result = array('success' => true);
try
{
$session = $this->_getSession();
$cart = $this->_getCart();
$products = json_decode($_POST['products'],true);
if(!is_array($products))
{
throw new Exception("Products data not sent");
}
foreach ($products as $product_data)
{
$product = $this->_initProduct($product_data['id']);
if(!$product)
throw new Exception("Product id {$product_data['id']} not found");
$info = array('qty' => $product_data['qty']);
if($product_data['options'])
$info['options'] = $product_data['options'];
$cart->addProduct($product,$info);
}
$cart->save();
$this->_getSession()->setCartWasUpdated(true);
/**
* #todo remove wishlist observer processAddToCart
*/
Mage::dispatchEvent('checkout_cart_add_product_complete',
array('product' => $products[0], 'request' => $this->getRequest(), 'response' => $this->getResponse())
);
$cartItems = $cart->getQuote()->getAllItems();
$result['cart'] = array();
foreach($cartItems as $item)
$result['cart'][] = json_decode($item->toJson());
}
catch (Mage_Core_Exception $e)
{
if ($this->_getSession()->getUseNotice(true)) {
$this->_getSession()->addNotice($e->getMessage());
} else {
$messages = array_unique(explode("\n", $e->getMessage()));
foreach ($messages as $message) {
$this->_getSession()->addError($message);
}
}
$result['success'] = false;
$result['exception'] = $e->getMessage();
}
catch (Exception $e) {
$this->_getSession()->addException($e, $this->__('Can not add item to shopping cart'));
$result['success'] = false;
$result['exception'] = $e->getMessage();
}
header('Content-Type: application/json',true);
ob_end_clean();
echo json_encode($result);
exit();
}
Please don't answer with "Move the code to the /app/code/local/ directory". I understand that's a better place for it, and will move it there in the future, but unless your answer will solve the issue, please just post a comment. In order to get a faster response I'm starting a bounty and want good answers to this specific issue, not just tips on better ways to integrate this code.
If there's any information I can provide to assist please let me know. We're under a tight deadline...
I've spent over 10 hours on this. For the moment I believe I have a partial solution. But I'm not sure why this solution works...
It seems that Magento requires a redirect in order to complete the add to cart process. So instead of
header('Content-Type: application/json',true);
ob_end_clean();
echo json_encode($result);
exit();
I store my JSON in the session and redirect to a new cart action:
$this->_getSession()->setCartJsonResult(json_encode($result));
$this->_redirect('checkout/cart/postajaxadd');
That action then dumps the JSON data
public function postajaxaddAction()
{
$session = $this->_getSession();
header('Content-Type: application/json',true);
ob_end_clean();
echo $this->_getSession()->getCartJsonResult();
exit();
}
This still fails sometimes; however now my JavaScript code does not get the JSON data it was expecting and is able to repeat the request. The second request is successful more often than the first... However there are still cases when the AJAX requests fail no matter what.
Not sure if this is causing the problems you're running into, but a better way to do a JSON response would be to use the existing "Magento/Zend way" of doing it.
Instead of:
header('Content-Type: application/json',true);
ob_end_clean();
echo json_encode($result);
exit();
Use:
$this->getResponse()->setHeader('Content-Type', 'application/json', true)->setBody(json_encode($result));
We've experienced issues adding things to the cart when session storage runs out and new sessions can't be created. If you're storing sessions on disk or in memcache, check that you've allocated enough space.

Resources