Hi there I am trying use some wordpress ajax my first ajax request works fine but the second one does not. Can some one please tell me why this is happening
Works fine:
PHP
//Add Students Details to DB
add_action( 'wp_ajax_my_action', 'my_action_callback' );
function my_action_callback() {
$fName = $_POST['fName'];
$lName = $_POST['lName'];
$dob = $_POST['dob'];
$gender = $_POST['gender'];
$diet = $_POST['diet'];
$current_id = get_current_user_id();
global $wpdb;
$result = $wpdb->insert(
'wp_students',
array(
'ID' => NULL,
'first_name' => $fName,
'last_name' => $lName,
'birthdate' => $dob,
'gender' => $gender,
'dietary_requirements' => $diet,
'user_id' => $current_id
)
);
echo json_encode($result);
wp_die();
}
JS
var data_value = {
action: 'my_action',
fName: $(acc[i]).find('input.fName').val(),
lName: $(acc[i]).find('input.lName').val(),
dob: $(acc[i]).find('input.dob').val(),
gender: $(acc[i]).find('select.gender').val(),
diet: $(acc[i]).find('textarea.diet_req').val()
};
$.ajax({
type: "post",
dataType: "json",
url: my_ajax_object.ajax_url,
data: data_value,
success: function(msg) {
if (msg == false) {
$('#insert_status').html('<strong><span style="color: red;">Error: </span></strong>Details Have Not Been Updated');
return false;
}
},
error: function(xhr, status, error) {
var i = JSON.parse(xhr.responseText)
alert(i.Message);
}
});
Does not work:
PHP
//Delete Students Details
add_action( 'wp_ajax_my_delete', 'my_action_callback_delete' );
function my_action_callback_delete() {
echo 'here';
global $wpdb;
$result = $wpdb->delete( 'wp_students', array( 'usesr_id' => get_current_user_id()) );
echo json_encode($result);
wp_die();
}
JS
var value = {
action: 'my_delete'
};
$.ajax({
type: "post",
dataType: "json",
url: my_ajax_object.ajax_url,
data: value,
success: function(msg) {
if (msg == false) {
$('#insert_status').html('<strong><span style="color: red;">Error: </span></strong>Details Have Not Been Updated');
return false;
}
},
error: function(xhr, status, error) {
var i = JSON.parse(xhr.responseText)
alert(i.Message);
}
});
If you could help me would be great. Wordpress Ajax is not a straight forward as normal ajax.
Could it be that you just have a typo in your delete function?
'usesr_id' => get_current_user_id()
should probably be
'user_id' => get_current_user_id()
//Delete Students Details
add_action( 'wp_ajax_my_delete', 'my_action_callback_delete' );
function my_action_callback_delete() {
echo 'here';
global $wpdb;
$result = $wpdb->delete( 'wp_students', array( 'usesr_id' => get_current_user_id()) );
echo json_encode($result);
wp_die();
}
Related
My ajax function goes in error after I set the dataType to Json.
That's the code:
Ajax script:
$('#da').on("change",function() {
$.ajax({
url: "callAjaxIndex.php",
type: "POST",
dataType: "json",
data: {
method: 1,
id: $('#da').val(),
},
success: function() {
alert('test');
},
error: function() {
alert('error');
}
});
});
callAjaxIndex.php
<?PHP
require('includes/core.php');
if ( isset($_POST['method']) ) {
$sql = "SELECT tratte.nome as 'nome_arrivo', tratte.id as 'id_arrivo' FROM tariffe, tratte WHERE id_arrivo = tratte.id AND id_partenza = '".$_POST['id']."'";
$query = $conn->query($sql);
while ( $tariffe = $query->fetch_array() ) {
$result[] = array(
'id' => $tariffe['id_arrivo'],
'nome' => $tariffe['nome_arrivo']
);
}
echo json_encode($result);
}
?>
What's wrong?
Thank you
You can try this
$(document).on('change', '#da', function(){
$.post("callAjaxIndex.php", {'method': 1, 'id': $(this).val()}, function(data){
var d = $.parseJSON(data); //here is the data parsed as JSON
//data is that returned from callAjaxIndex.php file
});
});
<?php
require('includes/core.php');
if ( isset($_POST['method']) ) {
$sql = "SELECT tratte.nome as nome_arrivo, tratte.id as id_arrivo FROM tariffe INNER JOIN tratte ON id_arrivo = tratte.id WHERE id_partenza = '".$_POST['id']."'";
$query = $conn->query($sql);
while ( $tariffe = $query->fetch_array() ) {
$result[] = array(
'id' => $tariffe['id_arrivo'],
'nome' => $tariffe['nome_arrivo']
);
}
echo json_encode($result);
}
You can find out the error by changing your function to this:
//other code
error: function(data)
{
console.log(data.responseText)
}
//other code
This will tell you why it fails, might be something generic but better than 'error'
Also note:
this was done from a phone so excuse any mistakes
I'd rather this be treated as a comment until I can get to a machine to help more :)
i have this ajax form validation code igniter. my view is something like this
<?php
echo form_open('Provinces/create',array('id' => 'form-user'));
?>
<label for="PROVINCE" class="col-sm-2 control-label col-sm-offset-2">Province Name:</label>
<div class="col-sm-5">
<input type="text" class="form-control" id="PROVINCE" name="PROVINCE" value = "<?= set_value("PROVINCE"); ?>">
</div>
<button class="btn btn-info fa fa-save" type="submit">  Save</button>
<a href = '<?php echo base_url().'Provinces/index'; ?>' class = 'btn btn-danger fa fa-times-circle'>  Cancel</a>
<?php
echo form_close();
?>
and i have this javascript
<script>
$('#form-user').submit(function(e){
e.preventDefault();
var me = $(this);
// perform ajax
$.ajax({
url: me.attr('action'),
type: 'post',
data: me.serialize(),
dataType: 'json',
success: function(response){
if (response.success == true) {
// if success we would show message
// and also remove the error class
$('#the-message').append('<div class="alert alert-success">' +
'<span class="glyphicon glyphicon-ok"></span>' +
' Data has been saved' +
'</div>');
$('.form-group').removeClass('has-error')
.removeClass('has-success');
$('.text-danger').remove();
// reset the form
me[0].reset();
url = "<?php echo site_url('Provinces/ajax_add')?>";
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
alert('success');
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
}else{
$.each(response.messages, function(key, value) {
var element = $('#' + key);
element.closest('div.form-group')
.removeClass('has-error')
.addClass(value.length > 0 ? 'has-error' : 'has-success')
.find('.text-danger')
.remove();
element.after(value)
});
}
}
});
});
</script>
i have found this code on google and just customized it. but the problem is, i am not that familiar with ajax, the part where the form validation fails, work perfectly fine, but when it is succes, even though it shows alert('success'); it doesnt add the value in the database. i need to finish this projects in a few weeks. please help.
here is where i get the validations,
public function create(){
$data = array('success' => false, 'messages' => array());
$this->form_validation->set_rules('PROVINCE','Province Name','trim|required|max_length[30]|callback_if_exist');
$this->form_validation->set_error_delimiters('<p class="text-danger"','</p>');
if($this->form_validation->run($this)){
$data['success'] = true;
}else{
foreach ($_POST as $key => $value) {
# code...
$data['messages'][$key] = form_error($key);
}
}
echo json_encode($data);
}
also here is my ajax_add
public function ajax_add()
{
$data = array(
'PROVINCE' => $this->input->post('PROVINCE'),
);
$insert = $this->Provinces_Model->save($data);
echo json_encode(array("status" => TRUE));
}
and here is my model,
public function save($data)
{
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}
i have solved it. just did put
$data = array(
'PROVINCE' => $this->input->post('PROVINCE'),
);
$insert = $this->Provinces_Model->save($data);
echo json_encode(array("status" => TRUE));
into my controller, which makes my controller
public function create(){
$data = array('success' => false, 'messages' => array());
$this->form_validation->set_rules('PROVINCE','Province Name','trim|required|max_length[30]|callback_if_exist');
$this->form_validation->set_error_delimiters('<p class="text-danger"','</p>');
if($this->form_validation->run($this)){
$data['success'] = true;
$data = array(
'PROVINCE' => $this->input->post('PROVINCE'),
);
$insert = $this->Provinces_Model->save($data);
echo json_encode(array("status" => TRUE));
}else{
foreach ($_POST as $key => $value) {
# code...
$data['messages'][$key] = form_error($key);
}
}
echo json_encode($data);
}
and my javascript
$('#form-user').submit(function(e){
e.preventDefault();
var me = $(this);
// perform ajax
$.ajax({
url: me.attr('action'),
type: 'post',
data: me.serialize(),
dataType: 'json',
success: function(response){
if (response.success == true) {
// if success we would show message
// and also remove the error class
$('#the-message').append('<div class="alert alert-success">' +
'<span class="glyphicon glyphicon-ok"></span>' +
' Data has been saved' +
'</div>');
$('.form-group').removeClass('has-error')
.removeClass('has-success');
$('.text-danger').remove();
// reset the form
me[0].reset();
$('.alert-success').delay(500).show(10, function() {
$(this).delay(3000).hide(10, function() {
$(this).remove();
});
})
}else{
$.each(response.messages, function(key, value) {
var element = $('#' + key);
element.closest('div.form-group')
.removeClass('has-error')
.addClass(value.length > 0 ? 'has-error' : 'has-success')
.find('.text-danger')
.remove();
element.after(value)
});
}
}
});
});
You dont't need to use uppercase when accessing your controller
just use
url = "<?php echo site_url('provinces/ajax_add')?>";
Validation the request data before inserting
try
public function ajax_add()
{
$response = array(
'success' => false
) ;
$this->load->library('form_validation');
// add your validation
$this->form_validation->set_rules('PROVINCE', 'PROVINCE', 'required');
if ($this->form_validation->run() == FALSE)
{
$data = array(
'PROVINCE' => $this->input->post('PROVINCE')
);
$insert = $this->Provinces_Model->save($data);
if($insert){
$response['success'] = TRUE ;
$response['message'] = 'Record created successfully' ;
}
else{
$response['message'] = 'Unable to create record' ;
}
}
else
{
$response['message'] = 'Invalid data' ;
}
echo json_encode($response);
}
Then check for the 'message' index in your ajax response in the javascript code
This will give an idea of where there is problem, whether its from the
view or
controller or'
Model
I have implemented jQuery autocomplete function for my web, which is working fine. But I want the result of the autocomplete to retrieve only the data of a particular person and not the complete database result.
Below is the jQuery for the autocomplete
jQuery(document).ready(function($){
$('.product_desc').autocomplete({source:'functions/products.php?', minLength:2});
products.php
//Path for the databsae
<?php
include '../include/configuration.php';
if ( !isset($_REQUEST['term']) )
exit;
$rs = mysql_query('select id,item_name,fk_vendor_id from item where item_name like "%'. mysql_real_escape_string($_REQUEST['term']).'%" order by item_name asc ', $con);
$data = array();
if ( $rs && mysql_num_rows($rs) )
{
while( $row = mysql_fetch_array($rs, MYSQL_ASSOC) )
{
$data[] = array(
'label' => $row['item_name'],
'value' => $row['item_name']
);
}
}
else
{
$data[] = array(
'label' => 'not found',
'value' =>''
);
}
// jQuery wants JSON data
echo json_encode($data);
flush();
?>
Any solution will be appreciated.
Try this:
$(".product_desc").autocomplete({
source: "functions/products.php",
minLength: 2,
select: function(event,ui){
//do something
}
});
Try this code, Any text field having class .search the auto complete suggestion will works on server side in ajax.php file you need to return array as below:
$response = ['Computer', 'Mouse', 'Keyboard', 'Monitor'];
echo json_encode($response);
Here is sample code for auto suggest.
$(document).on('keyups','.search',function() {
$(this).autocomplete({
source: function( request, response ) {
if (request.term != "") {
$.ajax({
url: "ajax.php",
dataType: "json",
method: "post",
data: {
name: request.term
},
success: function (data) {
if (data != "") {
response($.map(data, function (item) {
var name = item.name;
return {
label: name,
value: name,
data: item
}
}));
}
}
});
}
},
autoFocus: true,
minLength: 2,
select: function( event, ui ) {
var name = ui.item.data;
$(this).val(name);
}
});
});
I am calling a php function from javascript by passing three arguments, on the other side php function inside the php file gets two values from database and prints all the value. for that I have written this code but this is not working, means this code prints nothing in the output so kindly help.
javascript code
jQuery.ajax(
{
type: "POST",
url: 'save.php',
dataType: 'json',
data: {functionname:'saveUser', arguments:["className", "student_id", "isPresent"]},
success: function (obj, textstatus) {
if( !('error' in obj) ) {
alert(obj.result);
}
else {
console.log(obj.error);
}
}
});
php code
<?php
header('Content-Type: application/json');
if( $_POST['functionname'] == 'saveUser' ) {
include_once("dbConnection.inc");
$db = db_connect();
$newSql = "SELECT class_id, date FROM class_session WHERE class_id = (select max(class_id) from class_session)";
$result = mysql_query($newSql, $db);
$row = mysql_fetch_array($result);
$class_id = $row["calass_id"];
$date = $row["date"];
echo json_encode(Array(
'result' => $_POST['arguments'][0] .' '. $_POST['arguments'][1] .' '. $_POST['arguments'][2] .' '. $class_id .' '. $date
));
}
?>
The right property is method not type, see jQuery.ajax()
jQuery.ajax({
method: "POST",
url: 'save.php',
dataType: 'json',
data: {functionname:'saveUser', arguments:["className", "student_id", "isPresent"]},
success: function (obj, textstatus) {
if( !('error' in obj) ) {
alert(obj.result);
}
else {
console.log(obj.error);
}
}
});
I have one form with activated clientValidation, but the JS code to validate the form has not been registered by Yii.
My form code is here:
$form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(
'id' => 'login-form',
'enableClientValidation' => true,
'clientOptions' => array(
'validateOnSubmit' => true,
'afterValidate' => 'js:function(form, data, hasError) {
if (!hasError){
str = $("#login-form").serialize() + "&ajax=login-form";
$.ajax({
type: "POST",
url: "' . Yii::app()->createUrl('/') . '",
data: str,
dataType: "json",
beforeSend : function() {
$("#login").attr("disabled",true);
},
success: function(data, status) {
if (data.authenticated) {
window.location = data.redirectUrl;
} else {
$.each(data, function(key, value) {
var div = "#"+key+"_em_";
$(div).text(value);
$(div).show();
});
$("#login").attr("disabled",false);
}
},
});
return false;
}
}',
),
));
echo $form->textField($model, 'username');
echo $form->passwordField($model, 'password');
echo TbHtml::submitButton('Login', ['id' => 'login']);
$this->endWidget();
The registered JS code is only this:
<script type="text/javascript">
/*<![CDATA[*/
jQuery('body').popover({'selector':'a[rel=popover]'});
jQuery('body').tooltip({'selector':'a[rel=tooltip]'});
/*]]>*/
</script>
I don't see, why its not working. Please help me to find the bug.
The code is from this blog post: http://tahiryasin.wordpress.com/2013/05/23/ajax-based-yii-login-form/