Undefined index: Error in ajax POST and/or php script? - javascript

I'm trying to send an ajax POST to a php file, however the php file sends a notice of "undefined index", and the php file never seems to receive the value i'm trying to send it. I've been searching for the answer to why this isn't working correctly, so hopefully someone can give me some insight.
My javascript function receives a value from the html, and receives the correct value. (it's "1" in this case)
function deleteMediaFromDatabase(val)
{
$.ajax({ url: 'deleteMediaFromDatabase.php',
data: {vals : val},
type: 'post',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: Could not delete");
}
});
}
Here is part of my php file that should receive the post:
<?php
ini_set("display_errors", "On");
error_reporting(E_ALL);
$val = $_POST["vals"];
// create connection
$con = mysqli_connect(<stuff you don't care about>);
error_log($val . ' is the value', 3, "./error.log");
?>
I am, however getting this error message from php:
Notice: Undefined index: vals in
/xxx/xxx/htdocs/AdminPanel/deleteMediaFromDatabase.php on line 9
And my javascript always outputs the alert in the error: "Error: Could not delete"
I know this question has been asked and answered many times, however unless I'm skipping over something small, my code, to me, looks correct. (but doesn't it always...)

There is error in syntax of jquery.. You missed out syntax of data. This should be like this-
function deleteMediaFromDatabase(val)
{
$.ajax({ url: 'deleteMediaFromDatabase.php',
data: {'vals' : val},
type: 'post',
dataType:'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: Could not delete");
}
});
}

The problem can come from the dataType not being specified or that the dataType specified does not match thus returned by the server.
Explicitely set the dataType, e.g.
dataType:'json'
and make sure that your script returns data that is "encoded" in the data type that you chose, e.g. in PHP:
echo json_encode($something);

Instead of:
$val = $_POST["vals"];
use this:
if (isset($_POST['vals']) {
$val = $_POST['vals'];
}

Change Ajax syntax...
$.ajax({
type: "POST",
url: 'deleteMediaFromDatabase.php',
data: {'vals' : val},//Have u tried this
success: function(output) {
alert(output);
}
error: function(request, status, error){
alert("Error: Could not delete");
}
);

$val = $_POST["vals"];
I got same problem , i tried declaring the variable as global , that solved my problem.
global $val;
$val = $_POST["vals"];
and always check isset($_POST["vals"])

Related

i can't pass a json object from my php to my jquery

I tried to pass a json object from my test.php to my jquery in index.html but i can't.
here is my test.php script:
<?php
if(isset($_POST["view"]))
{
$output .= '
<li>No Notification Found</li>
';
$total_row=2;
$data = array(
'notification' => $output,
'unseen_notification' => $total_row
);
echo json_encode($data);
}
?>
and here is my jquery script , "the alert in js show undefined as result":
function load_unseen_notification(view = '')
{
$.ajax({
url:"test.php",
method:"POST",
data:{view:view},
dataType:"json",
complete:function(data)
{
alert(data.notification);
$('.dropdown-menu').html(data.notification);
if(data.unseen_notification > 0)
{
$('.count').html(data.unseen_notification);
}
}
})
}
In PHP, you need to put a header response from the server so that the browser knows what it got in response (see: https://www.iana.org/assignments/media-types/media-types.xhtml , http://php.net/manual/en/function.header.php):
<?php
header("Content-Type: application/json");
In JavaScript, you need to use success event:
$.ajax({
url: "test.php",
method: "POST",
data: {
view: 10
},
dataType: "json",
success: function(data) {
alert(data.notification);
}
});
success - A function to be called if the request succeeds.
Arguments: ( Anything data, String textStatus, jqXHR jqXHR ).
complete - A function to be called when the request finishes (after success and error callbacks are executed).
Arguments: ( jqXHR jqXHR, String textStatus )
Documentation: http://api.jquery.com/jquery.ajax/
If to use complete, then access to data can be got by means of jqXHR Object (see: http://api.jquery.com/jQuery.ajax/#jqXHR):
complete: function(jqXHR) {
if (typeof jqXHR.responseJSON !== 'undefined') {
alert(jqXHR.responseJSON.notification);
}
}
Of course if necessary it is possible to combine different event handlers.
P.S. For debugging use console.log(data) instead of alert(data) and look through the log in the browser. For example, for Google Chorme (F12, Tab: Logs): https://developers.google.com/web/tools/chrome-devtools/console/get-started
It might be a good idea as well to set the content-type header at the top of your PHP script:
<?php
header("Content-Type: application/json");
jQuery will probably interpret the body as JSON instead of 'text'.
I added $.trim()to my data.responseText and finally it's working (i don't know why :) )
var obj = JSON.parse($.trim(data.responseText));
$('.dropdown-menu').html(obj.notification);
Thx a lot for you all for your assisting

AJAX call returns undefined in Header / form-data

I am trying to get the contents from some autogenerated divs (with php) and put the contents in a php file for further processing. The reason for that is I have counters that count the number of clicks in each div. Now, I ran into a problem. When I echo back the data from the php file, the call is made, but I get undefined in the form-data section of the headers, and NULL if I do var_dump($_POST). I am almost certain I am doing something wrong with the AJAX call. I am inexperienced to say the least in AJAX or Javascript. Any ideas? The code is pasted below. Thanks for any help / ideas.
The AJAX:
$(document).ready(function(e) {
$("form[ajax=true]").submit(function(e) {
e.preventDefault();
var form_data = $(this).find(".test");
var form_url = $(this).attr("action");
var form_method = $(this).attr("method").toUpperCase();
$.ajax({
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
$("#resultcart").html(returnhtml);
}
});
});
});
The PHP is a simple echo. Please advise.
Suppose you have a div
<div id="send_me">
<div class="sub-item">Hello, please send me via ajax</div>
<span class="sub-item">Hello, please send me also via ajax</span>
</div>
Make AJAX request like
$.ajax({
url: 'get_sorted_content.php',
type: 'POST', // GET is default
data: {
yourData: $('#send_me').html()
// in PHP, use $_POST['yourData']
},
success: function(msg) {
alert('Data returned from PHP: ' + msg);
},
error: function(msg) {
alert('AJAX request failed!' + msg);
}
});
Now in PHP, you can access this data passed in the following manner
<?php
// get_sorted_content.php
if(!empty($_POST['yourdata']))
echo 'data received!';
else
echo 'no data received!';
?>
It's sorted. Thanks to everyone. The problem was I didn't respect the pattern parent -> child of the divs. All I needed to do was to wrap everything in another div. I really didn't know this was happening because I was echoing HTML code from PHP.

AJAX in WordPress only returns 0

I'm trying to utilize WordPress's admin-ajax feature in order to build a dynamic admin panel option-set for a plugin. Essentially, once an option is selected from a dropdown (select/option menu), PHP functions will sort through and display more dropdown menus that fall under the dropdown above it. I began with a simple return that I was hoping to utilize later down the line, but I can't seem to get the text to print out without running into unidentified issues.
The AJAX I set up puts out a 200 status but the response never builds, and I'm left with 0 as my result. Here's the code:
JS/jQuery built into PHP function ajax-action()
$ = jQuery;
$('#platform').change(function(e) {
var data = {
action: 'action_cb',
type: 'POST',
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(errorThrown);
},
success: function(response) {
$('#user_id').val(response);
}
};
$.ajax(ajaxurl, data, function(data) {
$('#user_id').val(data);
});
e.preventDefault();
});
PHP functions and add-actions
add_action('wp_ajax_action_cb','action_cb');
add_action('admin_footer','ajax_action');
function action_cb() { $platform = 'test'; echo json_encode($platform); wp_die(); };
My question is: how can I fix this and prevent it from continuing to happen? I'd like to return the actual results and not 0.
As per the wordpress documentation:
https://codex.wordpress.org/AJAX_in_Plugins (Reference "Error Return Values")
A 0 is returned when the Wordpress action does not match a WordPress hook defined with add_action('wp_ajax_(action)',....)
Things to check:
Where are you defining your add_action('wp_ajax_action_cb','action_cb');?
Specifically, what portion of your plugin code?
Are you logged into wordpress? You mentioned the admin area, so I'm assuming so, but if you are not, you must use add_action('wp_ajax_nopriv_{action}', ....)
Additionally, you didn't share the function this is tied to:
add_action('admin_footer','ajax_action');
And lastly, why are you using "json" as the data type? If you are trying to echo straight HTML, change data type to 'html'. Then you can echo directly on to page (or as a value as you are doing). Currently, you are trying to echo a JSON object as a value in the form...
So your code would look like so:
function action_cb() { $platform = 'test'; echo $platform; p_die(); };
...and your AJAX could be:
<script type = "text/javascript">
jQuery.ajax({
url: ajaxurl,
type: 'post',
data: {'action' : 'action_cb'},
success: function (data) {
if (data != '0' && data != '-1') {
{YOUR SUCCESS CODE}
} else {
{ANY ERROR HANDLING}
}
},
dataType: 'html'
});
</script>
Try This:
<script>
$ = jQuery;
$('#platform').change(function(e) {
var data = {
data: {'action' : 'action_cb'},
type: 'POST',
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(errorThrown);
},
success: function(response) {
$('#user_id').val(response);
}
};
$.ajax(ajaxurl, data, function(data) {
$('#user_id').val(data);
});
e.preventDefault();
});
</script>
Probably you need to add
add_action('wp_ajax_nopriv_action_cb', 'action_cb');
https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)
just make small change in your AJAX. I am assuming you're logged in as admin.
replace action in data object with data:"action=action_cb",
var data = {
data:"action=action_cb",
type: 'POST',
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(errorThrown);
},
success: function(response) {
$('#user_id').val(response);
}
};
$.ajax(ajaxurl,data,function(data){
$('#user_id').val(data);
});
To prevent WP adding zero into response i always using die(); insted of wp_die();
and registering function:
add_action( 'wp_ajax_action_cb', 'action_cb_init' );
add_action( 'wp_ajax_nopriv_action_cb', 'action_cb_init' );
function action_cb_init() {
}
When calling to function with AJAX use action: 'action_cb'
Hope this helps. I have already explained standard way of using ajax in wp.
Wordpress: Passing data to a page using Ajax
Ok, I have been recreating your code now in my own project and noticed that the javascript you shared returned the ajax-object and not the results. So what I come up with is a bit rewriting, but is worked fine when I tried it.
$j = jQuery.noConflict();
$j('#platform').change(function(e) {
$j.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: 'action_cb',
}
}).done(function( data ) {
// When ajax-request is done.
if(data) {
$j('#user_id').val(data);
} else {
// If 0
}
}).fail(function(XMLHttpRequest, textStatus, errorThrown) {
// If ajax failed
console.log(errorThrown);
});
e.preventDefault();
});
I hope the comments explain good enough how it is working. Note how I'm using $j instead of just $ for the jQuery.noConflict mode.
For those by the "Load More" problem.
Normally "0" is used instead of false.
I found such a solution.
So that 0 does not come. Try this code with false.
PHP
ob_start(); // start the buffer to capture the output of the template
get_template_part('contents/content_general');
$getPosts[] = ob_get_contents(); // pass the output to variable
ob_end_clean(); // clear the buffer
if( $read == $articles->found_posts )
$getPosts[] = false;
JS
if( posts[i] == false )
$(".load_more_button").fadeOut();

