parseJSON does not work in ajax - javascript

I try to do ajax and then back json data in Wordpress.
My Ajax is:
$.ajax({
type: "POST",
dataType : 'html',
url: "/wp-content/themes/myproject/ajax/otros_alojamientos.php",
data: {
idPost: '<?php echo $ID; ?>'
},
success: (function(data) {
alert(data); // this is my json
var a = $.parseJSON(data);
alert(a.titulo); // there is not nothing here. Undefined.
}),
error: (function(data) {
console.log('Error alojamientos');
}),
});
My Json back is:
string(50) "{"titulo":"aaatitle","descripcion":"bbbdescription"}"
I can not print titulo or descripcion with alert or console.log...
Cheers!

change your datatype param
$.ajax({
type: "POST",
dataType : 'json',
url: "/wp-content/themes/myproject/ajax/otros_alojamientos.php",
data: {
idPost: '<?php echo $ID; ?>'
},
success: (function(data) {
alert(data.titulo); // data is parsed as Json by jQuery
}),
error: (function(data) {
console.log('Error alojamientos');
}),
});
you should check your error callback function params also (it doesn't expect data as 1st param)

Well the response you are getting that is neither a valid json or valid html. So either you remove the dataType and then you have to parse it or just add dataType:"json" but in your case that is not a valid json.
So i would like to tell you that you should use dataType:"text" and then you can parse it:
$.ajax({
type: "POST",
dataType : 'text',
url: "/wp-content/themes/myproject/ajax/otros_alojamientos.php",
data: {
idPost: '<?php echo $ID; ?>'
},
success: (function(data) {
var json = data.split(' ')[1]; // gets you the json string
var validJson = $.parseJSON(json); // parses as valid json
alert(validJson.titulo);
}),
error: (function(data) {
console.log('Error alojamientos');
}),
});

Related

can't get data from json even getting a response on the console

I've been trying to send this information to the js.
$statement = ibase_prepare($sql);
$query = ibase_execute($statement);
while ($row = ibase_fetch_assoc($query)) {
$data[] = $row;
}
echo json_encode($data);
However, when I try to, I get the response, but I can't get the data.
$('document').ready(function (){
$.ajax({
method: "POST",
url: "../Dashboard/php/chart.php",
dataType: "json",
sucess: function (data){
console.log(JSON.stringify(data));
}
});
})
You just have a grammatical error in a word "sucess", the correct word is "success"
$.ajax({
method: "POST",
url: "./data.php",
dataType: "json",
sucess: function (data){ // Here -> success
alert(JSON.stringify(data));
}
});

Have problem when parsing data with JSON Parse

I got problem when parsing JSON from my AJAX. This is my error and the data that I want to parse
This my code:
var url = "<?php echo base_url(); ?>home/get_produk_by_eancode";
$.ajax({
type: "POST",
url: url,
data: { kodePilihan: kodeBarangPilihan, kodeScala: kodeScala, codecust:
codeCustomer },
success: function(result) {
if(result) {
console.log(result);
obj = $.parseJSON(result);
}
My controller
public function get_produk_by_eancode() {
$eancode = $this->input->post('kodePilihan');
$kodeScala = $this->input->post('kodeScala');
$codecust = $this->input->post('codecust');
$barangPilihan = $this->web_ordering_model->get_produk_by_eancode_page3($eancode, $kodeScala, $codecust)->row_array();
echo json_encode($barangPilihan);
}
My result data from the controller or you can see in picture
{"SC01132":"*1038 AR BRU KM","SC01002":"BOX-50 dengan Roda","SC01011":"A-19","brand":"Kiramas","verpacking":12,"List1":"76250.00000000","SC01001":"625050","Free":".00","LastTglProduksi":"1900-01-01 00:00:00.000","PricelistName":"Netto"}
You get this error because what you give to parseJSON is not a string.
First try to add content-type to you AJAX call :
contentType: "application/json; charset=utf-8",
dataType: "json",
Also you can convert your object to a string.
var url = "<?php echo base_url(); ?>home/get_produk_by_eancode";
$.ajax({
type: "POST",
url: url,
dataType: "json", //changes
data: ({ kodePilihan: kodeBarangPilihan, kodeScala: kodeScala, codecust: codeCustomer }),
success: function(result) {
if(result) {
console.log(result);
var obj = JSON.parse(result); //changes
console.log(obj); //changes
}
}
Solved by this code
$.trim()
Sorry for my long report, thanks.

jQuery AJAX POST method not working

I am trying to execute the AJAX operation. the call is working fine but the problem I am having is that I am getting an empty string as a response. There is no error in the console. all I get is an empty string. Even when I change the dataType to JSON, I still get the same response.
JavaScript Code:
$.ajax({
url: "data/saveCart.php",
method: "POST",
data: {
cartItem:item
},
dataType: "text",
success: function(data){
console.log(data);
}
});
PHP code:
if(isset($_POST['cartItem'])) {
echo "AJAX successful";
} else {
echo "AJAX failed";
}
It seems like it was caused by not stringifying your data.
var item = {
toothbrush: {
price: 1
}
};
$.ajax({
url: "data/saveCart.php",
method: "POST",
data: {
cartItem: JSON.stringify( item )
},
dataType: "text",
success: function(data){
console.log(data);
}
});

Undefined index in post method of JSON object sent by jQuery AJAX

I've tried almost all suggestions but it doesn't work. My ids are working properly in the JavaScript function when I alert my array using arr['id']. However, when I try $_POST['id'] on a different PHP file (I've used AJAX and specified the URL) is gives me an error.
scriptfile.php:
<script>
function detailsmodal(cid, pid) {
var arr = { "cid": cid, "pid": pid };
jQuery.ajax({
url: '/frontend/include/detailsmodal.php',
method: "post",
data: arr,
success: function(data) {
jQuery('body').append(data);
jQuery('#details-modal').modal('toggle');
},
error: function() {
alert("something went wrong");
}
});
}
detailsmodal.php
<?php
echo $_POST['cid'];
?>
You could try sending your data as json like this:
$.ajax({
type: "POST",
url: "/frontend/include/detailsmodal.php",
contentType: "application/json",
dataType: "json",
data: JSON.stringify({ cid: cid, pid: pid }),
success: function(data) {
jQuery('body').append(data);
jQuery('#details-modal').modal('toggle');
},
error: function() {
alert("something went wrong");
}
});
For the decoding you could use javascript JSON.parse
var myObj = JSON.parse(this.responseText);
or
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
echo $data["cid"];

how to send two or more separate result for ajax success

I want to know how can I send two separate result to ajax j Query success
php file:
if(mysqli_affected_rows($dbCnn)== -1)
echo "Failed";
else
echo "Success" ;
include('table.php');
jquery:
$.ajax({
url: 'insert.php',
dataType: 'text',
type: 'post',
contentType: 'application/x-www-form-urlencoded',
data: $(this).serialize() + '&' + ids + '=' + 'submit',
success: function(data) {
$("#tableContainer").html(data);
}
});
I want to have to data, one for echo "Success" for example, and one for include table.php .
You could serialize them in json:
In your php:
ob_start();
include('table.php');
$table = ob_get_clean();
echo json_encode(array('table' => $table, 'message' => 'success'));
In javascript change as follows:
$.ajax({
url: 'insert.php',
dataType: 'json',
type: 'post',
contentType: 'application/x-www-form-urlencoded',
data: $(this).serialize()+ '&' + ids + '=' + 'submit',
success: function(response){
$("#tableContainer").html(response.table);
alert(response.message);
}
});
You're not so far. And Has I can see you're not asking for json.
Anyway just to tell you, you don't need the word success to call success in your ajax request.
$.ajax({
url: 'insert.php',
dataType: 'text',
type: 'post',
data: $(this).serialize() + '&' + ids + '=' + 'submit',
success: function(data) {
$("#tableContainer").html(data);
}
});
PHP
if(mysqli_affected_rows($dbCnn)== -1){
echo "Failed";
} else {
echo "Success";
include('table.php');
}
You can build a formatted response, in which you detail result1, result2,... resultx.
Nowadays, most people would use JSON in order to format and send data. But you could also use XML or define your own.
JSON example:
{
"status": "ok",
"results": {
"connection": true,
"table": false
}
}
Dazu kann in PHP die Funktion json_encode() verwendet werden:
json_encode([
'status' => 'ok',
'results' => array(
'connection' => $result1,
'table' => $result2
)
]);

Categories