I am trying to submit a form without leaving the page using json.
However, the method below ignores the data I have entered into the CKEditor.
Any ideas (and feel free to correct my terminology)?
<script type="text/javascript">
$(document).ready( function() {
$("#addStory input[type=submit]").click(function(e) {
e.preventDefault();
$.post('_posteddata.php', $("#addStory").serialize(), function(result) {
alert(result.adminList);
}, "json");
});
});
</script>
<form name="addStory" action="" method="post" id="addStory">
<label for="story_story">Story: </label><textarea id="story_story" name="story_story"><p></p></textarea>
<?php
// Include the CKEditor class.
include("ckeditor/ckeditor.php");
// Create a class instance.
$CKEditor = new CKEditor();
$CKEditor->basePath = '/ckeditor/'
$CKEditor->replace("story_story");
?>
<input type="submit" value="Submit" />
</form>
_posteddata.php:
include 'connection.php';
function check_input($value, $quoteIt)
{
// Stripslashes
if (get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
// Quote if not a number
if (is_null($value) || $value=="") {
$value = 'NULL';
} else if (!is_numeric($value) && $quoteIt == 1) {
$value = "'" . mysql_real_escape_string($value) . "'";
}
return $value;
}
// CKEDITOR STUFF FOR STORY_STORY
if (isset($_POST)) {
$postArray = &$_POST;
}
foreach ( $postArray as $sForm => $value )
{
if($sForm == "story_story") {
$story_story = check_input($value, 1);
}
}
$query = "INSERT INTO story_table (story) VALUES ($story_story)";
mysql_query($query) or die(mysql_error() . $query);
$return = array();
$return['adminList'] = "New story added with ID: " . mysql_insert_id();
header('application/json');
echo json_encode($return);
mysql_close();
In this kind of situation you must force CKEditor to update the contents of the textarea
So your function would be something like this:
$(document).ready( function() {
$("#addStory input[type=submit]").click(function(e) {
e.preventDefault();
CKEDITOR.instances.story_story.updateElement(); // Update the textarea
$.post('_posteddata.php', $("#addStory").serialize(), function(result) {
alert(result.adminList);
}, "json");
});
});
Related
Okay I am using prepared statement to get all the cities.
this is my php file
<?php
include_once '../includes/db_connect.php';
$search = $_GET['term'];
if($stmtgetstore = $mysqli->prepare("SELECT * FROM cities WHERE city LIKE '%$search%'"))
{
//$stmtgetstore->bind_param("s",$search);
$stmtgetstore->execute();
$getstore = $stmtgetstore->get_result();
$stmtgetstore->close();
}
else
{
echo $mysqli->error;
}
$array = array();
$json = '[';
$first = true;
while($store = $getstore->fetch_assoc())
{
if (!$first) { $json .= ','; } else { $first = false; }
$json .= '{"value":"'.$store['city'].'"}';
}
$json .= ']';
?>
And this is my script and html
<script type="text/javascript">
$(document).ready(function()
{
$('#autoCity').autocomplete(
{
source: "scripts/search_store_by_city.php",
minLength: 2
})/*.data( "autocomplete" )._renderItem = function( ul, item )
{
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( item.city )
.appendTo( ul );
};*/
});
</script>
<div class="container">
<form action="" method="GET">
<input type="text" id="autoCity">
</form>
</div>
But somehow when I enter letters in textbox I see no result coming in console and no error also but when I run query in database it gives me rows
This query
SELECT * FROM cities WHERE city LIKE '%Kara%'
Any idea what me doing wrong?
Okay I forgot to echo my json at the end of the script
<?php
include_once '../includes/db_connect.php';
$search = $_GET['term'];
if($stmtgetstore = $mysqli->prepare("SELECT * FROM cities WHERE city LIKE '%$search%'"))
{
//$stmtgetstore->bind_param("s",$search);
$stmtgetstore->execute();
$getstore = $stmtgetstore->get_result();
$stmtgetstore->close();
}
else
{
echo $mysqli->error;
}
$array = array();
$json = '[';
$first = true;
while($store = $getstore->fetch_assoc())
{
if (!$first) { $json .= ','; } else { $first = false; }
$json .= '{"value":"'.$store['city'].'"}';
}
$json .= ']';
echo $json;
?>
I am working on WordPress plugin. In plugin there is a check box, when a user checked the checkbox a value will be saved in database via ajax and when its unchecked the value will be deleted from database via ajax. So I create a checkbox and write an ajax code.
Here is my code:
HTML Code
<?php
$cart_items = get_cart_contents();
$cart_info = array();
foreach ($cart_items as $_data) {
$prod_id = $_data['id'];
$cart_info[] = array(
'prod_id' => $prod_id,
);
}
$_cart_sr = serialize($cart_info);
?>
<label class="label" for="purchase">
<?php _e('Purchase', 'product'); ?>
<input type="checkbox" id="purchase" />
</label>
<input type="hidden" class="cart_info" value='<?php echo $_cart_sr; ?>'>
Here is my Ajax and PHP Code:
add_action('wp_ajax_values_save', 'save_check_value');
add_action('wp_ajax_nopriv_values_save', 'save_check_value');
add_action('wp_ajax_values_delete', 'delete_check_value');
add_action('wp_ajax_nopriv_values_delete', 'delete_check_value');
add_action("wp_head", "edd_gift_email_ajax");
function edd_gift_email_ajax() {
?>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery("#purchase").click(function () {
if(jQuery(this).is(":checked")) {
var cart_info_save = jQuery('.cart_info').val();
var data_save = {
action: 'values_save',
cart_info_save: cart_info_save
}
jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', data_save, function (save_result) {
alert(save_result);
});
} else {
var cart_info_delete = jQuery('.cart_info').val();
var data_delete = {
action: 'values_delete',
cart_info_delete: cart_info_delete
}
jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', data_delete, function (delete_result) {
alert(delete_result);
});
}
});
});
</script>
<?php
}
And here is my save and delete query
function save_check_value() {
global $wpdb;
$info_save = stripcslashes($_REQUEST['cart_info_save']);
$cart_info_un_sr_save = unserialize($info_save);
foreach ($cart_info_un_sr_save as $user_gift_cart_save) {
$prod_user_id_save = $user_cart_save['prod_id'];
echo $prod_user_id_save . " _ Add This";
//update_post_meta($prod_user_id_save, 'this_product', '1');
}
}
function delete_check_value() {
global $wpdb;
$info_delete = stripcslashes($_REQUEST['cart_info_delete']);
$cart_info_un_sr_delete = unserialize($info_delete);
foreach ($cart_info_un_sr_delete as $user_cart_delete) {
$prod_user_id_delete = $user_cart_delete['prod_id'];
echo $prod_user_id_delete . " _ Delete This";
//delete_post_meta($prod_user_id_delete, 'this_product', '1');
}
}
So when I checked the check box the alert gives me this value 168 _ Add This (this is what I want) but when I unchecked the check box the alert gives me this value 0 (I want this value 168 _ Delete This).
I checked every thing but I got confused that why else condition not give me the right value.
Any suggestions.
Not directly a solution but I can't help thinking there is quite a lot of duplication of code which could be somewhat simplified.
The initial javascript function could be like:
<script type="text/javascript">
jQuery( document ).ready(function() {
jQuery("#purchase").click( function() {
var action=jQuery(this).is(":checked") ? 'save' : 'delete';
var cart_info=jQuery('.cart_info').val();
var data={
action:'value_'+action,
cart_info:cart_info
};
jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', data, function( result ) {
alert( result );
});
}
});
});
</script>
And rather than two distinct functions that share almost the same code you could do:
<?php
function check_value() {
global $wpdb;
$info = stripcslashes( $_REQUEST['cart_info'] );
$cart_info = unserialize( $info );
/* To find the `action` analyse the following */
exit( print_r( $cart_info ) );
foreach( $cart_info as $gift ) {
list( $junk, $action ) = explode( '_', $gift['action'] );
$product = $gift['prod_id'];
echo $product . " _ ".$action." this";
switch( $action ){
case 'save':
update_post_meta($product, 'this_product', '1');
break;
case 'delete':
delete_post_meta($product, 'this_product', '1');
break;
}
}
}
?>
The answer of #RamRaider is good but You can still reduce more code and might be it will work for you as well :)
Here's the jQuery:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("#purchase").click( function() {
// Method variable will be using to define which
// function should trigger later in our PHP
var cart_method = jQuery(this).is(":checked") ? 'save' : 'delete';
var cart_info = jQuery('.cart_info').val();
var data = {
action: 'modify_cart',
cart_method: cart_method,
cart_info: cart_info
};
jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', data, function( result ) {
alert( result );
});
}
});
});
</script>
And then here is our PHP code:
<?php
function modify_cart_func() {
global $wpdb;
// Get method from our jQuery
$method = $_POST['cart_method'];
$info = stripcslashes( $_REQUEST['cart_info'] );
$cart_info = unserialize( $info );
foreach( $cart_info as $gift ) {
// If method is save
if ($method == 'save') {
update_post_meta($gift['product_id'], 'this_product', 1);
// If method is delete
} else if ($method == 'delete') {
delete_post_meta($gift['product_id'], 'this_product', 1);
}
}
}
?>
And finally your ajax call:
<?php
add_action('wp_ajax_modify_cart', 'modify_cart_func');
add_action('wp_ajax_nopriv_modify_cart', 'modify_cart_func');
?>
Hope that makes sense to you ;)
I am not sure if this causes the problem but if you are calling ajax when not logged in it tries to call wp-ajax with action email_values_delete not values_delete which i guess you are trying to call. Of course you might have that action as well for some other functionality.
If that is not the case change this
add_action('wp_ajax_nopriv_email_values_delete', 'delete_check_value');
To this
add_action('wp_ajax_nopriv_values_delete', 'delete_check_value');
You should also add wp_die(); in the end of each php function you are calling via wp-ajax.
Hope this helps.
Edit:
Sorry, it tries to call values_delete but since there is only email_values_delete (for non logged in users) defined I would guess ajax request might return something like 0.
I need help with two things.
First: if I hit empty submit button. It should show me a error.
Second: If there is 0 results, it will give an error.
$(document).ready(function(){
$(".search").click(function(){
$.post("search.php", { keywords: $(".keywords").val() }, function(data){
$("div#search").empty()
$.each(data, function(){
$("div#search").append("- <a href='#?id=" + this.id + "'>" + this.title + "</a><br>");
});
}, "json");
});
});
--
$query = $db->prepare("SELECT `media`.`id`, `media`.`title` FROM `media` WHERE `media`.`title` LIKE :keywords");
$keywords = (isset($_POST['keywords']) === true) ? $_POST['keywords'] : '';
if (empty($keywords) === true) {
$error = 'error';
echo json_encode( $error );
} else {
$query->bindValue(':keywords', '%' . $keywords . '%', PDO::PARAM_STR);
$arr = array();
$query->execute();
while( $row = $query->fetch(PDO::FETCH_ASSOC) ) {
$arr[] = array( "id" => $row["id"], "title" => $row["title"]);
}
echo json_encode( $arr );
}
OK I have painstakingly recreated (jsfiddle does not let you copy/paste) this on my local machine. Your html/js code should look like this:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<input type="text" name="search" class="keywords">
<input type="submit" name="submit" class="search">
<div id="search"></div>
<script>
$(document).ready(function(){
$(".search").click(function(){
$.post(
"search.php",
{ keywords: $(".keywords").val() },
function(data){
$("div#search").empty()
$("div#search").append(data);
},
"json"
);
});
});
</script>
</body>
</html>
And for the PHP search.php page:
<?php
$keywords = (isset($_POST['keywords']) === true) ? $_POST['keywords'] : '';
if (empty($keywords) === true) {
echo json_encode( "error" );
}
else {
// run mysql commands
// if resultset == empty
// echo json_encode( "error" );
echo json_encode( "actual data" );
}
?>
To parse json data in javascript do this:
$.post(
"search.php",
{ keywords: $(".keywords").val() },
function(data) {
$("div#search").empty();
obj = JSON.parse(data);
$("div#search").append(obj.id + " " + obj.title);
},
"json"
);
try using $(this) instead of this
I have this code in my view file (searchV.php):
<html>
<head>
<title>Search Domains</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
function noTextVal(){
$("#domaintxt").val("");
}
function searchDom(){
var searchTxt = $("#searchTxt").val();
var sUrl = $("#url").val();
$.ajax({
url : sUrl + "/searchC",
type : "POST",
dataType : "json",
data : { action : "searchDomain", searchTxt : searchTxt },
success : function(dataresponse){
if(dataresponse == "found"){
alert("found");
}
else{
alert("none");
}
}
});
}
</script>
</head>
<body>
<form id="searchForm">
<input type="text" id="searchTxt" name="searchTxt" onclick="noTextVal()" >
<input type="submit" id="searchBtn" name="searchBtn" value="Search" onclick="searchDom()" />
<input type="hidden" id="url" name="url" value="<?php echo site_url(); ?>" />
</form>
<?php
var_dump($domains);
if($domains!= NULL){
foreach ($domains->result_array() as $row){
echo $row['domain'] . " " . $row['phrase1'];
echo "<br/>";
}
}
?>
</body>
</html>
and below is my controller (searchC.php):
<?php
class SearchC extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('searchM');
}
public function index()
{
$data['domains'] = $this->searchM->getDomains();
$this->load->view('pages/searchV', $data);
switch(#$_POST['action']){
case "searchDomain":
echo "test";
$this->searchDomains($_POST['searchTxt']);
break;
default:
echo "test2";
echo "<br/>action:" . ($_POST['action']);
echo "<br/>text:" . $_POST['searchTxt'];
}
}
public function searchDomains($searchInput)
{
$data['domains'] = $this->searchM->getDomains($searchInput);
$res = "";
if($data['domains']!=NULL){ $res = "found"; }
else{ $res = "none"; }
echo json_encode($res);
}
} //end of class SearchC
?>
Now I've done a test on the controller using switch to check if the json data passed was successful but it's always showing undefined.. What's wrong here? Can someone explain why the data is not recognized in the controller??
You aren't passing the data in via the url, so you need to use $this->input->post() to retrieve the data.
For example,
public function searchDomains()
{
$data['domains'] = $this->searchM->getDomains($this->input->post('searchTxt'));
$res = "";
if($data['domains']!=NULL){ $res = "found"; }
else{ $res = "none"; }
echo $res;
}
I believe that the data is being correctly returned, but the problem is with your code check. The $.ajax function parses the JSON and transforms it into a JavaScript object. Therefore you would need to modify your code as follows:
if(dataresponse.res == "found"){ // Changed from dataresponse to dataresponse.res
alert("found");
}
else{
alert("none");
}
This should work for you.
I m using codeigniter and would like to grab some user info with ajax. This is what I have but it s not working
In the view I have a defined variable:
<script type="text/javascript">
var end_user = "<? echo $user_id; ?>";
</script>
<div id="tabs6"></div>
js file:
function get_experience()
{
$.post(base_url + "index.php/home/get_experience", { user : end_user }, function(data) {
if (data.status == 'ok')
{
$("div#tabs6").html(data);
}
else
{ //nothing }
}, "json");
}
get_experience();
controller:
public function get_experience()
{
$this->load->model('experience_model');
$end_user = $this->input->post('user');
$one_exp = $this->experience_model->one_exp($end_user);
if ($one_exp->num_rows() > 0)
{
$one_exp_html = '<ul>';
foreach($one_exp->result() as $exp)
{
$one_exp_html .= '<li>';
$one_exp_html .= $exp->experience;
$one_exp_html .= '</li>';
}
$one_exp_html .= '</ul>';
$result = array('status' => 'ok', 'content' => $one_exp_html);
return json_encode($result);
exit();
}
else
{
$result = array('status' => 'ok', 'content' => 'nothing here');
return json_encode($result);
exit();
}
}
model:
function one_exp($end_user)
{
$query_str = "SELECT experience FROM exp WHERE user_id = ?";
$query = $this->db->query($query_str, $end_user);
}
You need to add return $query to your one_exp method.
EDIT
You're setting user_id in your view, but then using end_user in your javascript function get_experience().
Also, since it's json you'll need to change the html fill to
$("div#tabs6").html(data.content);
For more debugging add an alert to your callback (right before if (data.status == 'ok') add alert(data);)
You've got to echo the result out I think, not return it.
I am not sure but problem occurs in end_user value in js.Try this oneView File:
<script type="text/javascript">
var end_user = "<? echo $user_id; ?>";
get_experience(end_user);
</script>
<div id="tabs6"></div>
The js file:
function get_experience(foo)
{
$.post(base_url + "index.php/home/get_experience", { user : foo }, function(data) {
if (data.status == 'ok')
{
$("div#tabs6").html(data);
}
else
{ //nothing }
}, "json");
}