Skip to content

Instantly share code, notes, and snippets.

@solepixel
Created August 29, 2015 13:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save solepixel/5af78fca98fc7cce0dfd to your computer and use it in GitHub Desktop.
Save solepixel/5af78fca98fc7cce0dfd to your computer and use it in GitHub Desktop.
jQuery + JSON + AJAX (old blog post)
function ajaxJSON(json){
if(json){
var obj = (typeof(json) == 'object') ? json : eval('(' + json + ')');
eval(obj.script);
if(obj.confirm){
obj.success = confirm(obj.confirm);
}
return obj;
}
return {};
}
<?php
$description = trim($_POST['description']);
$sku = trim($_POST['sku']);
$result = array();
if(empty($description) || empty($sku)){
$result['html'] = 'Please fill in all required fields.';
$result['success'] = false;
} else {
$result['html'] = 'Your product was added successfully.';
$result['success'] = true;
/* I'd also like to add the product to a list of products on the page. */
$product_string = '$("#products").append(\'<div>%s (%s) - <a href="#delete" class="delete">delete</a></div>\');';
$result['script'] = sprintf($product_string, $description, $sku);
}
echo json_encode($result);
exit();
<!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>AJAX + JSON = Organized Responses</title>
<script type="text/javascript" src="/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
// this will parse scripts, execute the confirm if applicable and return the object for further use
function ajaxJSON(json){
if(json){
var obj = (typeof(json) == 'object') ? json : eval('(' + json + ')');
eval(obj.script);
if(obj.confirm){
obj.success = confirm(obj.confirm);
}
return obj;
}
return {};
}
$(function(r){
$("#my_form").submit(function(s){
var params = $(this).serialize();
$.ajax({
type: 'post',
url: 'products_ajax/add/',
data: params,
dataType: 'json',
success: function(response){
result = ajaxJSON(response);
if(result.html){
if(result.success){
$(".error").hide();
$("#response").show().html(result.html);
// reset my form to get ready for a new entry
$('#my_form').each(function(e){
this.reset();
});
} else {
$("#response").hide();
$(".error").show().html(result.html);
}
}
focus_first();
}
});
/*
// A non-async way to use this is:
var response = $.ajax({
type: 'post',
url: 'products_ajax/add/',
data: params,
dataType: 'json',
async: false
}).responseText;
result = ajaxJSON(response);
if(result.html){
if(result.success){
$(".error").hide();
$("#response").show().html(result.html);
// reset my form to get ready for a new entry
$('#my_form').each(function(e){
this.reset();
});
} else {
$("#response").hide();
$(".error").show().html(result.html);
}
}
focus_first();
// you may want to submit the form with the following line
//return result.success;
*/
return false;
});
// form init
focus_first();
$("a.delete").live('click', function(c){
if(confirm('Are you sure?')){
$(this).parents('div:first').remove();
focus_first();
}
return false;
});
});
function focus_first(){
$("#my_form input[type=text][value='']:first").focus();
}
</script>
<style type="text/css">
#response { color:#090; }
.error { color:#F00; }
#my_form, #products { float:left; width:300px; }
</style>
</head>
<body>
<div id="response"></div><!-- successful response message -->
<div class="error"></div><!-- error response message -->
<form id="my_form" action="/" method="post">
<fieldset>
<legend>Add a Product</legend>
<p><label>Description: <input type="text" name="description" /></label></p>
<p><label>SKU: <input type="text" name="sku" /></label></p>
<input type="submit" value="Go!" />
</fieldset>
</form>
<div id="products">
<h2>Products</h2>
</div>
</body>
</html>
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Cajax {
private $ci;
private $result = array();
function Cajax(){
// uncomment the next line if you want CI access
//$this->ci = get_instance();
}
function add($data, $key){
if(isset($this->result[$key]) && !empty($this->result[$key])){
$this->result[$key] .= $data;
} else {
$this->result[$key] = $data;
}
}
function add_html($html){
$this->add($html, 'html');
}
function add_script($script){
$this->add($script, 'script');
}
function add_text($text){
$this->add(strip_tags($text), 'text');
}
function success($val=true){
$this->result['success'] = $val;
}
function confirm($confirm){
$this->result['confirm'] = $confirm;
}
function restrict($loggedin, $redirect='/login/'){
if(!$loggedin){
$this->add_script('alert("Your session is no longer valid. Press OK to be taken to login page."); window.location = "'.$redirect.'";');
$this->finish();
}
}
function finish($success=NULL){
if($success != NULL && is_bool($success)){
$this->success($success);
}
if(count($this->result)> 0){
echo json_encode($this->result);
}
exit();
}
}
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment