json_decode returns null - laravel - php

i am sending json object from front-end using ajax call as the following:
<button id="btn">click me</button>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$('#btn').click(function () {
$.ajax({
url:"/execute",
type:"POST",
contentType: 'json',
data:{
"test":"hello"
},
success:function (data) {
console.log(data.status);
}
});
});
</script>
and i want to decode this json object in laravel, here is my controller code:
public function executeFunction(Request $request){
if($request->header()['content-type'][0] === 'json')
{
Log::info(json_decode($request->getContent(),true));
}
return response()->json(["status"=>"success"]);
}
json_decode returns null here, what might be the problem? Thanks.

I found a solution to this problem, the trick is to use JSON.stringify(data) in front end and json_decode will works fine.
Front end code:
button id="btn">click me</button>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$('#btn').click(function () {
$x = {
"test":"hello"
};
$.ajax({
url:"/execute",
type:"POST",
contentType: 'application/json',
data:JSON.stringify($x),
success:function (data) {
console.log(data);
}
});
});
</script>
Controller code:
public function executeFunction(Request $request){
if($request->header()['content-type'][0] === 'application/json')
{
Log::info(json_decode($request->getContent())->test);
}
}
If you dump the content, this will be the result:
object(stdClass)#423 (1) {
["test"]=>
string(5) "hello"
}

Related

not returning anything in ajax

this is simple test for ajax and i want to send variable t in my index.php and get data(t) in my process.php and alert digit 15 when i click on button but my problem is not alerting anything
this is my index.php
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function () {
var t = 10;
$("#btn").click(function () {
$.ajax({
type:'post',
url:'process.php',
data:{
't':t
},
success:(function (response) {
alert(response);
}
})
})
})
</script>
<button id="btn">Click!</button>
this is my process.php
<?php
$res = $_POST['t'] + 5;
return $res
?>
Change codes like below:-
1.jQuery:-
$(document).ready(function () {
var t = 10;
$("#btn").click(function () {
$.ajax({
type:'post',
url:'process.php',
data:{'t':t},
success:function (response) { //remove (
alert(response);
}
});
});
});
2.Php:-
<?php
$res = $_POST['t'] + 5;
echo $res; //use echo rather than return
?>
Reason:-
return is used for returning a value from a function to another piece of PHP code.jQuery is not part of the execution of the PHP code on the server, so it has no idea what is really going on server side. jQuery is waiting for the rendered server response, which is what echo provides.
Note:- After doing These changes, Please check the browser console while running the ajax and see any error happen there? If yes share with us
i) Change your code with following code
$(document).ready(function () {
var t = 10;
$("#btn").click(function () {
$.ajax({
type:'post',
url:'process.php',
data:{
't':t
},
success:(function (response) {
alert(response);
}) //Close brace missing
})
})
});
2) Change return to echo
$(document).ready(function(){
$("#btn").click(function (){
var t = 10;
$.ajax({
type:'post',
url:'process.php',
data:{
t:t
},
success:(function (response) {
alert(response);
// you didnt close )
}) // close of success
})// close of ajax
})// close of click
}); // close of document
Process.php
<?php
$res = $_POST['t'] + 5;
echo $res;
?>
You should add jQuery like this
<script src="jquery-3.2.1.min.js"></script>
If you actually have downloaded and placed the file in the same directory.
You can include in from a CDN if you don't want to download it.
use this instead:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
And fix your JS code: (remove the extra '}' ...)
$(document).ready(function () {
var t = 10;
$("#btn").click(function () {
$.ajax({
type:'post',
url:'test.php',
data:{
't':t
},
success:(function (response) {
alert(response);
})
})
});
});

Jquery autocomplete wont give any result

I am new to codeignitor and trying to get jquery autocomplete from database . There are already many questions asked about this topic but none of those helped me.
Here is my script function from view file
View
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js">
</script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js">
</script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-
ui.css" />
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js">
</script>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript">
$(function() {
$( "#vname" ).autocomplete({
source: function(request, response) {
$.ajax({
url: "vendor/search",
data: { term: $("#vname").val()},
dataType: "json",
type: "GET",
success: function(data){
var resp = $.map(data,function(obj){
return obj.tag;
});
response(resp);
}
});
},
minLength: 2
});
});
</script>
</head>
.
.
.
.
<input type="text" class="form-control" name="vendor_name" id="vname" />
here is controller(vendor) function (search) from which I am trying to get array of suggestion from database
Controller
public function search()
{
$json = [];
$this->load->database();
if(!empty($this->input->get("term"))){
$this->db->like('name', $this->input->get("term"));
$query = $this->db->select('id,name as text')
->limit(10)
->get("vendors");
$json = $query->result();
}
echo json_encode($json);
}
the problem is that when I type in input field, nothing happen (no autocomplete appears) but my vendor/search function is working fine while accessing it directly and pass something as parameter. I think $_GET[term] is always empty or something.
I dont have any idea what to do now any suggestion would be appreciable.
Change this line:
url: "vendor/search",
to:
url: "<?php echo base_url('vendor/search'); ?>",
Change in controller
public function search(){
$json = [];
$this->load->database();
if(!empty($this->input->get("term"))){
$this->db->like('name', $this->input->get("term"));
$query = $this->db->select('id,name as text')
->limit(10)
->get("vendors");
$json = $query->result();
}
//set page header
$this->output
->set_content_type('application/json')
->set_output(json_encode($json));
}
replace script tag
<script type="text/javascript">
$(function() {
$( "#vname" ).autocomplete({
source: function(request, response) {
$.ajax({
url: "<?=base_url(); ?>vendor/search?term="+request.term,
dataType: "json",
type: "GET",
success: function(data){
response($.map(data, function (value, key) {
return {
label: value.text,
value: value.id
}
}));
}
});
},
minLength: 2,
select: function(event, ui) {
//select event of autocomplete
console.log("id : ",ui.item.value);
console.log("text : ",ui.item.label);
$('#vname').val(ui.item.label);
return false;
},
});
});
</script>

