Javascript Return JSON not working [duplicate] - javascript

This question already has answers here:
Returning JSON not working properly
(7 answers)
Closed 9 years ago.
i am returning json from my php file, the php file works fine and json is echoed properly, but the problem within the js...
the output should be {"name":"somename", "id":"someid","l":"something","sname":"somename","desc":"longdescriptionhere"}
JAVASCRIPT
function getClubData(id) {
alert(id);
$.ajax({
url: 'someurl',
crossDomain: true,
type: 'post',
data: id,
success: function (data) {
var json = jQuery.parseJSON(data);
alert(data);
},
});
};
PHP
$json = json_encode(array('name' => $name, 'id' => $id, 'l' => $l, 'sname' => $sname, 'desc' => $desc));
echo $json;
i am sure the php is correct, because it echoes on the page, the correct information, its just not transferring properly back to the javascript...

EDIT / UPDATE
Now that I actually get whats going on, and what you want...
Heres my updated answer
You need to give the id a key, so that on the other side your PHP script knows where to get this id....through the $_POST variable.
So your javscript...
function getClubData(id) {
alert(id);
$.ajax({
url: 'someurl',
crossDomain: true,
type: 'post',
data: {'theid':id},
success: function (data) {
var json = jQuery.parseJSON(data);
alert(data);
},
});
};
And then your php script would get that id
$id = $_POST['theid'];
$sql = "SELECT * from YOURTABLE WHERE ID = $id";
//and rest of your query and database stuff etc etc

Related

Jquery ajax with JSON return can't access to data inside the JSON

