How i use ajax with wordpress - ajax

I am new to ajax. I want to place a combobox on page. Combobox contain option
by popularity, by price and by date.
I want to change the content of div with ajax without reloading the page.
e.g i am displaying a product of watches. when user change the value at combo box, the value/images displayed at page will be change as accordingly.
1) i want to know how to use ajax with word press.
2)code to achieve this.
I am using this code:
<div class="prodimg">
<ul class="rcollpro">
<?php
$ordr ='date';
$args = array( 'post_type' => 'product', 'product_cat' => 'Rings', 'stock' => 1, 'posts_per_page' => 12, 'orderby' =>'$ordr','order' => 'DESC' );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?>
<li class="rcollproli">
<?php if (has_post_thumbnail( $loop->post->ID )) echo get_the_post_thumbnail($loop->post->ID, 'shop_catalog'); else echo '<img src="'.woocommerce_placeholder_img_src().'" alt="Placeholder" width="65px" height="115px" />'; ?>
<h3><?php the_title(); ?></h3>
<span class="price"><?php echo $product->get_price_html(); ?></span><br />
<?php woocommerce_template_loop_add_to_cart( $loop->post, $product ); ?>
</li><!-- /span3 -->
<?php endwhile; ?>
<?php wp_reset_query(); ?>
</ul><!-- /row-fluid -->
</div>

You dont actually need to implement Ajax, but you can do it with simple JS. I can share a simple code with you for your reference.
<script type="text/javascript">
function hourChange(selectObj) {
var selectIndex=selectObj.selectedIndex;
var selectValue=selectObj.options[selectIndex].text;
var output=document.getElementById("output");
//alert(output.innerText);
output.innerHTML=selectValue;
}
</script>
<select id="hour" onchange="hourChange(this);">
<option>1</option>
<option>2</option>
</select>
<p/>
you selected: <span id="output">1</span>
Try this in simple HTML file. And it's easy to implement it in WP too.

You can find the solution below for your code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
$( document ).ready(function() {
$("#selector").change(function() {
var selectedValue = $("#selector option:selected").val();
alert('Selected text ' + selectedValue);
});});
</script>
</head>
<body>
<select name="orderby" class="orderby" id="selector">
<option value="menu_order">Default sorting</option>
<option value="popularity">Sort by popularity</option>
<option value="date ">Sort by newness</option>
<option value="price">Sort by price: low to high</option>
<option value="price-desc">Sort by price: high to low</option>
</select>
</body>
</html>

Related

fineuploader - encoding special characters

When i uploaded a file with the name "äüö.txt" the file on the ftp-server gets the name "-956.txt". This only happens when the name of the file contains special characters. How can I solve this problem?
HTML-Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org /TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<script src="jquery-1.10.2.min.js"></script>
<script src="custom.fineuploader-4.0.3.js" type="text/javascript"></script>
<script type="text/template" id="qq-template-manual-noedit">
<div class="qq-uploader-selector qq-uploader">
<div class="qq-upload-drop-area-selector qq-upload-drop-area" qq-hide-dropzone>
<span>Drop files here to upload</span>
</div>
<div class="qq-upload-button-selector qq-upload-button">
<div>Upload a file</div>
</div>
<span class="qq-drop-processing-selector qq-drop-processing">
<span>Processing dropped files...</span>
<span class="qq-drop-processing-spinner-selector qq-drop-processing-spinner"></span>
</span>
<ul class="qq-upload-list-selector qq-upload-list">
<li>
<div class="qq-progress-bar-container-selector">
<div class="qq-progress-bar-selector qq-progress-bar"></div>
</div>
<span class="qq-upload-spinner-selector qq-upload-spinner"></span>
<span class="qq-upload-file-selector qq-upload-file"></span>
<span class="qq-upload-size-selector qq-upload-size"></span>
<a class="qq-upload-cancel-selector qq-upload-cancel" href="#">Cancel</a>
<span class="qq-upload-status-text-selector qq-upload-status-text"></span>
</li>
</ul>
</div>
</script>
<script type="text/javascript">
$(document).ready(function () {
var manualuploader = $("#fine-uploader-fileUploadEmailCampaigns").fineUploader({
autoUpload: false,
multiple: false,
template: "qq-template-manual-noedit",
editFilename: {
enabled: false
},
request: {
endpoint: 'endpoint.php'
},
});
$('#triggerUpload').click(function () {
manualuploader.fineUploader('uploadStoredFiles');
});
})
</script>
<title>Unbenanntes Dokument</title>
<link href="custom.fineuploader-4.0.3.min.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="fine-uploader-fileUploadEmailCampaigns">
</div>
<div id="triggerUpload" class="btn btn-primary" style="margin-top: 10px;">Upload</div>
</body>
</html>
PHP-Code:
<?php
// Include the upload handler class
require_once "handler.php";
$uploader = new UploadHandler();
// Specify the list of valid extensions, ex. array("jpeg", "xml", "bmp")
$uploader->allowedExtensions = array(); // all files types allowed by default
// Specify max file size in bytes.
$uploader->sizeLimit = 10 * 1024 * 1024; // default is 10 MiB
// Specify the input name set in the javascript.
$uploader->inputName = "qqfile"; // matches Fine Uploader's default inputName value bydefault
// If you want to use the chunking/resume feature, specify the folder to temporarily save parts.
$uploader->chunksFolder = "chunks";
$method = $_SERVER["REQUEST_METHOD"];
if ($method == "POST") {
header("Content-Type: text/plain");
// Call handleUpload() with the name of the folder, relative to PHP's getcwd()
$result = $uploader->handleUpload("files");
// To return a name used for uploaded file you can use the following line.
$result["uploadName"] = $uploader->getUploadName();
echo json_encode($result);
}
else {
header("HTTP/1.0 405 Method Not Allowed");
}
?>
My guess is that the locale ($LANG) you are using to write out the file does not match the locale of your OS. For example, to properly create a file with non-english characters in the name in my development environment (OS X, Java 7, IntelliJ) I need to be sure that the LANG environment variable associated with my JVM is "en_US.UTF-8", which matches the $LANG variable set in OS X.

uncaught exception: Call to StartUpload failed in uploadify integration with codeigniter

i have integrated uploadify with codeigniter.i can't able select images while clicking the select photos.
MY View file
<!DOCTYPE HTML>
<html lang="en-GB">
<head>
<meta charset="UTF-8">
<title>Uploadify V3 & CodeIgniter</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="Capsone-System2" >
<!-- Styles -->
<link href="/assets/bootstrap/css/bootstrap.min.css" type="text/css" media="screen" rel="stylesheet"/>
<link href="<?php echo base_url;?>assets/js/jquery/uploadify_31/uploadify.css" type="text/css" media="screen" rel="stylesheet"/>
<!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<!-- Main Content -->
<div class="container">
<h1 class="page-header">Uploadify V3 & CodeIgniter</h1>
<p>This is a simple tutorial demo showing Uploadify V3 working with CodeIgniter 2.1.2</p>
<?php echo form_open_multipart(); ?>
<ul class="unstyled">
<li>
<?php echo form_upload('userfile','','id="userfile"'); ?>
<?php echo (isset($error)) ? $error : ''; ?>
</li>
<li>
<?php echo form_button(array('content'=> 'Upload', 'id'=>'upload-file', 'class'=>'btn btn-large btn-primary')); ?>
</li>
</ul>
<?php echo form_close(); ?>
</div>
<!-- End Of Main Content -->
<!--<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>-->
<!--<script>window.jQuery || document.write('<script src="<?php echo base_url;?>assets/js/jquery/jquery-1.8.0.min.js"></script>')</script>-->
<script src="<?php echo base_url;?>assets/js/jquery/uploadify_31/jquery.uploadify-3.1.min.js" type="text/javascript"></script>
<!--<script src="<?php echo base_url;?>assets/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>-->
<script type="text/javascript">
$(document).ready(function () {
var base_url = '<?php echo base_url; ?>';
alert(base_url);
$('#upload-file').click(function (e) {
e.preventDefault();
$('#userfile').uploadify('upload', '*');
alert(base_url);
});
$('#userfile').uploadify({
'debug':true,
'auto':false,
'swf': base_url + 'assets/js/jquery/uploadify_31/uploadify.swf',
'uploader': base_url + 'uploadify_v3/do_upload',
'cancelImg': base_url + 'assets/javascript/jquery/uploadify_31/uploadify-cancel.png',
'fileTypeExts':'*.jpg;*.bmp;*.png;*.tif',
'fileTypeDesc':'Image Files (.jpg,.bmp,.png,.tif)',
'fileSizeLimit':'2MB',
'fileObjName':'userfile',
'buttonText':'Select Photo(s)',
'multi':true,
'removeCompleted':false,
'onUploadError' : function(file, errorCode, errorMsg, errorString) {
alert('The file ' + file.name + ' could not be uploaded: ' + errorString);
}
});
});
</script>
</body>
</html>
My Controller File
I have error uncaught exception: Call to StartUpload failed
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* #property CI_Upload $upload
*/
class Uploadify_v3 extends CI_Controller
{
public $view_data = array();
private $upload_config;
function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->helper(array('url', 'form'));
$this->load->view('uploadify_v3', $this->view_data);
}
public function do_upload()
{
$this->load->library('upload');
$image_upload_folder = FCPATH . '/uploads';
if (!file_exists($image_upload_folder)) {
mkdir($image_upload_folder, DIR_WRITE_MODE, true);
}
$this->upload_config = array(
'upload_path' => $image_upload_folder,
'allowed_types' => 'png|jpg|jpeg|bmp|tiff',
'max_size' => 2048,
'remove_space' => TRUE,
'encrypt_name' => TRUE,
);
$this->upload->initialize($this->upload_config);
if (!$this->upload->do_upload()) {
$upload_error = $this->upload->display_errors();
echo json_encode($upload_error);
} else {
$file_info = $this->upload->data();
echo json_encode($file_info);
}
}
}
/* End of file uploadify_v3.php */
/* Location: ./application/controllers/uploadify_v3.php */
I have spent more time..still now i can't fix this error..please help me.
I too had the same problem, it was a security issue because I was hosting the flash .swf file on a separate domain eg: static.mysite.com
Make sure your swf file and post handler script are hosted on the same domain that you are accessing the site from.
Or if you need to add cross domain posting then see here:
http://www.adobe.com/devnet/adobe-media-server/articles/cross-domain-xml-for-streaming.html

