AJAX & JSON not working, no error or success handlers - php

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.

Related

TextArea not sending data on Submit

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?

Serialize Data with AJAX and call action in Wordpress

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);

Ajax Error: "Unexpected end of input"

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.

JSON/AJAX still displays error

Background
I have a web application which displays "simple" information about an account, i.e. Name and account Number.... I have a button on the side to display "detailed" information... i.e Name, Acct# and Phone#.
The system needs to pull the information dynamically upon clicking this button, and will populate into specified div's... What am I doing wrong in this case, because I am constantly receiving the alert with "Error Loading Information". Edit: -Changed error alert to alert(textStatus) - Now all I have is "error" in the alert box....
JS/Ajax
$('.view_information').click(function(e) {
//On Clicking the function, dynamically load the data for the viewing
var dataObj = {};
dataObj["id"] = $(this).data('id');
dataObj["action"] = "get"; // "get" or "set"
$.ajax({
url: 'view_agency_info.php',
type: 'POST',
data: dataObj,
dataType: 'json',
success: function(data){
/* Doesn't Work....*/
$('.view_id').html(data.id);
$('.view_name').html(data.name);
$('.view_account').html(data.account);
$('.view_phone').html(data.phone);
/*Also Doesn't work...
$('.view_id').html(data.message['id']);
$('.view_name').html(data.message['name']);
$('.view_account').html(data.message['account']);
$('.view_phone').html(data.message['phone']);*/
},
error: function(jqXHR, textStatus, errorThrown){
// alert('Error Loading Information');
alert(textStatus);
}
});
JSON
<?php
include_once('customer.class.php');
$customer = new Customer();
$query = "SELECT * FROM table WHERE id=$id LIMIT 1"; //expecting one row
try {
$result = $customer->runQuery($query); //class function with fetchAll
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
$message = array(
'id' => $id,
'name' => $result[0]['agency_name'],
'account' => $result[0]['account_number'],
'phone' => $result[0]['phone']
);
}
print json_encode($message);
?>
It appears I was able to fix the syntax to get it operable.... Had to do with passing the array into json to execute.
I changed the JS/AJAX to:
/* Old Variable Definitions
//var dataObj = {};
//dataObj["id"] = $(this).data('id');
//dataObject["column"] = $(this).data('column');
//dataObj["action"] = "get"; // "get" or "set"*/
/* New Syntax: */
var data_id = $(this).data('id');
var data_action = "get";
var column_toact_on = $(this).data('column');
$.ajax({
url: 'view_agency_info.php',
type: 'POST',
//data: dataObj, // OLD array
data: {id : data_id, action: data_action, column: column_toact_on},
dataType: 'json',
success: function(data){
alert("Wooptee Doo Basil!");}

Receive PHP parameters with jQuery ajax post

I am sending data via jQuery's .ajax method to my PHP file. Both files are on the same domain. The file making the post looks like this..
$('#pdf').click(function() {
var proj_name = $('#proj_name').text();
var date = $('#date').text();
var req_comp_date = $('#req_comp_date').text();
var status = $('#status').text();
var secondUserID = $('#secondUserID').text();
var postData = {
"proj_name" : proj_name,
"date" : date,
"req_comp_date" : req_comp_date,
"status" : status,
"secondUserID" : secondUserID,
};
console.log(postData);
$.ajax({
type: "POST",
url: "test.php",
data: postData,
success: function(){
alert(proj_name + ' ' + status);
window.open("test.php");
}
});
});
And the PHP file getting the post data is...
//request parameters
$proj_name = $_POST['proj_name'];
$date = $_POST['date'];
$req_comp_date = $_POST['req_comp_date'];
$status = $_POST['status'];
$secondUserId = $_POST['secondUserId'];
echo 'postData: ' . var_dump($_POST);
if ($_POST)){
echo $proj_name;
echo $date;
echo $req_comp_date;
echo $status;
echo $secondUserId;
} else {
echo 'problem';
}
In my firebug console, I can see that the parameters posted with .ajax, but I cannot get the post via PHP. Can anyone help me out please? Thank you.
Add the error callback to your to your $.ajax call to debug if the request is failing.
$.ajax({
type: "POST",
url: "test.php",
data: postData,
success: function(){
alert(proj_name + ' ' + status);
window.open("test.php");
},
// Alert status code and error if fail
error: function (xhr, ajaxOptions, thrownError){
alert(xhr.status);
alert(thrownError);
}
});
Update
Change this:
if ($_POST)){
echo $proj_name;
echo $date;
echo $req_comp_date;
echo $status;
echo $secondUserId;
} else {
echo 'problem';
}
To this:
if ($_POST)){
// Make a array with the values
$vals = array(
'proj_name' => $proj_name,
'date' => $date,
'req_comp_date' => $req_comp_date,
'status' => $status,
'secondUserId' => $secondUserid
);
// Now we want to JSON encode these values to send them to $.ajax success.
echo json_encode($vals);
exit; // to make sure you arn't getting nothing else
} else {
// so you can access the error message in jQuery
echo json_encode(array('errror' => TRUE, 'message' => 'a problem occured'));
exit;
}
Now in your jQuery .success callback:
success: function(data){ // Our returned data from PHP is stored in "data" as a JSON Object
alert(data.req_comp_date); // access your returned vars like this.
// data.date; // is your posted date.. etc
alert(data.proj_name + ' ' + data.status);
window.open("test.php");
// You can also get your error message like so..
if(data.error) // if its true, we have a error, so display it.
alert('ERROR: ' + data.message);
},
You dont really have to do this next bit (jquery does a good job of determining the data type returned), but its nice to have it in the code to understand what is being returned.
$.ajax({ ...
type: "POST",
url: "test.php",
data: postData,
dataType: "json" // <-- Add this to tell jquery, we are being returned a JSON object.
.... });

Categories