Error Ajax request

When I perform a simple ajax request I get the following error
TypeError: 'toString' called on an object that does not implement interface HTMLAnchorElement.
This is my ajax script
<script type="text/javascript">
$(document).on("ready", function(){
$("#tabla_persona table tr").click(function() {
var cod = $( "#identificador",this);
alert(cod.html());
var parametros={
"cod":cod
};
$.ajax({
type: 'POST',
url: '<?php echo site_url("archivo/prueba"); ?>',
data: parametros,
success: function(resp) {
$("#tabla_usuario_individual").html(resp);
}
});
});
});
</script>
This is my controller
public function prueba(){
$this->load->view('datos_persona');
}
and my simple page to see the result
<a>
Prueba
</a>
Try changing:
var parametros={
"cod":cod
};
to:
var parametros={
"cod":cod.html()
};
Just need simple change.I think the following code will work.
public function prueba(){
echo $this->load->view('datos_persona',true);
}

<a href=""> Action to database

Is there a way to update a database using 1 click?
i.e
echo "<a href='".$wpdb->query(" UPDATE partners SET active='no' WHERE partner_id='$active_partner->partner_id' ")."'>Disable</a>";
You need to react on a click with an ajax function.
i.e.
$('#your_button_id').bind('click', function () {
function_with_ajax();
})
function function_with_ajax() {
$.ajax({
here you could call the update.php script and transmit dynamic data
});
}
<button id="btn-save" type="button">
save
</button>
<script type="text/javascript">
jQuery(document.ready(function ($) {
$("#btn-save").click(
function () {
$.ajax({
type:"POST",
url:"/wp-admin/wp-ajax.php",
data:{
action:"save_data",
data:"data-update",
condition:"data-condition"
},
success:function (response) {
console.log(response);
},
error:function (error) {
console.log(error);
}
})
}
);
}))
</script>
and add to file function:
add_action("wp_ajax_save_data",function ()
{
global $wpdb;
$wpdb->update("your-table",
["your_field" => $_POST['data']]
,["condition-filed"=>$_POST['condition']]);
});

AJAX success function not executing

I'm trying to create a simple AJAX call for testing, but have encountered a problem. I have nested in my AJAX call a success function which should pop an alert message but it doesn't. Checking firebug, the POST is successful and responds with "A20" (without quotations). Is there something wrong in my code?
index.php (view)
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="init.js"></script>
<script src="jquery-1.10.2.min.js"></script>
</head>
<body>
<button id="your_button">Push me</button>
</body>
</html>
init.js
$(function() {
$('#your_button').bind("click", function() {
var json_data = {"category": "A", "size": "20"};
$.ajax({
url: "posted.php",
dataType: "json",
type: "POST",
cache: false,
data: {"data": json_data},
success: function (data) {
if (!data.error) {
alert('k');
} else {
alert('error!');
}
}
});
});
});
posted.php
$category = $_POST['data']['category'];
$tsize = $_POST['data']['size'];
echo ($category);
echo ($size);
Try this -
$(function() {
$('#your_button').bind("click", function() {
var json_data = {"category": "A", "size": "20"};
$.ajax({
url: "posted.php",
dataType: "json",
type: "POST",
cache: false,
data: json_data,
success: function (data) {
if (!data.error) {
alert('k');
} else {
alert('error!');
}
}
});
});
});
Posted.php
$category = $_POST['category'];
$tsize = $_POST['size'];
//echo ($category);
//echo ($tsize);
echo json_encode($_POST);
Your want json data but you were not echoing json data
this is not right:
data: {"data": json_data}
do like this:
data: {data: json_data}
You need to set proper headers in your PHP and send a valid json response from PHP file. Add these lines to your PHP
header('Access-Control-Allow-Origin: *');
header('Content-type: application/json');
and echo back some valid json from it like echo '{"auth":"true","error":"false"}';
First you are using two jquery libraries, remove any one of them.
Second replace data: {"data": json_data}, with data: json_data,.
Third on posted.php use $category = $_POST['category'] and $tsize = $_POST['size'];.
Hope it will help you.

Categories