Form submit in $(document).ready(function(){. Is there a simple fix?

This should be an easy fix for the right guru! Everything is working for me except that I can't get this form to submit without clicking the submit button. The data values are all valid. The action page, ...gdform.php, uses $_post to get the "redirect" value from the form and then uses php to do a header Location change. That works fine if I execute the form with the submit button. I just need it to happen without any click...
Take a look, please!
<?php session_start();
require_once('Connect.php') ;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Nitrofill Document</title>
<?php
//error_reporting(E_ALL);
$sn=$_GET['num'];
echo $sn;
mysql_connect($hostname,$username, $password) OR die('Unable to connect to database! Please try again later.');
mysql_select_db($dbname);
$selectSQL = "select * from `Presentations` where `serialnum` ='" . $sn ."'" ;
$result = mysql_query($selectSQL) or die(mysql_error());
$row = mysql_fetch_array($result, MYSQL_BOTH);
$thedoc = urldecode($row['docurl']);
$therecip=urldecode($row['recipient']);
$thetracker=urldecode($row['tracker']);
$lastacc=urldecode($row['last_accessed']);
?>
</head>
<body>
<form id="notice" action="http://m3sglobal.com/gdform.php" method="post">
<input name="subject" value="<?php echo $therecip . " has viewed the document you sent them.";?> " />
<input type="hidden" name="redirect" value="<?php echo $thedoc ; ?>"/>
<label>Email:</label><input type="text" name="email" value="<?php echo $thetracker ; ?>"/>
<label>Comments:</label><textarea name="comments" cols="40" rows="5">
Document Viewed:<?php echo $thedoc ; ?>
When Accessed:<?php echo $lastacc ; ?>
</textarea>
<input type="submit" name="submit"/>
</form>
</body>
</html>
<script type="text/javascript">
$(document).ready(function(){
myfunc
});
function myfunc () {
var frm = document.getElementById("notice");
frm.submit();
}
</script>
I might be wrong but shouldn't it be: (corrected typos)
$(document).ready(function(){
myfunc(); <--// with ();
});
function myfunc() { <--// without space
var frm = document.getElementById("notice");
frm.submit();
}
or better yet:
$(document).ready(function(){
$("form#notice").submit();
});
EDIT:
Prowla is right, you also didn't declare the jQuery library. Good catch Prowla, I missed that, just saw the typos.
EDIT #2:
Your code is pretty messy there, and you have that PHP generated string in the <head>. Also your submit had no value, you used name. I cleaned it up, here is working code (for me at least):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Nitrofill Document</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("form#notice").submit();
});
</script>
</head>
<body>
<!--// ALL THE PHP SHOULD GO HERE TO MAKE THE URL BELOW //-->
qyO452ZKphttps://docs.google.com/presentation/pub?id=1chxqg-qjrfEvAR9_Jia7lt4ps2_Q7IfTiI41bQE7Q_4&start=true&loop=false&delayms=3000<br/>greg.mcgee#gmail.com<br/>greg.mcgee#advetel.com<br/>Thu, 23 Feb 2012 19:42:11 MST<br/>
<!--// END PHP //-->
<form id="notice" action="http://m3sglobal.com/gdform.php" method="post">
<input name="subject" value="greg.mcgee#gmail.com has viewed the document you sent them. " />
<input type="hidden" name="redirect" value="https://docs.google.com/presentation/pub?id=1chxqg-qjrfEvAR9_Jia7lt4ps2_Q7IfTiI41bQE7Q_4&start=true&loop=false&delayms=3000"/>
<label>Email:</label><input type="text" name="email" value="greg.mcgee#advetel.com"/>
<label>Comments:</label><textarea name="comments" cols="40" rows="5">
Document Viewed:https://docs.google.com/presentation/pub?id=1chxqg-qjrfEvAR9_Jia7lt4ps2_Q7IfTiI41bQE7Q_4&start=true&loop=false&delayms=3000
When Accessed:Thu, 23 Feb 2012 19:42:11 MST
</textarea>
<input type="submit" value="submit"/>
</form>
</body>
</html>
You might want to consider using firebug to help you troubleshoot your pages. Its how I figured this out. Also remember Prowla's advice, and protect your SQL.
Using jQuery: (Remember to put the jquery script in your <head> tags).
<head>
...
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
...
<head>
...
// submit form with id notice
$(document).ready(function(){
$('#notice').submit();
});
Also your SQL is subject to injection. Please look into using prepared statements.
Sample in PHP:
$mysqli = new mysqli('localhost', 'user', 'password', 'db');
$stmt = $mysqli->prepare('select * from `Presentations` where `serialnum` =?');
$stmt->bind_param('i',$sn);
$stmt->execute();
....

Ajax div refreshing

I have a problem with AJAX , I cant find a good solution to refresh only my div "chatwindow" every second. I have tried many posts from stackoverflow and from google.
Can someone help me... to make this.
So far my code
<!DOCTYPE HTML>
<?php
include 'config.php';
?>
<html>
<head>
<title>JavaScript Chat</title>
<link href="style.css" rel="stylesheet" type="text/css"/>
</script>
</head>
<body>
<div class="container">
<div id="chatwindow">
<?php
$result = mysql_query("select * from Message");
while($row = mysql_fetch_array($result))
{
echo '<p>' . $row['username'] . " : " . $row['message'] . '</p>';
}
?>
</div>
<div class="inputMessage">
<form method="post">
<hr></hr>
<textarea name="message" rows="1" cols="55"></textarea><br/>Fill username here<br/>
<input type="submit" value="verstuur" name="submit"/>
<input type="text" value="" name="username" />
</form>
<?php
if(isset($_POST['submit']))
{
if (!empty($_POST['username']))
{
if(!empty($_POST['message']))
{
$message = mysql_real_escape_string(htmlentities($_POST['message']));
$username = mysql_real_escape_string(htmlentities($_POST['username']));
$query = "INSERT INTO Message (`username`,`message`) VALUES ('".$username."','".$message."')";
mysql_query($query);
}
else
{
echo '<script type="text/javascript">alert(\'Je kan niet niks sturen\')</script>';
}
}
else
{
echo '<script type="text/javascript">alert(\'Vul een gebruikresnaam in!\')</script>';
}
}
?>
</div>
</div>
</body>
</html>
[1]: http://chaotix.nl/chat/ "chat"
first you have to download latest jquery file from http://code.jquery.com/jquery-1.7.1.js
put this
<script type="text/javascript" src="jquery-1.7.1.js"></script>
under the head section
now put below code after <script type="text/javascript" src="jquery-1.7.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
window.setInterval(function(){
$.ajax({
url: 'chat.php',
type: "POST",
data: "",
cache: true,
success: function(response){
$("#chatwindow").html(response);
}
}, 1000);
});
</script>
you should extract php code form chatwindow div into another file and call it with AJAX and setInterval function every second.. if you wish to do it in this way.
This would be
chat.php
<?php
$result = mysql_query("select * from Message");
while($row = mysql_fetch_array($result))
{
echo '<p>' . $row['username'] . " : " . $row['message'] . '</p>';
}
?>
Then you would have your main file from which you would call ajax and refresh div:
<!DOCTYPE HTML>
<?php
include 'config.php';
?>
<html>
<head>
<title>JavaScript Chat</title>
<link href="style.css" rel="stylesheet" type="text/css"/>
</script>
</head>
<body>
<div class="container">
<div id="chatwindow">
</div>
<div class="inputMessage">
<form method="post">
<hr></hr>
<textarea name="message" rows="1" cols="55"></textarea><br/>Fill username here<br/>
<input type="submit" value="verstuur" name="submit"/>
<input type="text" value="" name="username" />
</form>
<?php
if(isset($_POST['submit']))
{
if (!empty($_POST['username']))
{
if(!empty($_POST['message']))
{
$message = mysql_real_escape_string(htmlentities($_POST['message']));
$username = mysql_real_escape_string(htmlentities($_POST['username']));
$query = "INSERT INTO Message (`username`,`message`) VALUES ('".$username."','".$message."')";
mysql_query($query);
}
else
{
echo '<script type="text/javascript">alert(\'Je kan niet niks sturen\')</script>';
}
}
else
{
echo '<script type="text/javascript">alert(\'Vul een gebruikresnaam in!\')</script>';
}
}
?>
</div>
<script type="text/javascript">
$(document).ready(function(){
setInterval ( "get()", 1000 );
});
function get(){
$.ajax({
type: 'GET',
url: 'chat.php',
success: function(data){
$("#chatwindow").html(data);
}
});
}
</script>
</div>
</body>
</html>
Try this one
<html>
<head>
<script langauge="javascript">
var counter = 0;
window.setInterval("refreshDiv()", 5000);
function refreshDiv(){
counter = counter + 1;
document.getElementById("test").innerHTML = "Testing " + counter;
}
</script>
</head>
<body>
<div id="test">
Testing
</div>
<div id="staticBlock">
This is a static block
</div>
</body>

