Serialize Data with AJAX and call action in Wordpress - 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);

Related

Can not update data with ajax on codeigniter

I tried to update the data with ajax on php but it went wrong while ajax information has been successful but the data is not updated, I think the script is correct but do not want to update the data, what is wrong with my script ??
<input type="hidden" id="select_id" name="select_id" value="<?php echo $read_inbox['id_data']; ?>" />
$('[id^=delete_read_inbox]').click(function() {
if (confirm('You are sure to delete this message?')) {
var id = $("#select_id").val();
var url = base_url+'message/delete_inbox_read';
$.ajax({
url : url,
type: 'POST',
data: 'select_id='+id,
success: function(response) {
console.log('success');
},
error: function (request, jqXHR, textStatus, errorThrown) {
console.log(request.responseText);
}
});
} else {
}
});
Controllers
function delete_inbox_read() {
$this->Message->delete_ReadInbox();
redirect('user/message/inbox');
}
Models
function delete_ReadInbox() {
$update = $this->input->post('select_id');
$data = array(
'delete_pa_inbox' => 0
);
$this->db->where('id_Message', $update);
$this->db->update('tb_message', $data);
}
you are trying to POST 'id' from js and fetching 'select_id' on PHP side, hence its not working, change to:
...
var id = $("#select_id").val();
var url = base_url+'message/delete_inbox_read';
$.ajax({
url : url,
type: 'POST',
data: { 'id' : id },
success: function(response) {
console.log('success');
},
....
Controller:
function delete_inbox_read() {
//get the POST data
$select_id = $this->input->post('id'); //id not select_id
$this->Message->delete_ReadInbox($select_id);
//redirect('user/message/inbox'); //remove redirect
echo "done";
}
Model:
function delete_ReadInbox($select_id) {
$data = array(
'delete_pa_inbox' => 0
);
$this->db->where('id_Message', $select_id);
$this->db->update('tb_message', $data);
}

Success not being returned from ajax post

AJAX Post is not returning success call in wordpress. I have the following code and I can get to the first dialog box in testing, but no mater what I do its not getting to the second. It's not finding the function in functions.php even though I have it declared.
jQuery(document).ready(function(){
jQuery("#send_btn").click(function(){
var datastring = $("#redemmpointsForm").serialize();
var points = $('#points').val();
var comments = $('#comments').val();
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {"action": "redeempoints", "points":points},
success: function(response) {
if(response.type == "success") {
alert('do i get here');
}
else {
// Do something else
}
}
});
});
}); //Modal event Ends
functions.php file
wp_localize_script( 'inkthemes', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php')));
function functionRedeempoints() {
die();
return true;
}
add_action("wp_ajax_functionRedeempoints", "functionRedeempoints");
add_action("wp_ajax_nopriv_functionRedeempoints", "functionRedeempoints");
Ok so i treid the following
jQuery(document).ready(function(){
jQuery("#send_btn").click(function(){
var points = jQuery('#points').val();
var comments = jQuery('#comments').val();
var allData = {
action: 'functionRedeempoints',
points: points,
comments:comments
}
var data = JSON.stringify(allData);
alert( data);
jQuery.ajax({
type : "post",
dataType : 'json',
url : myAjax.ajaxurl,
data : data,
success: function(response) {
if(response.success) {
alert('do i get here');
}
else {
// Do something else
}
}
});
});
}); //Modal event Ends
And iN MY FUCNTIONS php Its like its not fidning the php function.
wp_localize_script( 'inkthemes', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php')));
function functionRedeempoints() {
wp_send_json_success(true);
}
add_action("wp_ajax_redeempoints", "functionRedeempoints");
add_action("wp_ajax_nopriv_redeempoints", "functionRedeempoints");
The problem is that your function functionRedeempoints does not return anything that the ajax call can handle.
It just dies even before the return statement.
Also a return by the PHP end will never actually be interpreted by the JS. JS can only read from the http request, so you need to actually write to it by an echo statement.
Wordpress provides a convenient way of handling this for you:
What you need would be something like:
function functionRedeempoints() {
wp_send_json_success(true);
}
This already takes care of stopping execution and properly JSON encoding your response.
Also the correct response handling on the JS side is a little different than in your example code.
You can find the details on this here:
https://codex.wordpress.org/Function_Reference/wp_send_json_success
But what it boils down to is that the success is encoded in the result.success property of the response.
Hence you want your check to be
if(response.success)
instead of if(response.type == "success")
With these changes your example should work though :)
Working example ( in plugin form) based on your code:
Put this in hello.php in the plugins folder
<?php
/*
Plugin Name: Ajax demo
*/
function test_load_js() {
wp_register_script( 'ajax_demo', plugins_url( 'hello.js' ), array( 'jquery' ) );
wp_localize_script( 'ajax_demo', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script( 'ajax_demo' );
}
function functionRedeempoints() {
wp_send_json_success( true );
}
add_action( "wp_ajax_functionRedeempoints", "functionRedeempoints" );
add_action( "wp_ajax_nopriv_functionRedeempoints", "functionRedeempoints" );
add_action( "init", "test_load_js" );
if ( ! defined( 'DOING_AJAX' ) ) {
echo '<input type=button value="send" id="send_btn">';
}
Put this in hello.js in the plugins folder
jQuery(document).ready(function () {
jQuery("#send_btn").click(function () {
var points = jQuery('#points').val();
var comments = jQuery('#comments').val();
var data = {
action: 'functionRedeempoints',
points: points,
comments: comments
};
alert(JSON.stringify(data));
jQuery.ajax({
type: "post",
dataType: 'json',
url: MyAjax.ajaxurl,
data: data,
success: function (response) {
if (response.success) {
alert('do i get here');
}
else {
// Do something else
}
}
});
});
});
Hope this helps you to get a start here, works just fine when you click the button that should appear on the upper left of your admin screen ( zoom in ;) )

add php variable into wordpress mysql query

I am trying to insert into DB data from an ajax query. When I test the function with simple text it works :
array('reference_id'=> 'test'),
array('checkin_time'=> 'test'),
but my PHP variables do not while they are correct (tested by alert(), they are both strings)
array('reference_id'=> $calendartime),
array('checkin_time'=> $reference_id),
Here is the full code in my template functions.php:
wp_enqueue_script('jquery');
wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
function addCheckin(){
global $wpdb, $calendartime, $reference_id;
$calendartime = $_POST['calendar_time'];
$reference_id = $_POST['reference_id'];
if($wpdb->insert('checkin',
array('reference_id'=> $calendartime),
array('checkin_time'=> $reference_id),
array( '%s'),
array( '%s') )===FALSE){
echo "Error";
}else {}
die();
}
add_action('wp_ajax_addCheckin', 'addCheckin');
add_action('wp_ajax_nopriv_addCheckin', 'addCheckin');
And the jquery :
$.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
data:{
action: addCheckin,
reference_id: $('.reference input').val(),
calendar_time: calendar
},
success: function(response) {
alert(response);
},
error: function(){
alert("failure");
}
});
Thanks for your help
Your WordPress Insert seems to be wrong. It should be:
$wpdb->insert('checkin',
array('reference_id' => $calendartime,
'checkin_time' => $reference_id),
array( '%s', '%s') )
I also think your AJAX post JavaScript should be like:
$.post( MyAjax.ajaxurl, {
data:{
action: addCheckin,
reference_id: $('.reference input').val(),
calendar_time: calendar
},
success: function(response) {
alert(response);
},
error: function(){
alert("failure");
}
});
Update : I added the following code to my theme header.php (It was for a page using Contact Form 7) :
<script type='text/javascript' src='/wp-content/plugins/contact-form-7/includes/js/jquery.form.min.js?ver=3.40.0-2013.08.13'></script>
<script type='text/javascript'>
/* <![CDATA[ */
var _wpcf7 = {"loaderUrl":"\/wp-content\/plugins\/contact-form-7\/images\/ajax-loader.gif","sending":"Sending ..."};
/* ]]> */
</script>
<script type='text/javascript' src='/wp-content/plugins/contact-form-7/includes/js/scripts.js?ver=3.5.2'></script>
and now it works with the following code :
var data = {
'action': 'form',
'reference_id': $('.reference input').val(),
'calendar_time': calendar
};
$.post( form.ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
Hope it will help

How can json with variable jquery wordpress

I'm having a problem with passing variables in PHP to jQuery via AJAX.
My code PHP is:
function obtieneurl($args, $instance){
extract( $args );
$valorjson = apply_filters('', $instance['value']);
$variableurl = "http://api.openweathermap.org/data/2.5/weather?q=".$valorjson;
return $variableurl;
}
File Weather-ajax-js.js:
jQuery(document).ready(function() {
jQuery.ajax({
type: 'json',
url: '/wp-admin/admin-ajax.php',
data:{
'action':'obtieneurl'
},
dataType: 'html',
success:function(data){
alert(data);
},
error: function(errorThrown){
alert('error');
console.log(errorThrown);
}
});
});
What is the problem?
the function needs to be changed to receive the data from ajax as data is not passed to the function arguments.
function obtieneurl(){
$args= $_POST['action']; // or whatever your method is in your ajax call
extract( $args );
$valorjson = apply_filters('', $instance['value']);
$variableurl = "http://api.openweathermap.org/data/2.5/weather?q=".$valorjson;
return $variableurl;
}

AJAX & JSON not working, no error or success handlers

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.

Categories