Passing JSON object to PHP script

I am trying to pass a JSON object that looks similar to this:
{"service": "AAS1", "sizeTypes":[{"id":"20HU", "value":"1.0"},{"id":"40FB","2.5"}]}
Just a note: In the sizeTypes, there are a total of about 58 items in the array.
When the user clicks the submit button, I need to be able to send the object to a PHP script to run an UPDATE query. Here is the javascript that should be sending the JSON to the PHP script:
$('#addNewSubmit').click(function()
{
var payload = {
name: $('#addservice').val();
sizeTypes: []
};
$('input.size_types[type=text]').each(function(){
payload.sizeTypes.push({
id: $(this).attr('id'),
value: $(this).val()
});
});
$.ajax({
type: 'POST',
url: 'api/editService.php',
data: {service: payload},
dataType: 'json',
success: function(msh){
console.log('success');
},
error: function(msg){
console.log('fail');
}
});
});
Using the above click function, I am trying to send the object over to php script below, which is in api/editService.php:
<?php
if(isset($_POST['service']))
{
$json = json_decode($_POST['service'], true);
echo $json["service"]["name"] . "<br />";
foreach ($json["service"]["sizeTypes"] as $key => $value){
echo $value["value"] . "<br />";
}
}
else
{
echo "Nooooooob";
}
?>
I do not have the UPDATE query in place yet because I am not even sure if I am passing the JSON correctly. In the javascript click function, you see the SUCCESS and ERROR functions. All I am producing is the ERROR function in Chrome's console.
I am not sure where the error lies, in the JavaScript or the PHP.
Why can I only produce the error function in the AJAX post?
Edit
I removed the dataType in the ajax call, and added JSON.stringify to data:
$.ajax({
type: 'POST',
url: 'api/editService.php',
data: {servce: JSON.stringify(payload)},
success: function(msg){
console.log('success');
},
error: function(msg){
console.log('fail'), msg);
}
});
In the PHP script, I tried this:
if(isset($_POST['service'))
{
$json = json_decode($_POST['service'], true);
foreach ($json["service"]["sizeTypes"] as $key => $value){
$insert = mysqli_query($dbc, "INSERT INTO table (COLUMN, COLUMN, COLUMN) VALUES (".$json["service"] . ", " . "$value["id"] . ", " . $value["value"]")");
}
}
else
{
echo "noooooob";
}
With this update, I am able to get the success message to fire, but that's pretty much it. I cannot get the query to run.
without seeing the error, I suspect the error is because ajax is expecting json (dataType: 'json',) but you are echoing html in your php
Try to change
error: function(msg){
console.log('fail');
}
to
error: function(msg){
console.log(msg);
}
There might be some php error or syntax issue and you should be able to see it there.
Also try to debug your php script step by step by adding something like
echo "still works";die;
on the beginning of php script and moving it down till it'll cause error, then you'll know where the error is.
Also if you're expecting JSON (and you are - dataType: 'json' in js , don't echo any HTML in your php.
As you are sending an object in your service key, you probably have a multi-dimensional array in $_POST['service'].
If you want to send a string, you should convert the object to json:
data: {service: JSON.stringify(payload)},
Now you can decode it like you are doing in php.
Also note that you can only send json back from php if you set the dataType to json. Anything other than valid json will have you end up in the error handler.
Example how to handle a JSON response from editService.php. Typically, the editService.php script will be the worker and will handle whatever it is you need done. It will (typically) send a simple response back to the success method (consider updating your $.ajax to use the latest methods, eg. $.done, etc). From there you handle the responses appropriately.
$.ajax({
method: 'POST',
url: '/api/editService.php',
data: { service: payload },
dataType: 'json'
})
.done(function(msh) {
if (msh.success) {
console.log('success');
}
else {
console.log('failed');
}
})
.fail(function(msg) {
console.log('fail');
});
Example /editService.php and how to work with JSON via $.ajax
<?php
$response = [];
if ( isset($_POST['service']) ) {
// do your stuff; DO NOT output (echo) anything here, this is simply logic
// ... do some more stuff
// if everything has satisfied, send response back
$response['success'] = true;
// else, if this logic fails, send that response back
$response['success'] = false;
}
else {
// initial condition failed
$response['success'] = false;
}
echo json_encode($response);

using returned json values in calls not working

Trying to use the values I return from my php yet there are not working properly.
<script type="text/javascript">
$(function () {
$('#delete').on('click', function () {
var $form = $(this).closest('form');
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
dataType : 'json'
}).done(function (response) {
if (response.success == 'success') {
// fade out the deleted comp
$("#c"+response.computer_id+"").fadeOut("slow");
// remove from the drop down
$("#comp_selection option[value='#c"+response.computer_id+"']").remove();
} else {
alert('Some error occurred.');
}
});
});
});
</script>
I am returning from the php file :
echo json_encode($ajax_result);
which is returning :
{"computer_id":1,"success":"success"}
EDIT: I found a small error in code outside of this where I was returning a different value than expected. All is well and the above was indeed correct to start with.
You should debug using firebug or whatever developer tools you have in your browser - firebug in Firefox is very good for this as you can see the JSON data passed back from the AJAX call.
That said, your issue is that the data is probably under response.d - so look at response.d.success and response.d.computer_id
Maybe the content you are receiving from your PHP server is sent as simple text, and must be sent with the headers set for JSON content:
header('Content-Type: application/json');

Categories