why target="blank" doesn't open a new window

I am going to show $Content in a new window. after some searches I found the following code. but it doesn't open a new window and echoes $content in the same page.
<form method="POST" action=" <?php echo $Content; ?> " target="blank"></form>
update:
THIS IS THE CODE:
<?php
if(isset($_POST['submit']))
{
include 'library/config.php';
include 'library/opendb.php';
$Unit_Code = $_POST['Unit_Code'];
$File_Name = $_POST['File_Name'];
$_SESSION['Unit'] =$Unit_Code;
$_SESSION['file'] =$File_Name;
$query = "SELECT Unit_Code,File_Name, type,size, Content FROM Units WHERE ((Unit_Code = '$Unit_Code')&&(File_Name='$File_Name'))";
$result = mysql_query($query) or die(mysql_error());
list($Unit_Code, $File_Name, $type, $size, $Content) = mysql_fetch_array($result);
header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=$File_Name");
?>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="dblclick.js"></script>
</head>
<body>
<form method="POST" action=" <?php echo $Content; ?> " target="_blank"></form>
</body>
</html>
<?php
include 'library/closedb.php';
exit;
}
?>
It's target="_blank". The underscore is important.
You missed the _
<form action="URL TO POST THE FORM" method="POST" target="_blank">
<?php echo $Content; ?>
</form>
Missing: _ before targetin your HTML attribute: < .. target="_blank">

Resources