How to Parse php json_decode data to Jquery Ajax request [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
The current problem now is this, the below files are working perfectly well, but when using console.log(data), it prints out the result I wanted very well.
But what I want is to print out the result in a html tag (div) profoundly instead of console.log().
The Php File section
<?php
$transaction_id = $_POST['transaction_id'];//get the Transaction ID from Ajax request..
//get the full transaction details as an json from VoguePay
$json = file_get_contents('https://example.com/?v_transaction_id=' . $transaction_id . '&type=json');
$transaction=json_decode($json, true);
//header('Content-Type: application/json');
echo json_encode($transaction);
The Ajax Section...
//clear the display section
$("#id-input2").html('');
var data="";
//call the Ajax Request..
$.ajax({
url: "php/fetch_transaction_id.php",
type: "POST",
data: {transaction_id:transaction_id},
dataType: "json",
success: function (vp_response) {
$.each(vp_response, function(index, value) {
data=(index + ': ' + value);
console.log(data);
});
$('#searchID').val('Data Recieved!');
},
});
Here is the output for using console.log();:
cur: NGN
transaction_id: 5a3182d82a8c6
email: talk2awe2004#example.com
total_amount: 1016.7000
total: 1000
merchant_ref:
memo: MLM Bank Union Creation
status: Approved
date: 2017-12-13 20:49:26
method: MasterCard & Verve (Naira)
referrer: https://www.mlmbank.net/Leaders/create.html
total_credited_to_merchant: 1001.450000
extra_charges_by_merchant: 16.700000
charges_paid_by_merchant: 15.250000
fund_maturity: 2017-12-15
merchant_id: 3362-0054095
total_paid_by_buyer: 1000
process_duration: 0.000395
I want same using a html tag instead.

You can return your array in JSON format with application/json content-type
<?php
if(isset($_POST['transaction_id'])) {
//get the full transaction details
$json = file_get_contents('https://example.com');
//create new array to store our transaction
$transaction = json_decode($json, true);
// Here you can do something with $transaction
// And return it in JSON format for ajax request
header('Content-Type: application/json');
echo json_encode($transaction);
}
After that you can get this json in ajax like this
<script>
$.get('transaction.php', {transaction_id: 'SOME ID'}, function(data) {
console.log(data);
});
</script>
jQuery will parse data as javascript object because of content-type

If the link you reach out to has raw json, you can simply echo it out :
PHP
if (isset($_POST['transaction_id']))
{
$TransactionId = $_POST['transaction_id'];
echo file_get_contents('https://example.com');
}
You want to add the success event handler in your ajax call and then $.each through your response. :
*Note : Make sure you have dataType: 'json', this tells jquery to parse the json response.
Javascript :
$.ajax({
type: 'POST',
url: '/yourphpfile.php',
data : {
transaction_id: '0'
},
dataType: 'json',
success : function(response) {
$.each(response, function(key, value) {
console.log(value.whatever);
});
}
});
Read more on accessing json values : jQuery Ajax: get specific object value

Related

How to get the ajax response from controller to a PHP variable on the view [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 4 years ago.
I am making an ajax request to the controller as shown below;
<script>
$(function() {
// when select changes
$('#languageselector').on('change', function() {
// create data from form input(s)
let formData = $('#myForm').serialize();
// send data to your endpoint
$.ajax({
url: '/selected/languageId',
method: 'post',
data: formData,
dataType: 'json', // we expect a json response
success: function(response) {
// whatever you want to do here. Let's console.log the response
console.log(response);
}
});
});
});
</script>
On the controller, I am returning
public function selectedLangId(Request $request)
{
return response()->json(['success'=> $request->languageSelected]);
}
I would like to get this JSON response json(['success'=> $request->languageSelected]) and assign it to a PHP variable on the view.
How do I manage that?
From the logs, the response is in the form of {"success":"2"}
I would want to get this JSON response and save it into a PHP variable on the view....
I want to use this variable to display certain forms according to this selection.
$.ajax({
type: "POST",
url: '<?php echo Router::url(array('controller'=>'nameofcontroller','action'=>'controllerfunction'));?>',
data:formdata ,
success: function (response)
{
if (response > 0)
{
} else
{
$('#check_mail').html('');
}
}
});

How to store value passed by ajax to database? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to display data or value return by the ajax function to be store in php variable as mentioned below. Any help?
This is my code
function getUserInfo()
{
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + acToken,
data: null,
success: function(resp) {
user = resp;
console.log(user);
$('#uName').text('Welcome ' + user.name);
$('#imgHolder').attr('src', user.picture);
},
dataType: "jsonp"
});
}
I want to display in php variable as
$name=$_POST['uName'];
$pics=$_POST['imgHolder'];
echo $name;
echo $pics;
I would use PHP to make the request and store the result in an array, since you need to use the result in php
$acToken='your value';
$result = file_get_content('https://www.googleapis.com/oauth2/v1/userinfo?access_token='.$acToken);
echo '<pre>';
print_r($result);
echo '<pre>';
make sure to assing a value to $acToken;
In your javascript, create ajax post request to your php url:
$.ajax({
type: "POST",
url: "some.php",
data: { uName: "John", imgHolder: "img" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
For more information, you can read jQuery AJAX documentation
try below:
$name=$_POST['uName'];
$pics=$_POST['imgHolder'];
echo json_encode(array('name'=>$name,'pics'=>$pics));
as that help for you

Ajax request for PHP to return HTML [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I have an element on a page that when clicked will make an ajax request to a receiver.php file:
<script>
function send(id){
$.ajax({
type: 'POST',
dataType: 'html',
url: 'receiver.php',
data: {id: id}
});
}
</script>
<img src="foo.bar" onclick="send(id)"/> <!-- simplified -->
My idea is that this receiver.php file will receive the id, then output a whole page of HTML based on that id
However, when I click on the element, the new HTML page that I expect doesn't show up. When I go to the Chrome inspector, Network tab I can see the request and the response is exactly the HTML content I need, but why doesn't it change to that new page and stay on the old page instead?
EDIT: This is my receiver.php, for testing purpose:
<html>
<head></head>
<body>
<?php
echo "<p>".$_POST['comid']."</p>";
echo "<p> foo foo </p>";
?>
</body>
</html>
this is the response:
<html>
<head></head>
<body>
<p>3</p><p> foo foo </p> </body>
</html>
Perhaps in your receiver.php script you're doing something like this, where you determine which HTML page to output depending on the id that it is receiving.
switch ($_POST['id']) {
case 'foo':
$filepath = 'bar';
break;
...
}
readfile($filepath);
You would have to reflect that in your AJAX query, using the success function of $.ajax.
function send(id) {
$.ajax({
type: 'POST',
dataType: 'html',
url: 'receiver.php',
data: {id: id},
success: function (data) {
// Replace the whole body with the new HTML page
var newDoc = document.open('text/html', 'replace');
newDoc.write(data);
newDoc.close();
}
});
}
You have to do something with the result that comes back from you AJAX call:
function send(id){
$.ajax({
type: 'POST',
dataType: 'html',
url: 'receiver.php',
data: {id: id},
success: function(data){
console.log(data);
}
});
}

Retrieve JSON Data with AJAX

Im trying to retrieve some data from JSON object which holds location information such as streetname, postcode etc. But nothing is being retrieved when i try and put it in my div. Can anybody see where im going wrong with this?
This is my ajax code to request and retrieve the data
var criterion = document.getElementById("address").value;
$.ajax({
url: 'process.php',
type: 'GET',
data: 'address='+ criterion,
success: function(data)
{
$('#txtHint').html(data);
$.each(data, function(i,value)
{
var str = "Postcode: ";
str += value.postcode;
$('#txtHint').html(str);
});
//alert("Postcode: " + data.postcode);
},
error: function(e)
{
//called when there is an error
console.log(e.message);
alert("error");
}
});
When this is run in the broswer is just says "Postcode: undefined".
This is the php code to select the data from the database.
$sql="SELECT * FROM carparktest WHERE postcode LIKE '".$search."%'";
$result = mysql_query($sql);
while($r = mysql_fetch_assoc($result)) $rows[] = $r;
echo json_encode($rows), "\n"; //Puts each row onto a new line in the json data
You are missing the data type:
$.ajax({
dataType: 'json'
})
You can use also the $.getJSON
EDIT: example of JSON
$.getJSON('process.php', { address: criterion } function(data) {
//do what you need with the data
alert(data);
}).error(function() { alert("error"); });
Just look at what your code is doing.
First, put the data directly into the #txtHint box.
Then, for each data element, create the string "Postcode: "+value.postcode (without even checking if value.postcode exists - it probably doesn't) and overwrite the html in #txtHint with it.
End result: the script is doing exactly what you told it to do.
Remove that loop thing, and see what you get.
Does your JSON data represent multiple rows containing the same object structure? Please alert the data object in your success function and post it so we can help you debug it.
Use the
dataType: 'json'
param in your ajax call
or use $.getJSON() Which will automatically convert JSON data into a JS object.
You can also convert the JSON response into JS object yourself using $.parseJSON() inside success callback like this
data = $.parseJSON(data);
This works for me on your site:
function showCarPark(){
var criterion = $('#address').val();
// Assuming this does something, it's yours ;)
codeAddress(criterion);
$.ajax({
url: 'process.php',
type: 'GET',
dataType: 'json',
data: {
address: criterion
},
success: function(data)
{
$("#txtHint").html("");
$.each(data, function(k,v)
{
$("#txtHint").append("Postcode: " + v.postcode + "<br/>");
});
},
error: function(e)
{
alert(e.message);
}
});
}

jQuery ajax request with json response, how to?

I am sending an ajax request with two post values, the first is "action" which defines what actions my php script has to parse, the other is "id" which is the id of the user it has to parse the script for.
The server returns 6 values inside an array() and is then encoded to JSON with the PHP function: json_encode();
Some of my responses are HTML, but when I encode it to JSON, it escapes "/" so it becomes "\/"
How do I disable that?
Also when I don't know how to display this in jQuery when I get the server response, I just thought that putting it all into a div would just display the numbers and HTML codes I had requested, but it displays the array as it is encoded in PHP.
PHP
$response = array();
$response[] = "<a href=''>link</a>";
$response[] = 1;
echo json_encode($response);
jQuery:
$.ajax({
type: "POST",
dataType: "json",
url: "main.php",
data: "action=loadall&id=" + id,
complete: function(data) {
$('#main').html(data.responseText);
}
});
How do I make this into working JSON?
You need to call the
$.parseJSON();
For example:
...
success: function(data){
var json = $.parseJSON(data); // create an object with the key of the array
alert(json.html); // where html is the key of array that you want, $response['html'] = "<a>something..</a>";
},
error: function(data){
var json = $.parseJSON(data);
alert(json.error);
} ...
see this in
http://api.jquery.com/jQuery.parseJSON/
if you still have the problem of slashes:
search for security.magicquotes.disabling.php
or:
function.stripslashes.php
Note:
This answer here is for those who try to use $.ajax with the dataType property set to json and even that got the wrong response type. Defining the header('Content-type: application/json'); in the server may correct the problem, but if you are returning text/html or any other type, the $.ajax method should convert it to json. I make a test with older versions of jQuery and only after version 1.4.4 the $.ajax force to convert any content-type to the dataType passed. So if you have this problem, try to update your jQuery version.
Firstly, it will help if you set the headers of your PHP to serve JSON:
header('Content-type: application/json');
Secondly, it will help to adjust your ajax call:
$.ajax({
url: "main.php",
type: "POST",
dataType: "json",
data: {"action": "loadall", "id": id},
success: function(data){
console.log(data);
},
error: function(error){
console.log("Error:");
console.log(error);
}
});
If successful, the response you receieve should be picked up as true JSON and an object should be logged to console.
NOTE: If you want to pick up pure html, you might want to consider using another method to JSON, but I personally recommend using JSON and rendering it into html using templates (such as Handlebars js).
Since you are creating a markup as a string you don't have convert it into json. Just send it as it is combining all the array elements using implode method. Try this.
PHP change
$response = array();
$response[] = "<a href=''>link</a>";
$response[] = 1;
echo implode("", $response);//<-----Combine array items into single string
JS (Change the dataType from json to html or just don't set it jQuery will figure it out)
$.ajax({
type: "POST",
dataType: "html",
url: "main.php",
data: "action=loadall&id=" + id,
success: function(response){
$('#main').html(response);
}
});
Connect your javascript clientside controller and php serverside controller using sending and receiving opcodes with binded data. So your php code can send as response functional delta for js recepient/listener
see https://github.com/ArtNazarov/LazyJs
Sorry for my bad English
Try this code. You don't require the parse function because your data type is JSON so it is return JSON object.
$.ajax({
url : base_url+"Login/submit",
type: "POST",
dataType: "json",
data : {
'username': username,
'password': password
},
success: function(data)
{
alert(data.status);
}
});

Categories