I am using Ajax to post my data, while using inspect elemet, I can see the post data from all other fields, but text area field comes empty, so the data fails to be saved to the database.
function addblog() {
save_method = 'add';
url = "<?php echo site_url('index.php/blog/post_new_blog')?>";
$.ajax({
url: url,
type: "POST",
data: $('#addblog').serialize(),
dataType: "json",
success: function (data) {
alert('Saved');
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error adding / update data');
}
});
}
HTML:
<div id="editor-one" class="editor-wrapper"></div>
<textarea id="descr" class="text" name="desc" style="display:none;"></textarea>
PHP:
public function post_new_blog()
{
$data = array(
'blog_title' => $this->input->post('title', true),
'blog_content' => $this->input->post('desc', true),
'blog_tags' => $this->input->post('tags', true),
);
$insert = $this->main_model->save_new_posts($data);
echo json_encode(array("status" => TRUE));
}
You are sending data as follows:
data: $('#addblog').serialize(),
does your
<textarea id="descr" class="text" name="desc" style="display:none;"></textarea>
inside html element with id addblog?
Meanwhile, i didn't understand why you set display to none for textarea?
Related
I'm doing a project on WordPress and I'm having some trouble with the auto-complete field on my form. No input is shown and no error in console. I created a small database on one of the WordPress database. I'm not very familiar with AJAX so please be kind :)
jQuery(document).ready(function($) {
jQuery('#dish').autoComplete({
source: function(name, response) {
jQuery.ajax({
type: 'POST',
dataType: 'json',
url: 'wp-admin/admin-ajax.php',
data: 'action=get_listing_names&name='+name,
success: function(data) {
response(data);
}
});
}
});
});
This is my jQuery code and I added the admin-ajax in the same folder as I was thinking it didn't find it (it's my_serach.js)
function ajax_listings() {
global $wpdb; //get access to the WordPress database object variable
//get names of all businesse
$name = $wpdb->esc_like(stripslashes($_POST['name'])).'%'; //escape for use in LIKE statement
$sql = "select name
from $wpdb->global
where name like %s
and post_type='portfolio' and post_status='publish'";
$sql = $wpdb->prepare($sql, $name);
$results = $wpdb->get_results($sql);
//copy the business titles to a simple array
$titles = array();
foreach( $results as $r )
$titles[] = addslashes($r->name );
echo json_encode($titles); //encode into JSON format and output
die(); //stop "0" from being output
i add this code on the functions.php on the theme i'm working on
<form method = "POST">
<div id = "container">
<div><label class="plate_label">Dish:</label><input type="text" name="dish_name[]" id="dish" class="dish" placeholder="Enter plate name" />
<label class="quantity_label">Quantity:</label><input type="text" name="dish_quantity[]" class="quantity" placeholder="Enter gram or pieces/slices" /></div>
</div>
and last the form where it should show the suggestions from the database.
Try this code.
jQuery(document).ready(function($) {
jQuery('#dish').autoComplete({
source: function(name, response) {
jQuery.ajax({
type: 'POST',
dataType: 'json',
url: 'http://caloriless.com/wp-admin/admin-ajax.php',
data: 'action=get_listing_names&name='+name,
success: function(data) {
response(data);
}
});
}
});
});
change ajax url url: 'wp-admin/admin-ajax.php', or url: 'http://caloriless.com/wp-admin/admin-ajax.php',
I've followed some tutorials on how Wordpress interacts with Ajax and I've tried to build a frontend form for my users. Starting with my html:
<form id="myform" action="" method="post" enctype="multipart/form-data">
<div id="apf-response" style="background-color:#E6E6FA"></div>
<input type="text" name="title" id="title" value="titlevalue">
<input type="text" name="description" id="description" value="descvalue">
//other inputs
<input type="submit" class="submit" value="Publish"/>
</form>
I've registered and localizd my script
function apf_enqueuescripts()
{
wp_enqueue_script('apf', APFSURL.'/js/apf.js', array('jquery'));
wp_localize_script( 'apf', 'apfajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
add_action('wp_enqueue_scripts', apf_enqueuescripts);
I've created wp_ajax_priv and wp_ajax_nopriv functions like:
function apf_addpost() {
get_currentuserinfo();
$uid = $current_user->ID;
$results = '';
$project_title = $_POST['title'];
$project_description = $_POST['description'];
$pid = wp_insert_post( array(
'post_title' => $project_title,
'post_content' => $project_description,
'post_status' => 'publish',
'post_author' => $uid,
'post_type' => 'project',
) );
if ( $pid != 0 )
{
$results = '*Post Added';
}
else {
$results = '*Error occurred while adding the post';
}
// Return the String
die($results);
}
add_action( 'wp_ajax_nopriv_apf_addpost', 'apf_addpost' );
add_action( 'wp_ajax_apf_addpost', 'apf_addpost' );
and I've writtend this very simple ajax function which is not working:
$(document).ready(function(){
msform_init(); //validation function which I'm not showing but it's working
$('#myform').submit(function(event){
event.preventDefault();
apfaddpost(); // which is my below ajax function
})
})
function apfaddpost() {
jQuery.ajax({
type: 'POST',
url: apfajax.ajaxurl,
action: 'apf_addpost', //where I should send data and trigger the php
data: $('#myform').serialize(),
success: function(data, textStatus, XMLHttpRequest) {
var id = '#apf-response';
jQuery(id).html('');
jQuery(id).append(data);
resetvalues();
},
error: function(MLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
It's obvious that I'm wrong but I can't see the error. I guess I'm serializing data and calling the action very badly but I don't know how to fix it. I'm not an expert as you can see. Thanks in advance.
My objective was to serialize many input values without writing all keys : values. I don't know if this is a good practice but I've fixed after many tries like this:
function apfaddpost() {
var formData = $('#msform').serialize(); //serialized
jQuery.ajax({
type: 'POST',
url: apfajax.ajaxurl,
data: formData + '&action=apf_addpost', //this was the problem
success: function(data, textStatus, XMLHttpRequest) {
var id = '#apf-response';
jQuery(id).html('');
jQuery(id).append(data);
resetvalues();
},
error: function(MLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
If there are better methods please share them, I'm beginner and I'm not really aware of potential issues.
Thanks.
The way in which wordpress does things tends to be confusing sometimes.
Try writing your javascript in the following manner:
(function($){
# assuming you have a lot of code before this line.
msform_init();
$('#myform').submit(function(event){
event.preventDefault();
apfaddpost(); // which is my below ajax function
});
function apfaddpost() {
$.post(apfajax.ajaxurl, {
action: 'apf_addpost', //where I should send data and trigger the php
title: $('#title').val(),
description: $('#description').val()
}, function(response) {
var id = '#apf-response';
$(id).html('');
$(id).append(response);
resetvalues();
});
}
})(jQuery);
I'm working on a web application which was not developed by me and I have the following autocomplete code which works with an AJAXcall:
$("#tags").autocomplete({
minLength: 2,
source: function (request, response) {
$.ajax({
url: "http://lainz.softwebsrl.it/ajax/autocompletecibo",
dataType: "json",
crossDomain: true,
type : 'post',
data:{
valore: request.term,
},
success: function (data) {
response(data);
console.log(data);
}
});
}
and below in the file I have:
<div class="div1" style="float: left">
<strong>Cerca Prodotto</strong><br/><br/>
<form class="form">
<div>
<input type="text" id="tags" value="">
</div>
<div>
<img class="btnaggiungi" src="http://lainz.softwebsrl.it/img/carrello.jpg" alt="Aggiungi" id="add_newProduct"/>
</div>
</form>
</div>
The problem is that I don't understand how to access the received JSON from PHP. PHP queries MySQL and in the end performs this:
$ris2 = array();
foreach($ris as $single)
{
$value = $single["cibo"];
$category = $single["categoria"];
$id = $single["id"];
$ris2[] = array(
"value" => $value,
"id" => $id,
"category" => $category
);
}
$valuesJson = Zend_Json::encode($ris2);
echo $valuesJson;
Where in $ris contains the result of the query with fetchAll(). How can I access value, id, category when the AJAX terminates? Where are they?
Check 'data' value in a callback function, success.
success: function (data) {
response(data);
console.log(data);
}
If type of data value is object,
console.log(typeof data, data.id, data.value);
If data is not expected value, check on a XHR response data of Chrome development networks tabs.
I am writing code to test AJAX image and data upload. However, the Ajax seems to return an error stating that the input is not valid:
Syntax error: unexpected end of input
The script and HTML are as follows
<input type="file" name="vdofile" id="file" />
<input type="text" id="name" />
<button id="send">Send</button>
$("#send").click(function(){
var form = new FormData();
form.append('vdofile',$("#file").prop("files")[0]);
form.append('name', $("#name").val());
$.ajax({
url: 'upload.php',
type: "POST",
data: form,
dataType: 'json',
contentType: false,
processData: false,
success: function(data)
{
alert(data.message);
},
error: function(xhr, status, error)
{
alert('An error occured.. ' + xhr.responseText + '..' + error );
}
});// ajax
}); // function
The test PHP is as follows:
header("Content-Type: application/json");
if(isset($_FILES['vdofile']) && isset($_POST['name']))
{
$result = array(
'message' => 'both data and file received'
);
}
else {
$result = array(
'message' => 'one of parameter missing'
);
}
return json_encode($result);
Your PHP is returning an empty response. return doesn't print anything.
print json_encode($result);
should work better.
I have some code which I plan on adding into a Magento store, once I have made it work on a test page, but unfortunately it isn't working on the test page.
The Javascript is as follows:
function plusAddToCart(qty_textbox_id, prodID, highlight_div_id){
var qty = document.getElementById(qty_textbox_id).value;
qty = parseInt(qty) + 1;
document.getElementById(qty_textbox_id).value = qty;
if(qty==0){
$(highlight_div_id).style.backgroundColor = "#f7e9f4";
}else{
$(highlight_div_id).style.backgroundColor = "#ebcde5";
}
$.ajax({
url: "addtocart.php",
data: "prodID="+prodID,
type: "POST",
dataType: 'json',
success: function(data) {
alert("DONE");
}
});
}
</script>
<div style="width:70px; margin:9px auto 0 auto;">
<input type='button' name='plus' onclick='plusAddToCart("qty1", "693", "product_highlight_693");' id="plus" class="cart-plus-minus" value='+'/>
<input name="qty" type="text" id="qty0" readonly="readonly" maxlength="5" value="0" class="quantity-box" />
</div>
PHP:
header("Content-Type: text/html");
require_once 'app/Mage.php';
Mage::app("default");
Mage::getSingleton("core/session", array("name" => "frontend"));
$session = Mage::getSingleton("customer/session");
$userData=Mage::helper('customer')->getCustomer()->getData();
$cart = Mage::getSingleton('checkout/cart');
$yourProId = $_POST['prodID'];
$qty=1;
$params = array( 'product' => $yourProId, 'related_product' => null, 'qty' => $qty );
$product = new Mage_Catalog_Model_Product();
$product->load($yourProId);
$cart->addProduct($product, $params);
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
$message = ('Your cart has been updated successfully.');
Mage::getSingleton('checkout/session')->addSuccess($message);
Can anybody see a reason why this wouldn't work??
The first step would be to add an error handler to your AJAX call:
$.ajax({
url: "addtocart.php",
data: "prodID="+prodID,
type: "POST",
dataType: 'json',
success: function(data) {
alert("DONE");
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Not done - ' + textStatus + ' ' + errorThrown);
}
}
This should give you a better indication of any problems.
Update
In your specific case, I think the problem is a combination of:
Setting the response dataType to 'JSON'
The web service doesn't return any content
I think the request may succeed, but when jQuery attempts to parse the JSON, the empty response cannot be parsed. If you change dataType to text you may avoid this problem as it won't attempt any parsing.