So I have this jquery code:
$(function(){
var url = 'template/traitComTest.php';
window.onload = function(e) {
// $(".formCom").ajaxForm({url: 'template/traitComTest.php', type: 'post'});
$.ajax({
type: "POST",
url: url,
data: $( ".formCom").serializeArray(),
success: function(reponse){
console.log(reponse);
}
});
}
});
with this php code:
if (isset($_REQUEST)) {
$adresse = $_POST['adresse'];
$com = $_POST['commentaire'];
$sql = $bdd->prepare('UPDATE tempSelector_template SET commentaire= :com WHERE exemple = :exem ');
$sql->execute(array(
":com" => $com,
":exem" => $adresse
));
$myData1 = array('result' => $sql);
echo json_encode($myData1);
$sql->closeCursor();
$sqlSelect = $bdd->prepare("SELECT commentaire FROM tempSelector_template WHERE exemple= :exemp");
$sqlSelect->execute(array(
":exemp" => $adresse
));
$myData = array('result1' => $sqlSelect);
echo json_encode($myData);
}
I get this response from ajax on chrome' console =>
{"result":{"queryString":"UPDATE tempSelector_template SET commentaire= :com WHERE exemple = :exem "}}{"result1":{"queryString":"SELECT commentaire FROM tempSelector_template WHERE exemple= :exemp"}}
and my issue is that I can't access to the data inside the json and need your help
Ok so you are basically returning 2 seperate sets of json encodes. It does not work that way. you can only accept a single set of json while reading through ajax. Not two. In your php script i see that you have included that following parts.
$myData1 = array('result' => $sql);
echo json_encode($myData1);
and
$myData = array('result1' => $sqlSelect);
echo json_encode($myData);
you should remove both parts and combine them into one single array using array_merge
$myData1 = array('result' => $sql);
$myData = array('result1' => $sqlSelect);
echo json_encode(array_merge(myData1, $myData));
also in your ajax request, set dataType to json
$.ajax({
type: "POST",
url: url,
dataType: 'json',
data: $(".formCom").serializeArray(),
success: function(reponse){
console.log(reponse);
});
You have 2 problems:
You are sending back invalid json: Instead of echoing out different json strings, you need to build a data-structure (an array or object) and only at the end encode and echo that once. Now you have concatenated json in your response and that makes it really hard to parse.
You are not parsing the json you get back in your javascript. When you return valid json (see 1.), you can add dataType: 'json' to your ajax call to have jQuery parse the response automatically:
$.ajax({
type: "POST",
dataType: 'json',
url: url,
// etc.
So you have a form and you want to submit and that ajax will return some data after submitting the form. And if you want to access the data of response. You need to add this things
1.) Add type = 'post' in your $.ajax object
2.) And use JSON.parse(response)

Send variable to php via ajax

I'm trying to send a input value to php via ajax but I can't seem to get this right. I'm trying to create a datatable based on the user input.
This is my code:
<input class="form-control" id="id1" type="text" name="id1">
My javascript code:
<script type="text/javascript">
$(document).ready(function() {
var oTable = $('#jsontable').dataTable(); //Initialize the datatable
$('#load').on('click',function(){
var user = $(this).attr('id');
if(user != '')
{
$.ajax({
url: 'response.php?method=fetchdata',
data: {url: $('#id1').val()},
dataType: 'json',
success: function(s){
console.log(s);
oTable.fnClearTable();
for(var i = 0; i < s.length; i++) {
oTable.fnAddData([
s[i][0],
s[i][1],
s[i][2],
s[i][3],
s[i][4],
s[i][5],
s[i][6],
s[i][7]
]);
} // End For
},
error: function(e){
console.log(e.responseText);
}
});
}
});
});
</script>
My php script:
<?php
$conn = pg_connect(...);
$id1 = $_POST["id1"];
$result = pg_query_params($conn, 'SELECT * FROM t WHERE id1 = $1 LIMIT 20', array($id1));
while($fetch = pg_fetch_row($result)) {
$output[] = array ($fetch[0],$fetch[1],$fetch[2],$fetch[3],$fetch[4],$fetch[5],$fetch[6],$fetch[7]);
}
echo json_encode($output);
?>
I don't know a lot of js but my php is correct i test it. So i guess the problem is in the javascript code.
The problem is, my datatable is not being created based on the user input.
Thank you!
change
data: {url: $('#id1').val()},
to:
type: 'POST',
data: {id1: $('#id1').val()},
However the problem might be bigger. You might not be getting the correct data from PHP. You can debug by adding the error option to your ajax() call, like this:
$.ajax({
url: 'response.php?method=fetchdata',
type: 'POST',
data: {id1: $('#id1').val()},
dataType: 'json',
success: function(s){
},
error: function (xhr, status, errorThrown) {
console.log(xhr.status);
console.log(xhr.responseText);
}
});
Then check your browser's Console for the output, this should give you some type of error message coming from PHP.
My assumption is that since you are using dataType: 'json', the ajax request expects JSON headers back, but PHP is sending HTML/Text. To fix, add the correct headers before echoing your JSON:
header('Content-Type: application/json');
echo json_encode($output);

jQuery.ajax post is being sent but $_POST is empty

I am trying to send information using AJAX from JavaScript in one file to PHP in another file. When I inspect the page on chrome after I have pressed the button, it shows the values under the form data sub section in networks, however, if I var_dump[$_POST] it shows it is empty.
Here is my JavaScript:
function details(id) {
var data = {"id" : id};
jQuery.ajax({
url: "/Example/includes/detail.php",
type: 'POST',
data: data,
success: function(data){
jQuery('body').append(data);
},
error: function(){
alert("Error");
}
});
}
Here is the PHP:
<?php
$id = $_POST['id'];
$id = (int)$id;
?>
Any help would be greatly appreciated. Thanks

Javascript and PHP. Sending Multiple Array to PHP Using Ajax and Convert it to PHP Array

I need some help. I am trying to send multiply array of width and length to php, straight forward. I don't want to save it to any HTML field, however it's not working. I am getting the width and length from html text are and convert it to a number and then add it to an array in javascript.
Here is the code for that
var widthL = [];
var lengthL = [];
var widths = document.wall.width.value;
var lengths = document.wall.length.value;
var wNumber = Number(widths);
var lNumber = Number(lengths);
widthL.push(JSON.stringify(wNumber));
lengthL.push(JSON.stringify(lNumber));
This is the Ajax code I am using to send it to PHP
$.ajax( {
type: "POST",
url: "./Summary.php",
data: {"widths": widthL, "lengths" : lengthL},
cache: false,
success: function (response) {
console.log("This is the width", widthL, " This is the length", lengthL);
}
});
In PHP I am using this code to receive it. But I am not getting things back.
<?php
$lengths = json_decode($_POST['lengths']);
$widths = json_decode($_POST['widths']);
echo 'This is the width: '.$widtsL;
echo 'This is the length: '.$lengths;
?>
I was hopping that someone could help me out here.
First you should specify the content type in the ajax POST:
$.ajax( {
type: "POST",
url: "./Summary.php",
contentType: "application/json; charset=UTF-8", // Add content type
data: {"widths": widthL, "lengths" : lengthL},
cache: false,
success: function (response) {
console.log("This is the width", widthL, " This is the length", lengthL);
}
});
then in PHP:
$request_body = file_get_contents('php://input'); //This reads the raw POST data
$json = json_decode($request_body); // Then parse it to JSON
$lengths = $json->lengths;
$widths = $json->widths;
please add a POST parameter name as dataType,type it value JSON,
the Ajax data param value use key=value&key=value format
then in php file enter debug code

Sending php value to js via ajax

So, I have the following ajax call:
jQuery.ajax({
type: "GET",
url: custom.ajax_url,
dataType: 'html',
data: ({ action: 'ajax_call'}),
success: function(data){
jQuery('.container').append(data);// Need changes
});
Then my php:
function rhmain_tag() {
// 1. Getting wp tag list:
$args = array(
'orderby' => 'count',
'order' => 'DESC'
);
$tags = get_tags($args);
foreach ( $tags as $tag ) {
echo $tag->term_id;
}
//2. Getting "another.php" file
$template_part_path = 'page-parts/another_php';
get_template_part($template_part_path);
exit;
}
add_action('wp_ajax_ajax_call', 'ajax_call');
add_action('wp_ajax_nopriv_ajax_call', 'ajax_call');
As you can see, in the php function, there are two separate thing going on.
Getting tag list passed onto the js as variable.
echo $tag->term_id; shows a number like this "16508164981650616502165031650416505165071650116520." So, somehow I need to put comma in between each term id (not sure how) so it looks like this : "16508,16498,16506,16502,16503,16504,16505,16507,16501,16520"
Then I need to pass these values to js to be used as a variable (not sure how)
another_php file is passed onto js (Works fine).
Questions:
How to do I add "comma" in between the tag term_id?
How do I pass these tag values to js?
EDIT: Using json_encode to pass data
PHP
function rhmain_tag() {
$template_part_path = 'page-parts/another_job';
$return_data['another_job'] = get_template_part($template_part_path);
$return_data['tag_id'] = '16498';
echo json_encode($return_data);
exit;
}
add_action('wp_ajax_rhmain_tag', 'rhmain_tag');
add_action('wp_ajax_nopriv_rhmain_tag', 'rhmain_tag');
JS:
jQuery.ajax({
type: "GET",
url: custom.ajax_url,
dataType: 'html',
data: ({ action: 'ajax_call'}),
success: function(data){
jQuery('.container').append(data.another_php);
var tag_list = data.tag_id;
});
Using json_encode to send an array containing both data that you require front end you then need to make the following changes to your ajax function.
Change the dataType to json
Access the data as data.another_php and data.tag_id
The full ajax:
jQuery.ajax({
type: "GET",
url: custom.ajax_url,
dataType: 'json',
data: ({ action: 'ajax_call'}),
success: function(data){
jQuery('.container').append(data.another_php);
var tag_list = data.tag_id;
});
To add the comma in between you could use a variable to store instead of echo'ing immediately. Like this :
$args=array(
'orderby'=>'count',
'order'=>'DESC'
);
$tags = get_tags($args);
$tag_list = "";
foreach ( $tags as $tag ) {
$tag_list += $tag->term_id + ",";
}
// Now trim the last comma
$tag_list = rtrim($tag_list, ",");
echo $tag_list;

Categories