Hi I am getting the following error when I call action in controller from ajax.
Undefined index : value.
This is my code in Document Ready
unique function is to create array of unique elements.
var modules =[];
var action = [];
var max_limit=[];
var details ={};
$(".btn-small").click(function()
{
modules = unique(modules);
action = unique(action);
limit = unique(limit);
details['id'] = id;
details['cost'] = sum;
details['modules'] = modules;
details['action'] = action;
details['limit'] = limit;
jsonString = JSON.stringify(details);
$.ajax({
url: "<?php echo Yii::app()->createUrl('/xxxxxxxx/actionDemo'); ?>",
data: {'value':jsonString },
type: 'post',
dataType:'json',
success: function() {
alert("st");
},
error: function(){
alert("Error: Could not delete");
}
});
This is my code in action in Controller :
public function actionDemo() {
$val = $_POST['value'];
var_dump($val);
die();
}
It means that "value" is not in you post data. Try to dump your POST and see what is going on.
This is probably because you are sending a JSON, so you POST will contain a JSON instead of an Array.
I think this will help you,
If you are sending JSON to server side you need to specify contentType in AJAX request. dataType:'json' says that what kind of response you expect from server.
Or else you can directly pass "data: {'value':details}," in AJAX without converting into JSON.
Related
Hi i don't get retrieve Ajax Data to PhP page its throwing error. i pass data as json object.
The error i'm getting is
Edit.php
$('#regForm').on('submit', function (e) {
var url = document.URL; // Get current url
var id = url.substring(url.lastIndexOf('=') + 1);
var data1 = $("#regForm").serialize();
data = {data:data1,id:id};
console.log(data)
$.ajax({
method:"POST",
url: 'update.php',
dataType : 'json',
data: data,
success: function () {
alert('form was submitted');
}
});
});
update.php
if(isset($_POST["submit"]))
{
print_r($_POST['data']);
// Error::: Undefined index:data in
pass Id using hidden input field and then form data serialize then after you can use by name wise on php page.
$_POST['name'];
Read my comment, then look at this:
JavaScript may look like this
$('#regForm').on('submit', function(e){
var s = location.search.split('&'), serialId = s[s.length-1], idArray = serialId.split('=');
if(idArray.length === 2 && idArray[1].trim() !== '' && idArray[0].match(/^id$/i)){
var serialData = $(this).serialize()+'&'+serialId;
$.ajax({
method:'POST', url:'update.php', dataType:'json', data:serialData},
success:function(jsonObj){
console.log(jsonObj);
}
});
}
e.preventDefault();
});
PHP may look like this
<?php
if($_POST['id']){
// each property as $_POST[propertyHere]
// sending back to JavaScript
$c = new stdClass; $c->someProp = 'some value';
echo json_encode($c); // dataType is json so you should get Object as result
}
?>
When I make an ajax call, I get the ID of my input and I add the id to my json data.
I need to get this id to use it id my success function.
IE : In data id = 1, i need in success to get .qte1
If you have any idea... :)
$('#action-button').click(function() {
$.ajax({
type: 'POST',
url: 'get_qty.php',
data: {
'id': $('input[name=qte]').val(),
},
success: function(data) {
$(".qte").html("");
$(".qte").append(data);
}
});
return false;
});
If I understood you correctly you can just concat the value as such
var data = JSON.parse(data);
var $div = "#qte" + data.id;
$($div).html("test");
I have converted to json object because if you don't have access to the php file this at least converts from string to object. Make sure you are using a #to call a specific div not a class.
This is my PHP:
header('Content-type: application/json');
$arr = array("id"=> $_POST['id'],"qty"=> "1");
echo json_encode($arr);
I am very new to ajax.
What I am trying to do here is bringing back some variables from a PHP file that I've wrote mainly to process a HTML form data into MySql db table.
After some research I concluded that I need to use json (first time) and I must add the part dataType:'json' to my ajax.
My problem is that after adding this part, I am no more able to submitting the form!
Can anyone please let me know what am I doing wrong here?
I just need to process the PHP code and return the three mentioned variables into a jquery variable so I can do some stuff with them.
Thank you in advance.
AJAX:
var form = $('#contact-form');
var formMessages = $('#form-messages');
form.submit(function(event) {
event.preventDefault();
var formData = form.serialize();
$.ajax({
type: 'POST',
url: form.attr('action'),
data: formData,
dataType: 'json', //after adding this part, can't anymore submit the form
success: function(data){
var message_status = data.message_status;
var duplicate = data.duplicate;
var number = data.ref_number;
//Do other stuff here
alert(number+duplicate+number);
}
})
});
PHP:
//other code here
$arr = array(
'message_status'=>$message_status,
'duplicate'=>$duplicate,
'ref_number'=>$ref_number
);
echo json_encode($arr);
The way you have specified the form method is incorrect.
change
type: 'POST',
to
method: 'POST',
And give that a try. Can you log your response and post it here ? Also, check your console for any errors.
If your dataType is json, you have to send Json object. However, form.serialize() gives you Url encoded data. (ampersand separated).
You have to prepare data as json object :
Here is the extension function you can add:
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
Credit goes to : Difference between serialize and serializeObject jquery
I can't access my variables through ajax using php.
AJAX CODE
$("input[name='absent[]'").change(function() {
var obj = $(this); //checkbox
var valueZero = obj.val();
var Code = obj.attr('data-Code');
var value = obj.attr('data-session');
/*var theTR = $(this).parent('tr').children().find('td:eq(0)').addClass('hidden');*/
/* alert( theTR.text());*/
/*$(this).addClass('hidden');*/
$.ajax({
data: "{ code: '"+ Code +"', abt_prt: "+ valueZero +", InOut: "+ value +" }", // need to access these variables in php
type: "post",
dataType:'json',
url: "insertabsent.php",
success: function(){
obj.addClass('hidden');
}
});
});
PHP CODE
<?php
if(isset($_REQUEST))
{
$code = $_POST['code']; //variable
$absent_present = $_POST['abt_prt']; //variable
$session = $_POST['InOut']; //variable
//need this variables to perform a insert query
}
?>
Do try this :
JAVASCRIPT
var mainString = "code="+Code+"&abt_prt="+valueZero+"&InOut="+value;
IN AJAX
data : mainString
PHP
$code = $_POST['code']; //variable
$absent_present = $_POST['abt_prt']; //variable
$session = $_POST['InOut']; //variable
use data like
data: { code:Code , abt_prt : valueZero , InOut : value },
and in php I don't really know what is $_REQUEST is but you can use
if(isset($_POST)){
}
Try changing data variable to:
data: {"code":Code,"abt_prt":valueZero,"InOut":value},
You are misunderstanding how AJAX parameters have to be sent. You do not need to send an index, you can send a simple Javascript object, like this:
$.ajax({
data: { code: Code, abt_prt: valueZero, InOut:value}, // need to access these variables in php
type: "post",
dataType:'json',
url: "insertabsent.php",
success: function(){
obj.addClass('hidden');
}
});
However, if for some reason you want to send a string like you did, then decode it using json_decode.
I am working in Wordpress trying to use an ajax request to fetch user data by passing the user id.
I can see that the user id sends correctly via AJAX POST but I am getting an internal error message and I don't know why.
At first I thought it was because I was trying to fetch some custom fields that I had added to the user profile but even when I simplified my script I am still getting the error message.
Any help is much appreciated!
Front End
$('.author').click(function() {
var id = $(this).attr('id');
var temp = id.split('-');
id = temp[1];
$.ajax({
type: 'POST',
url: 'wp-content/themes/twentyeleven/author_info.php',
data: {id: id},
dataType: 'html',
success: function(data) {
$('#author-bio').html(data);
}
});
return false;
});
author_info.php
$user_id = $_POST['id'];
$forename = get_the_author_meta('user_firstname', $user_id);
$output = $user_id;
echo $output;
Error Message
500 (Internal Server Error) jquery.min.js:4
Mathieu added a hackable approach to intercepting a request and redirecting it, which is fine. I prefer to build out AJAX responses that return json_encoded arrays.
$('.author').click(function() {
var id = $(this).attr('id');
var temp = id.split('-');
id = temp[1];
$.ajax({
url: 'http://absolute.path/wp-admin/admin-ajax.php',
data: {'action' : 'ajax_request', 'fn': 'getAuthorMeta', 'id': id},
dataType: 'json',
success: function(data) {
//We expect a JSON encoded array here, not an HTML template.
}
});
return false;
});
Now we build out the function to handle our ajax requests.
First, we need to define our ajax add_action method ->
add_action('wp_ajax_nopriv_ajax_request', 'ajax_handle_request');
add_action('wp_ajax_ajax_request', 'ajax_handle_request');
We need to use both add_action lines here. I won't get into why. You'll notice the _ajax_request here. This is the 'action' that we sent over in our AJAX function data: {'action' : 'ajax_request'}. We use this hook to validate our AJAX request, it can be anything you'd like.
Next, we'll need to build out or function ajax_handle_request.
function ajax_handle_request(){
switch($_REQUEST['fn']){
case 'getAuthorMeta':
$output = ajax_get_author_meta($_REQUEST['id']);
break;
default:
$output = 'That is not a valid FN parameter. Please check your string and try again';
break;
}
$output = json_encode($output);
if(is_array($output)){
return $output;
}else{
echo $output;
}
}
Now let's build our function to actually get the author meta.
function ajax_get_author_meta($id){
$theMeta = get_the_author_meta([meta_option], $id);
return $theMeta;
}
Where [meta_option] is a field provided by WP's native get_the_author_meta function.
At this point, we'll now go back to our success:function(data) and (data) is a reference to the json_encoded array we've returned. We can now iterate over the object to get our fields and output them into the page as you'd like.
You are not in a POST at that moment because you are calling a specific page of your template that probably doesn't correspond to any article in your blog.
Instead, create a pluggin that will do this:
add_action('template_redirect', 'my_author_meta_intercept');
function my_author_meta_intercept(){
if(isset($_POST['getAuthorMeta'])){
echo get_the_author_meta('user_firstname', $_POST['getAuthorMeta']);
exit();
}
}
This will short circuit the request to the same page as before when you call it using:
http://mysite/mycurrenturl?getAuthorMeta=testMetaKey
So calling that post normally will return the article as usual, but if you pass in ?getAuthorMeta, it will stop the template from being selected and simply return the exact content you want it to return.
In your page, you just have to change your javascript to:
$('.author').click(function() {
var id = $(this).attr('id');
var temp = id.split('-');
id = temp[1];
$.ajax({
type: 'POST',
url: window.location.href,
data: {getAuthorMeta: id},
success: function(data) {
$('#author-bio').html(data);
}
});
return false;
});
Just make sure you adapt the concept to what you need!
I would rather recommend you to use WP AJAX action method.
As in your case, add the following to your functions.php file.
add_action('wp_ajax_get_user_info', 'ajax_get_user_info');
add_action('wp_ajax_nopriv_get_user_info', 'ajax_get_user_info');
function ajax_get_user_info() {
//Handle request then generate response using WP_Ajax_Response or your html.
}
then in javascript tag.
$('.author').click(function() {
var id = $(this).attr('id');
var temp = id.split('-');
id = temp[1];
jQuery.post(
ajaxurl, /* if you get error of undefined ajaxurl. set it to "http://example.com/wordpress/wp-admin/admin-ajax.php"*/
{
'action':'get_user_info',
'user_id':id
},
function(response){
alert('The server responded: ' + response);
}
);
});
I would recommend you to read the 5 tips for using AJAX in WordPress.
p.s; Code above is not tested, it may have errors. but you get the idea.