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;
}
Related
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);
?>
here is my simple code
$.ajax({
url:'action.php',
method: 'POST',
data:{getcart:1},
success:function(response){
$('#getcart').html(response);//want to display $return_value (from action page)
$('#getcart2').html(response);//want to display $return_value2 (from action page)
}
});
Here i am sending request to action.php
and if in action.php i have echo two variables separately for example.
$return_value = " //Some html here "; echo $return_value;
$return_value2= "//some other html"; echo $return_value2;
So the question is in ajax i have function with argument response . how i will be able to receive these both variables from php and display it in different divs.
i hope you guys help me. thanks.
Send the responses as JSON.
In PHP
$return = array( $return_value, $return_value2 );
echo json_encode($return);
In Javascript
var response = JSON.parse(response);
$("#getcart").html(response[0]);
$("#getcart2").html(response[1]);
your could return a json from action
echo json_encode(array('cart' => $return_value, 'cart2' => $return_value2));
then in your js,
$.ajax({
url:'action.php',
method: 'POST',
data:{getcart:1},
dataType: 'json',
success:function(response){
$('#getcart').html(response.cart1);//want to display $return_value (from action page)
$('#getcart2').html(response.cart2);//want to display $return_value2 (from action page)
}
});
You need to use json_encode in order to get multiple records or data.
action.php
<?php
header('Content-Type: application/json');
$array = array(
'var1'=> 'var value 1',
'var2'=> 'var value 2'
// more variables to go
);
echo json_encode($array);
?>
and then read your variables in JS
dataType: 'json',
success:function(response){
console.log(response.var1);
console.log(response.var2);
$('#getcart').html(response.var1);
$('#getcart2').html(response.var2);
}
You can use json_encode to create an object like:
$array = [
"return_value" => " //Some html here ",
"return_value2" => "//some other html",
];
echo json_encode($array)
Then add dataType: 'json' to your ajax options. The response then will be an object like:
{
"return_value" => " //Some html here ",
"return_value2" => "//some other html",
}
Where you can access the specific values with e.g. response.return_value2 and thus separate them.
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.
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
I finally could receive a response from my AJAX PHP call.
But now in return I get my full HTML site instead of a JSON object or string.
What is wrong here?
var request = $.ajax({
url: "mysite.php",
type: "POST",
data: {select:requestStr},
dataType: "html"
});
request.done(function( data ) {
console.log(JSON.stringify(data));
});
I send a simple string to my php class. This is what I get from the response-text in my developer tool from the browser:
data=Test
On PHP site I just return that respone:
<?php
$myData = array();
$myData['data'] = "test";
if (isset($_POST)) {
$myData['data'] = $_POST;
}
echo json_encode($myData);
exit();
?>
And this is the console.log from the response:
"<!DOCTYPE html>\r\n<html>\r\n<head> ... </html>\"Test\""
EDIT
I only need the end of the response and that is "Test" but not the whole HTML file.
UPDATE
I extracted my PHP class and wrote a Little Version like the PHP code above.
But now my response is an empty object {"data":[]}
Hey put type="Json" instead of the "text"
Put a exit(); after echo json_encode($myData);