I am using datatables in which I've implemented a <select> tag, I am trying to create a dependent dropdown but the problem is ajax returns only 0,
Also when I alert(data) in success function, the alert comes up with [object Object] reponse, not sure what's going wrong.
For testing purpose I've putted the echo "<option value='test'>Test</option>";
$('#data-modification-table tbody').on('change', 'td select', function(e) {
e.preventDefault();
let $tr = $(e.target).closest('tr');
$.ajax({
type: "POST",
url: ajaxurl,
dataType: "json",
data: {
action: "send_dropdown_account_data",
account_id: $tr.find('.user_account_name').val(),
project_id: $tr.find('.user_project_name').val(),
},
success: function(data) {
alert(data);
},
error: function(req, status, err) {
console.log('Something went wrong', status, err);
}
});
});
add_action('wp_ajax_nopriv_send_dropdown_account_dat', 'update_modification_dropdown_options');
add_action('wp_ajax_send_dropdown_account_dat', 'update_modification_dropdown_options');
function update_modification_dropdown_options()
{
echo "<option value='test'>Test</option>";
$output = ob_get_clean();
wp_send_json_success($output);
wp_die();
}
Inside inspect's network option I can see this response for admin-ajax.php: {"success":true,"data":"0"}
In console there is no error or message.
Instead of echoing the output you should just return an array of data instead directly to the wp_send_json_success method.
E.g.
$data = [
'input' => '<option value="test">Test</option>',
];
wp_send_json_success($data);
https://developer.wordpress.org/reference/functions/wp_send_json_success/
The response will be returned in that AJAX call as JSON.
alert(data.input)
First of all you can remove the type and dataType. Encode a variable into JSON using wp_json_encode(). Your function send_dropdown_account_data will end as following:
echo wp_json_encode([
'input' => '<option value="test">Test</option>',
]);
wp_die();
Now at ajax success function you will have to parse it before using.
success: function(data) {
data = JSON.parse(data);
alert(data.input);
},
Also check your action hook names as #DeepakSaini mentioned.
You are missing action name in add_action();
add_action('wp_ajax_nopriv_send_dropdown_account_data', 'update_modification_dropdown_options');
add_action('wp_ajax_send_dropdown_account_data', 'update_modification_dropdown_options');
Try this one in ajax function.
Related
I am trying to send form data using ajax. But there's an error in ajax operation and only "error" callback function is executed.
Here's what I tried:
$("#issue_submit").click(function (e) {
console.log("clicked on the issue submit");
e.preventDefault();
// Validate the form
var procurementForm = $("#it_procuremet_form");
if($(procurementForm).valid()===false){
return false;
}
// Show ajax loader
appendData();
var formData = $(procurementForm).serialize();
// Send request to save the records through ajax
var formRequest = $.ajax({
url: app.baseurl("itprocurement/save"),
data: formData,
type: "POST",
dataType: "json"
});
formRequest.done(function (res) {
console.log(res);
});
formRequest.error(function (res, err) {
console.log(res);
});
formRequest.always(function () {
$("#overlay-procurement").remove();
// do somethings that always needs to occur regardless of error or success
});
});
Routes are defined as:
$f3->route('POST /itprocurement/save', 'GBD\Internals\Controllers\ITProcurementController->save');
Also I added :
$f3->route('POST /itprocurement/save [ajax]', 'GBD\Internals\Controllers\ITProcurementController->save');
I tried returning a simple string to the ajax call at the controller class.
ITProcurementController.php :
public function save($f3)
{
echo 'Problem!';
return;
$post = $f3->get('POST');
}
But only 'error' callback is executed. I cannot locate what is wrong. Please Help.
You are specifying that you expect json back:
// Send request to save the records through ajax
var formRequest = $.ajax({
url: app.baseurl("itprocurement/save"),
data: formData,
type: "POST",
// Here you specify that you expect json back:
dataType: "json"
});
What you send back is not json:
echo 'Problem!';
return;
This is an unquoted string, which is not valid json.
To send valid json back, you would need:
echo json_encode('Problem!');
return;
You could also remove the dataType attribute, depending on your needs.
I have a JSON response from my php file like:
[
{"id":"1"},
{"archiveitem":"<small>26.06.2015 12:25<\/small><br \/><span class=\"label label-default\">Bug<\/span> has been submitted by Admin"}
]
And try to fetch this response into a div after button was clicked, however firebug is telling me the message from the error-handler. I can't figure out the problem?
$('#loadarchive').click(function(){
$.ajax({
type: 'post',
url: '/src/php/LoadAdminDashboardArchive.php',
dataType: 'json',
data: {
action : 'getArchive'
},
success: function(results) {
var archiveelements = JSON.parse(results);
console.log(results);
$.each(archiveelements, function(){
$('#archivecontent').html('<div class="mark-read-container"><span class="btn-mark-unread" id="' + this.id + '">Unarchive</span></div><div class="bs-callout bs-callout-default">' + this.archiveitem + '</div>');
});
},
error: function(){
console.log('Cannot retrieve data.');
}
});
});
I tried to run your Code and I get
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
By defining dataType: 'json' your result is parsed already as an Array. So you can do something like:
success: function (results) {
if (results["head"]["foo"] != 0) {
// do something
} else if (results["head"]["bar"] == 1) {
// do something
}
}
this works on my computer:
$.ajax({
type: 'post',
url: '/src/php/LoadAdminDashboardArchive.php',
dataType: 'json',
data: { action : 'getArchive' },
success: function(results) {
console.log(results);
$.each(results, function(){
$('#archivecontent').html('<div class="mark-read-container"><span class="btn-mark-unread" id="' + this.id + '">Unarchive</span></div><div class="bs-callout bs-callout-default">' + this.archiveitem + '</div>');
});
},
error: function(){
console.log('Cannot retrieve data.');
}
});
You can get more information from the console if you dive into it a bit more. Or by logging these two parameters:
error: function(xhr, mssg) {
console.log(xhr, mssg);
}
First
your response is not correct,Correct response should look like this
[{
"id":"1",
"archiveitem":"<small>26.06.2015 12:25<\/small>
<br \/><span class=\"labellabel-default\">Bug<\/span> has been submitted by Admin"
},
{
...
}]
Second
You dont have to parse result ie.JSON.parse is not required since dataType:'json' will probably take care of json.
Finally your success method should look like this:
success: function(results) {
$.each(results, function(ind,el){
$('#archivecontent').html('<div class="mark-read-container"><span class="btn-mark-unread" id="' + el.id + '">Unarchive</span></div><div class="bs-callout bs-callout-default">' + el.archiveitem + '</div>');
});
},
As you are saying message from error-handler is showing.
That means AJAX is never sent to server because of incorrect URL or any other reason.
Use Firebug in Firefox and see the error in console tab.
Also I see your code
dataType: 'json',
data: { action : 'getArchive' },
success: function(results) {
var archiveelements = JSON.parse(results);
}
Do not use JSON.parse(results) because you have already written dataType: 'json', and any type of response is parsed automatically.
I was able to get it working and the problem was quite simple...
I forgot to paste the "button" - source code that initiated the ajax request. It was an Input of type "submit" and therefore the page reloaded by default after the response was retrieved successfully... so e.preventDefault(); was the way to go.
Thanks to all of you.
I have checked around, but can't seem to figure out how this is done.
I would like to send form data to PHP to have it processed and inserted into a database (this is working).
Then I would like to send a variable ($selected_moid) back from PHP to a JavaScript function (the same one if possible) so that it can be used again.
function submit_data() {
"use strict";
$.post('insert.php', $('#formName').formSerialize());
$.get('add_host.cgi?moid='.$selected_moid.');
}
Here is my latest attempt, but still getting errors:
PHP:
$get_moid = "
SELECT ID FROM nagios.view_all_monitored_objects
WHERE CoID='$company'
AND MoTypeID='$type'
AND MoName='$name'
AND DNS='$name.$selected_shortname.mon'
AND IP='$ip'
";
while($MonitoredObjectID = mysql_fetch_row($get_moid)){
//Sets MonitoredObjectID for added/edited device.
$Response = $MonitoredObjectID;
if ($logon_choice = '1') {
$Response = $Response'&'$logon_id;
$Response = $Response'&'$logon_pwd;
}
}
echo json_encode($response);
JS:
function submit_data(action, formName) {
"use strict";
$.ajax({
cache: false,
type: 'POST',
url: 'library/plugins/' + action + '.php',
data: $('#' + formName).serialize(),
success: function (response) {
// PROCESS DATA HERE
var resp = $.parseJSON(response);
$.get('/nagios/cgi-bin/add_host.cgi', {moid: resp });
alert('success!');
},
error: function (response) {
//PROCESS HERE FOR FAILURE
alert('failure 'response);
}
});
}
I am going out on a limb on this since your question is not 100% clear. First of all, Javascript AJAX calls are asynchronous, meaning both the $.get and $.post will be call almost simultaneously.
If you are trying to get the response from one and using it in a second call, then you need to nest them in the success function. Since you are using jQuery, take a look at their API to see the arguments your AJAX call can handle (http://api.jquery.com/jQuery.post/)
$.post('insert.php', $('#formName').formSerialize(),function(data){
$.get('add_host.cgi?moid='+data);
});
In your PHP script, after you have updated the database and everything, just echo the data want. Javascript will take the text and put it in the data variable in the success function.
You need to use a callback function to get the returned value.
function submit_data(action, formName) {
"use strict";
$.post('insert.php', $('#' + formName).formSerialize(), function (selected_moid) {
$.get('add_host.cgi', {moid: selected_moid });
});
}
$("ID OF THE SUBMIT BUTTON").click(function() {
$.ajax({
cache: false,
type: 'POST',
url: 'FILE IN HERE FOR PROCESSING',
data: $("ID HERE OF THE FORM").serialize(),
success: function(data) {
// PROCESS DATA HERE
},
error: function(data) {
//PROCESS HERE FOR FAILURE
}
});
return false; //This stops the Button from Actually Preforming
});
Now for the Php
<?php
start_session(); <-- This will make it share the same Session Princables
//error check and soforth use $_POST[] to get everything
$Response = array('success'=>true, 'VAR'=>'DATA'); <--- Success
$Response = array('success'=>false, 'VAR'=>'DATA'); <--- fails
echo json_encode($Response);
?>
I forgot to Mention, this is using JavaScript/jQuery, and ajax to do this.
Example of this as a Function
Var Form_Data = THIS IS THE DATA OF THE FORM;
function YOUR FUNCTION HERE(VARS HERE) {
$.ajax({
cache: false,
type: 'POST',
url: 'FILE IN HERE FOR PROCESSING',
data:Form_Data.serialize(),
success: function(data) {
// PROCESS DATA HERE
},
error: function(data) {
//PROCESS HERE FOR FAILURE
}
});
}
Now you could use this as the Button Click which would also function :3
Im trying to retrieve some data from JSON object which holds location information such as streetname, postcode etc. But nothing is being retrieved when i try and put it in my div. Can anybody see where im going wrong with this?
This is my ajax code to request and retrieve the data
var criterion = document.getElementById("address").value;
$.ajax({
url: 'process.php',
type: 'GET',
data: 'address='+ criterion,
success: function(data)
{
$('#txtHint').html(data);
$.each(data, function(i,value)
{
var str = "Postcode: ";
str += value.postcode;
$('#txtHint').html(str);
});
//alert("Postcode: " + data.postcode);
},
error: function(e)
{
//called when there is an error
console.log(e.message);
alert("error");
}
});
When this is run in the broswer is just says "Postcode: undefined".
This is the php code to select the data from the database.
$sql="SELECT * FROM carparktest WHERE postcode LIKE '".$search."%'";
$result = mysql_query($sql);
while($r = mysql_fetch_assoc($result)) $rows[] = $r;
echo json_encode($rows), "\n"; //Puts each row onto a new line in the json data
You are missing the data type:
$.ajax({
dataType: 'json'
})
You can use also the $.getJSON
EDIT: example of JSON
$.getJSON('process.php', { address: criterion } function(data) {
//do what you need with the data
alert(data);
}).error(function() { alert("error"); });
Just look at what your code is doing.
First, put the data directly into the #txtHint box.
Then, for each data element, create the string "Postcode: "+value.postcode (without even checking if value.postcode exists - it probably doesn't) and overwrite the html in #txtHint with it.
End result: the script is doing exactly what you told it to do.
Remove that loop thing, and see what you get.
Does your JSON data represent multiple rows containing the same object structure? Please alert the data object in your success function and post it so we can help you debug it.
Use the
dataType: 'json'
param in your ajax call
or use $.getJSON() Which will automatically convert JSON data into a JS object.
You can also convert the JSON response into JS object yourself using $.parseJSON() inside success callback like this
data = $.parseJSON(data);
This works for me on your site:
function showCarPark(){
var criterion = $('#address').val();
// Assuming this does something, it's yours ;)
codeAddress(criterion);
$.ajax({
url: 'process.php',
type: 'GET',
dataType: 'json',
data: {
address: criterion
},
success: function(data)
{
$("#txtHint").html("");
$.each(data, function(k,v)
{
$("#txtHint").append("Postcode: " + v.postcode + "<br/>");
});
},
error: function(e)
{
alert(e.message);
}
});
}
I have this jQuery script
var dataString = "class_id="+class_id;
$.ajax({
type: "POST",
url: "page.php",
data: dataString,
success: function (msg) {
//stuck here
},
error: function () {
showNotification("error", "Could not process at this time, try again later."); //this is a function created by me (which works fine so I just left the code in here)
}
});
my PHP output is something like this
echo '{status:1,message:"Success"}';
or
echo '{status:0,message:"Failure"}';
what I am trying to do in jQuery success: function(...) part is check if status is 0 or 1 and then show the message.
I tried to do is
success: function(text) {
if(parseInt(text.status) == 1) {
alert(text.message); // this is the success, the status is 1
} else {
alert(text.message); // this is the failure since the status is not 1
}
}
which didn't work, it was only outputing the else statement, even though the status was 1
Your PHP is generating invalid JSON, and shows no sign of setting an appropriate content type header to tell the browser to treat it as JSON in the first place. So first, fix the PHP:
header('application/json');
echo json_encode(Array("status" => 1, "message" => "Success"));
Then:
success: function (msg) {
alert(msg.message)
},
You can also use
PHP
echo json_encode(Array("status" => 1, "message" => "Success"));
JS
Inside your call back function use
success: function (msg) {
$.parseJSON(msg);
alert(msg.message);
}
The parseJSON will convert the json string returned/echoed by PHP in to json object.
Try something like below,
$.ajax({
type: "POST",
url: "page.php",
data: dataString,
dataType: 'json',
success: function (msg) {
if (msg.status == 0) {
alert("Success " + msg.message);
} else if (msg.status == 1) {
alert("Error " + msg.message);
}
},
error: function () {
showNotification("error", "Could not process at this time, try again later."); //this is a function created by me (which works fine so I just left the code in here)
}
});
If you don't specify in $.ajax the type 'json' data passed to response handler is treated as string. While if you specify 'json' dataType parameter you can use:
msg.status
and
msg.message
As a hint i suggest in php to use the json_encode function to generate json output.