how to Receive JSON data sent by ajax in PHP - javascript

I have the data that want sent to backend, its look like
function lihat(){
let id = "12345678";
let profile = [{name:"dave", department : "Engginering"},
{name:"Tedd", department : "Engginering"}]
$.ajax({
type:'POST',
url:'pages/dashboard/dashboard_be.php'
data:{
cekload : true,
keys : id,
dataList : profile
},
success:function(data){
console.log(data);
}
})
the question, how can I receive all of datas sent by ajax in php script
this what I've tried
$id = $_POST['keys'];
$cekload = $_POST['cekload'];
$data = json_decode($_POST['dataList'];);
//I wanna parsing the dataList object and then loop it, how to make it ?
thanks, before

If you're trying to send/receive javascript objects, you need to convert the object to a string before sending and decode it back in php (into an array maybe) before reading.
<script>
let id = "12345678";
let profile = [{name:"dave", department : "Engginering"},
{name:"Tedd", department : "Engginering"}]
$.ajax({
type:'POST',
url:'pages/dashboard/dashboard_be.php',
data:{
cekload : true,
keys : id,
dataList : JSON.stringify(profile)
},
success:function(data){
console.log(data);
}
});
</script>
PHP code:
<?php
$id = $_POST['keys'];
$cekload = $_POST['cekload'];
$data = json_decode($_POST['dataList'], true);
echo $id;
echo $cekload;
print_r($data);
?>

Related

Ajax call to php, get mysql data as array and use in JS function

I'm looking to make an ajax call to a PHP script to get data from MySQL, create a json array and pass it back to the success function of the ajax call, where i will then use it as parameters for a JavaScript function.
This is my ajax call,
$('button[name="message"]').click(function() {
var $row = $(this).closest("tr"); // Find the row
var $tenant_id = $row.find(".col-md-1 id").text(); // Find the tenants ID
var $landlord_id = "<?php echo $id; ?>"
$.ajax({
url : "./message.php",
type : "POST",
async : false,
data: {
landlord_id: $landlord_id,
tenant_id : $tenant_id
},
success: function(data){
console.log(data);
var messages = data;
insertChat(messages.sender_id, messages.body, messages.timestamp);
}
})
});
And this is my PHP file,
<?php
session_start();
require_once('../dbconnect.php');
// update tenants table to show deposit returned
if(isset($_POST['tenant_id'])){
$tenant_id = $_POST['tenant_id'];
$landlord_id = $_POST['landlord_id'];
$sql = "SELECT * from messages WHERE messages.sender_id OR messages.receiver_id = '$tenant_id' AND messages.sender_id OR messages.receiver_id = '$landlord_id'";
$result = mysqli_query($conn, $sql) or die("Error in Selecting " . mysqli_error($conn));
//create an array
$messages = array();
while($row =mysqli_fetch_assoc($result))
{
$messages[] = $row;
}
echo json_encode($messages);
}
?>
If anybody has a link to a tutorial or the individual parts that would be fantastic. I don't even know if the process i have outlined above is correct.
If anybody could tell me the correct way to go about this that would be of great help!
Thanks
Just a few things to adjust your javascript side (I won't explain the php sql injection issue you have... but please research prepare, bind_param and execute):
Since you are returning an ARRAY of $messages from php (json_encoded), you need to loop on those in your success handler.
Add dataType: 'JSON' to your options, so it explicitly expects json returned from php.
And you were missing a couple semicolons ;)
Adjustments added to your code:
$('button[name="message"]').click(function() {
var $row = $(this).closest("tr");
var tenant_id = $row.find(".col-md-1 id").text();
var landlord_id = "<?php echo $id; ?>";
$.ajax({
url : "./message.php",
type : "POST",
data: {
landlord_id: landlord_id,
tenant_id : tenant_id
},
dataType: 'JSON',
success: function(data){
console.log(data);
if (typeof data !== undefined) {
for(var i = 0; i < data.length; i++) {
insertChat(data[i].sender_id, data[i].body, data[i].timestamp);
}
}
}
});
});

How to get multiple return value from php by javaScript / jquery?

This is my javaScript code :
$(document).ready(function() {
$('#IMDB').click(function() {
var MovieID = $('#MovieID').val();
$.post('action/action.php', { url: "http://api.themoviedb.org/3/movie/"+MovieID
+"?append_to_response=credits,images&api_key=myapikey" }, function(data) {
$("#test").html(data);
});
});
});
When I click the button I get imdb id from my input field which I inserted
then I get the actual result from php. this is my php code.
<?php
$url = $_POST['url'];
$url2 = file_get_contents($url);
$json = json_decode($url2, true); //This will convert it to an array
$title = $json['original_title'];
$imdb = $json['imdb_id'];
echo $title;
echo $imdb;
return true;
?>
But I get result like this :
Batman: The Killing Jokett4853102
One is movie title and another is imdb id in same html tage. but I want to display my each result in each html tag like this :
$("#test").html(data); // result 1 -- movie title
$("#test2").html(data); // result 2 --- imdb id
Please help me how to get multiple value?
It would probably be easiest just to output the entire JSON structure and work with that in Javascript, but if you just want the title and id, change your individual echo calls to one with a hash:
header('Content-Type: application/json');
echo json_encode(array(
'title' => $title,
'id' => $imdb
));
Then you can reference them in your javascript using:
var id = data.id;
var title = data.title;
You could simply return an array instead of separated values :
return json_encode([$title,$imdb]);
Then in your js parse the returned data and pluck the attributes you want from it :
data = JSON.parse(data);
$("#test").html(data[0]);
$("#test2").html(data[1]);
Or you could add json to the $.post request the you don't have to parse the returned data :
$.post('action/action.php', { url: ...}, function(data) {
$("#test").html(data[0]);
$("#test2").html(data[1]);
}, "json");
//__^^^^__
Hope this helps.

How to get id and type in php foreach loop and send to server via ajax?

So i have 2 files index.php and changeLikeDislike.php. I think the issue is where javascript is trying to get the type and id but I do not know how I would go about that. My javascript function is being called in the foreach->li->divs. It was working before like this: data: dataString, but I added schoolId into data of ajax as well so it's like this now data: {dataString:dataString, schoolId:schoolId},
index.php
<?php
$last_id = 0;
foreach ($list as $rs) {
$last_id = $rs['id']; // keep the last id for the paging
?>
<li>
<div style="width:100%; color:#000;">
<?php echo '<div class="product_like thumb-div"><img src="like.png" class="rating-image " onclick=changeLikeDislike("like","'.$rs['id'].'")> <br><span id="product_like_'.$rs['id'].'">'.$rs['pLike'].'</span></div>';?>
<?php echo '<div class="product_dislike"><img src="dislike.png" class="rating-image" onclick=changeLikeDislike("dislike","'.$rs['id'].'")><br> <span id="product_dislike_'.$rs['id'].'">'.$rs['pDislike'].'</span></div>';?>
</div>
</li>
<?php
}
?>
<script type="text/javascript">
//begin like and dislike
function changeLikeDislike(type,id){
var dataString = 'id='+ id + '&type=' + type;
$.ajax({
type: "POST",
url: "changeLikeDislike.php",
data: {dataString:dataString, schoolId:schoolId},
cache: false,
success: function(result){
if(result){
console.log('working');
}
}
});//end ajax
}
schoolId works in data but not dataString in ajax How would i go about grabbing those. My php file for reference:
//checks if school page id was brought and stores into variable
if (isset($_POST['schoolId'])) {
$schoolIdFinal = $_POST['schoolId'];
}else {
echo "nope";
}
if (isset($_POST['type'])) {
$type = $_POST['type'];
}else {
echo "nope type";
}
if (isset($_POST['id'])) {
$id = $_POST['id'];
}else {
echo "nope id";
}
my page is echoing out "nope type nope id"
Please change
data: {dataString:dataString, schoolId:schoolId},
to
data: {type:type, id:id, schoolId:schoolId},
to match the params to your PHP script.
data can either be a query string (like your dataString) OR a json struct (like {type:type, id:id, schoolId:schoolId}).
See the documentation of jQuery.ajax():
"The data option can contain either a query string of the form key1=value1&key2=value2, or an object of the form {key1: 'value1', key2: 'value2'}."
see http://api.jquery.com/jquery.ajax/
The issue is in the data bracket. change
data: {dataString:dataString, schoolId:schoolId}
to
data: {dataString:'dataString', schoolId:'schoolId'}
next time do a print_r of $_REQUEST or $_POST to see what fields are being recognized and in this case it looks like its not detecting anything.

How to get the "data" fromphp array in ajax

My code in ajax.
$.ajax({
type: 'post',
url: 'url.php',
dataType: 'JSON',
success: function(data)
{
id = // I want to get the ID data
}
});
In my (data) there's already a different data in it one of that data is the ID. What I want to do is get the ID data and save it to a variable.
Here's my PHP :
$comments = array();
$get = "Some query";
$result = $connection->query($get);
while($row = mysqli_fetch_array($result))
{
$comments[] = $row;
}
echo json_encode($comments);
The parameter "data" will be the response printed by url.php script. It depends on how you are printing the information from PHP script.
If you print it as a json like {'id': 'some_id'}, then the "id" var can be fetched using data.id on your script.
But if you are just printing text, then "data" parameter will be the printed characters from url.php.
To help you more, you can post what you have inside url.php script.
Well, you're expecting the response to be a json object, since you set dataType to 'JSON'. So for example if your php script returns something like that:
<?php $result['data'] = $yourdata; $result['id'] =$id; echo json_encode($result); ?>
Then you can use the result on the client side like this:
success: function(result)
{
id = result.id;
data = result.data;
}

fetch rows from mysql using Ajax

I am trying to retrieve a row from mysql db using ajax, code bellow:
jQuery.ajax({
type: 'POST',
url: 'Connection.php',
dataType: 'text',
data: {'query_id' : query_id},
success: function(response){
data = response;
alert(data['username']); //print undefined!!!
},
error: function(xhr, ajaxOptions, thrownError){
alert("thrownError");
}
});
Here is my mysql php code:
<?php
$con = mysql_connect('****','****','****');
mysql_select_db("eBay",$con);
$username = $_SESSION['username'];
$query_id = $_POST['query_id'];
$myquery = "SELECT * FROM `Output` WHERE `username` =" '$username';
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
}
$data = mysql_fetch_array($query);
echo ($data);
mysql_close($server);
?>
In the response I get, I have undefined array cell. Any idea?
to return just the username from php:
$data = mysql_fetch_assoc($query)['username'];
in your javascript you should be able to do alert(data) instead of searching for the username tuple in an array.
Ideally you should return your data back in json instead of text that way it can remain structured and easier to access in javascript. You will need to change your ajax option to dataType: 'json'
and the PHP code to :
$data = json_encode(mysql_fetch_assoc($query));
You are getting array in $data variable so you should use json_encode function to get all values from resulting row like this-
$myquery = "SELECT * FROM `Output` WHERE `username` ='".$username."'";
foreach ($myquery as $test)
{
$field1_value =$test->name_of_field1_in_db;
$field2_value =$test->name_of_field2_in_db;
$field3_value =$test->name_of_field3_in_db;
}
$all_values_in_array=array('field1'=>$field1_value,'field2'=>$field2_value,'field3'=>$field3_value,);
echo json_encode(echo json_encode($arr_provider);
and get all value on ajax suucess function like this--
success: function(response){
var pro = jQuery.parseJSON(response);
var field1_val=pro.field1; //var field1 contain value of field1 in db
var field2_val=pro.field2;
var field3_val=pro.field3;
},
hope it will help you.
Best of Luck

Categories