error with ajax and json ..with php post - php

Ok I am banging my head against my desk.
I am posting to a method in my php script and I am returning a json array
public function test()
{
return json_encode($this->runResults() );
exit;
}
}
echo of above (echo json_encode($this->runResults() ) will give you this below
[
{"code":"123456","date_created":"2012-07-09","date_expires":null},{"code":"3453432","date_created":"2012-07-09","date_expires":null},
{"code":"3sdf324","date_created":"2012-07-09","date_expires":null},
{"code":"weewr22","date_created":"2012-07-09","date_expires":"2012-07-19"}
]
now in my javascript I have this
$.ajax({
url : 'test',
type : 'POST',
data : {
data1: adataval,
data2: bdataval
},
success : function(data) {
alert(data.length);
},
error : function() {
}
});
and this alerts out in 1000s as it reads every single character..where as I was hoping that the length should have been 4. so then I change the above ajax to this
$.ajax({
url : 'test',
type : 'POST',
datatype: 'json'
data : {
data1: adataval,
data2: bdataval
},
success : function(data) {
alert(data.length);
},
error : function() {
}
});
as you can see I added datatype: 'json'. but then I started getting
Uncaught Error: NOT_FOUND_ERR: DOM Exception 8
what am I doing wrong?

Try this PHP Script
public function test()
{
echo json_encode($this->runResults());
}
Update :
also in ajax method
use dataType not datatype

alert( $.parseJSON(data).length );
Also, in your script, you should set the content-type to json: header('Content-type: application/json');

Related

Wordpress ajax returns 0 only

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.

Jquery ajax return current page html in response

First, let me say that I've looked through other similar questions on this site and the jQuery documentation. So far, I haven't found something that fixes my issue.
I am trying to get HTML data from ajax request but every time in response i got current page html.
Here is my Ajax function.
jQuery.ajax({
url:"url to function call",
type: "POST",
datatype : "html",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: {
qtext: filter_search
},
success:function(data) {
console.log(data);
jQuery("#appendHtml").html(data);
},
error : function(data) {}
});
and here is my Joomla PHP function where I have return HTML
public function getHtmlAjax()
{
$token = $this->createToken();
$listData = $this->getKapsulelist($token);
$html = $this->buildLayout($listData);
echo $html;
jexit();
}
I had this issue because I was using:
echo admin_url(); to get the ajaxurl,
after changing to
echo admin_url('admin-ajax.php');
it worked!

jQuery AJAX call returns results before page headers resulting in parseerror

I am trying to create a simple AJAX call using JSON, but I keep getting a parse error on the result and when I check the resultText it shows the source code of the entire page, with the JSON response showing a success above the page headers.
Here is my AJAX call, where #class is a select box with values.
$("#class").change( function () {
if($('#class').val().length > 0){
$.ajax({
type: "GET",
url: "http://192.168.0.9/ajax",
data: 'class_id=' + $("#class").val(),
datatype: 'json',
async: 'true',
beforeSend: function() {
alert("Before send!");
},
success: function(result){
if (result.status){
$('#result').html(result);
} else {
alert('request unsuccessful!');
}
},
complete: function() {
alert("Complete!");
},
error: function (request,error) {
alert('A jQuery error has occurred. Status: ' + error +':'+ request.responseText);
$("#result").html(request.responseText);
}
});
} else {
alert('Please make a selection');
}
return false;
});
This is my PHP function that returns the result
$result = array();
$result['status'] = "success";
$result['message'] = "Types";
header("Content-Type: application/json; charset=utf-8", true);
echo json_encode($result);
Finally, this is the response I am getting in my error alert:
A jQuery error has occurred status:parseerror
{"status":"success", "message":"Types"}<!DOCTYPE html>
<html>
...rest of my page from where the request was sent
I am hoping this is a simple error and someone can tell me what I am doing wrong?
Perhaps your parameter should be pass in JSON format:
data: "{'class_id':'" + $("#class").val() + "'}",
Try to remove datatype:'json' from the Javascript and header("Content-Type: application/json; charset=utf-8", true); it should be recognize itself

jQuery Ajax request is only working with one parameter

i have a problem using ajax with a php file.
Used Code:
function deleteImage() {
$.ajax({
type : 'GET',
url : '../includes/deleteImage.php',
contentType : 'application/x-www-form-urlencoded',
data : {
method : "deleteImage",
id : "1"
},
success : function(msg) {
console.log(msg);
},
failure : function(msg) {
console.log(msg);
}
});
}
It doesn't work and the Chrome Console is showing me the following error:
GET http://localhost/MyPage/WebContent/includes/deleteImage.php?method=deleteImage&id=1
Okay, it looks like a missing file.
But when leaving the id parameter out, the request works without a problem.
I tried with different parameter names and with a plain xmlhttprequest without jquery.
The same error code is shown like above.
An other request with the same structure is working without a problem.
(http://localhost/MyPage/WebContent/includes/jsListener.php?method=showMainSiteEditor&id=4)
My local server is XAMPP and i'm testing in Google Chrome.
Please can you share error message and deleteImage.php code
still you can try some like:
pass direct data string
data :'method=deleteImage&id=1'
instead of
data : {
method : "deleteImage",
id : "1"
}
and use full URL too.
your code working perfect on my end with both post and get method try to give full url in method
function deleteImage() {
$.ajax({
type : 'GET',
url: "includes/ajax_response.php",
contentType : 'application/x-www-form-urlencoded',
data : {
method : "deleteImage",
id : "1"
},
success : function(msg) {
alert(msg);
console.log(msg);
},
failure : function(msg) {
console.log(msg);
}
});
}
and ajax_response.php
if($_REQUEST['method']=='deleteImage')
{
echo $_REQUEST['method'].$_REQUEST['id'];
}

jQuery json from PHP result

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.

Categories