Get values from array from php ajax post - php

I am currently working on a php project with the user of ajax. I need to populate values from a database into an html drop down box and I want to do this from an ajax post.
For all the other ajax so far in the project I have been using $.post but I do not need to post anything to the php script as it is just going to retrieve everything from the database. what I need to do is the php script retrieves the information from a database and populates the information into an array and then return the array to the calling php script that calls that ajax.
Is the array idea the best idea, if so how do I get the contents of the array from the ajax, or is there a better way and how do I do the ajax call if I am not doing a post of anything.
Thanks for any help you can provide.

The easiest way to do what you're describing is using JSON with your jQuery Ajax request, like so:
// PHP side
<?php
// Do your database query, and then echo out your desired data like so:
echo json_encode(array(
'test' => 'your data',
'test2' => array('you can also use', 'arrays'),
'test3' => array('or' => 'keyed arrays'),
));
die(); // don't echo anything other JSON, or you'll get errors
?>
// Javascript side
$.post("url.com", post_data, function(json)
{
// Do something with your data here:
alert(json.test);
alert(json.test2[1]);
alert(json.test3["or"]);
}, "json");

$.ajax({
url: "your_script.php",
global: false,
type: "POST",
data: {},
dataType: "json",
async:false,
success: function(results){
//append your json results to your DOM
$('#some_div').html('');
for(var i = 0; i < results.length; i ++)
{
$('#some_div').append('<p>' + results[i].html + '</p>');
}
}
});
and your PHP will need to json_encode the results...
die(json_encode(array(array('html' => 'first'), array('html' => 'second'))));

Related

Can't return json array from PHP to jQuery AJAX

Problem
I am using AJAX jQuery with a dropdown to get some response from PHP. So far i wanted just one row from database, but now i want another array.
Current situation
front -
$.ajax({
type: "POST",
url: "project_details.php",
data: data_string,
cache: false,
success: function(data){
if(data){
var json = data;
obj = JSON.parse(json);
$("#project-name").text(obj.project_name);
$("#start-date").text(obj.start_date);
}
}
});
back -
$result=mysqli_query($db,"SELECT distinct project_name,start_date FROM `projects` WHERE a.supervisor_email = '$email' and a.project_id = '$project'");
$count=mysqli_num_rows($result);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
if($count==1){
echo json_encode(array("project_name" =>$row['project_name'],
"start_date" => $start->format("d M,Y"))); }
What I want -
I need another array returned from PHP -
$result_1=mysqli_query($db,"SELECT member_email FROM `projects` WHERE a.supervisor_email
$email' and a.project_id = '$project'");
$row_1=mysqli_fetch_array($result,MYSQLI_ASSOC);
so the final echo should be something like
if($count==1){
echo json_encode(array($row_1,"project_name" =>$row['project_name'],
"start_date" => $start->format("d M,Y"))); }
I can't figure out how to read this from jQuery
Note that table I'm using is at project_id, member_email level
First of all, specify the datatype as json.
This way you do not need..
var json = data;
obj = JSON.parse(json);
..and you can use the data variable directly. Also, depending on what you are doing with the AJAX data, it may be better to use .html() instead of .text().
In regards to your original question, I see that you have added $row_1 to your existing array but it will not work that way. I don't know what it contains, but seems to be an array. Since AJAX is expecting json format you need to have key=>value pairs. How about like this?
PHP:
$json_arr = array();
while ($row_1=mysqli_fetch_array($result,MYSQLI_ASSOC)) {
$email{'member_email'] = $row_1['member_email'];
}
if($count==1){
echo json_encode(array("member_email" =>$email,
"project_name" =>$row['project_name'],
"start_date" => $start->format("d M,Y")));
}
AJAX:
$.ajax({
type: "POST",
url: "project_details.php",
data: data_string,
dataType: "json",
cache: false,
success: function(data){
if(data){
$("#member_email").text(data.member_email);
$("#project-name").text(data.project_name);
$("#start-date").text(data.start_date);
}
}
});
I'm not exactly sure if I got your question right. But you would like to have $row_1 as additional array to be echoed, am i right? If so, Try this:
PHP
echo json_encode( array(
"row_1" => $row_1,
"project_name" =>$row['project_name'],
"start_date" => $start->format("d M,Y")
)
);
Then on your $.ajax
use data.row_1 , data.project_name, data.start_date to refer to your encoded value
Note: I would also like to recommend what #EternalHour said that you should use dataType: 'json' instead for a much cleaner approach, and it seems to be easier that way too.
Please tell me if my recommended code worked. If not would you please tell me the error that comes with it too.
Do you get what you want when you do a console.log(obj); ?
Cause there is no "project_name" inside
your SQL-Select
Regarding jQuery .. tried $.each?
$.each(obj, function(key, project)
{
...text(project.project_name);
});

jQuery.parseJSON trouble

I'm pretty unfamiliar with JSON, as I haven't used it too much and I'm trying to learn some of it.
So I have an ajax request that gives me this: [{"palvelu_id":"1","palvelu_nimi":"Meikkikoulutus","palvelu_kuvaus":"Kuvaus","palvelu_hinta":"10"}]
And I'm trying to use jQuery.parseJSON to use it on a page.
var palveluData = $.parseJSON(d);
$("#ajanvarausInfo").html(palveluData.palvelu_kuvaus+"<br>"+palveluData.palvelu_hinta);
But I get undefined as answer, what am I doing wrong here?
You should get the first element of the array:
$("#ajanvarausInfo").html(palveluData[0].palvelu_kuvaus+"<br>...");
If the array has more than 1 element you should iterate through the array, you can use jQuery $.each() utility function.
EDIT::
Wow, looks like ive kept the window open for to long before replying -.-
You have an outter array there, so you need to take that into account ( your php side might be not correct )
$("#ajanvarausInfo").html(palveluData[0].palvelu_kuvaus+"<br>"+palveluData[0].palvelu_hinta);
Usually you not need that when properly setting everything up
$.ajax ({
url: 'myurl',
type: 'POST',
data: { key_value pairs here },
dataType: 'json',
success: function(response){
$("#ajanvarausInfo").html(response.palvelu_kuvaus+"<br>"+response.palvelu_hinta);
});
});
On the php side
$response = array(
"palvelu_id" => "1",
"palvelu_nimi" => "Meikkikoulutus",
"palvelu_kuvaus" => "Kuvaus",
"palvelu_hinta" => "10"
);
echo json_encode($response);

Pass PHP Variable to AJAX Variable

After a completed calculation form where the total is loaded in via PHP we have 4 pieces of data (variables left over with PHP)
$totalprice;
$totalduration;
$totaldives;
$totalhire;
At the moment the PHP ends with echo for each of these. The ajax then collects them like this.
success: function() {
$('#results').html();
The problem is that echos all results.
I would like to send the $totalprice to $('#resultsprice').html(); the $totalduration to $('#resultsduration').html(); etc etc...
Any ideas how to do that?
Marvellous
You could return a JSON string from PHP:
echo json_encode( array('totalprice'=>$totalprice, 'totalduration'=>$totalduration, 'totaldives'=>$totaldives, 'totalhire'=>$totalhire));
Then, change your jquery ajax call to set the response to json:
$.ajax({
url: your_url,
dataType: 'json',
success: function (data) {
$('#resultsprice').html(data.totalprice);
$('#resultsduration').html(data.totalduration);
});
Use the php function json_encode(). First in php create an array with the 4 variables. Json encode the array and echo the result. Then in jQuery use jQuery.parseJSON() to parse the json code to javascript variables. Here's an example:
PHP:
$data = array('var1' => 'value1', 'var2' => 'value2', 'var3' => 'value3', 'var4' => 'value14');
echo json_encode($data);
jQuery:
success: function(data) {
data = jQuery.parseJSON(data);
}
Use JSON as data format.
In PHP, you can use json_encode to create a JSON string. compact is an easy way to create an associative array from variables:
echo json_encode(compact('totalprice', 'totalduration', 'totaldives', 'totalhire'));
// compact produces array('totalprice' => <value-of-totalprice>, ...)
// json_encode produces '{"totalprice": <value>, ...}'
In jQuery, set the dataType option to json and the argument passed to the success callback will be a JavaScript object:
$.ajax({
// ... all other options ...
dataType: 'json',
success: function(data) {
// use .html() only for HTML data
$('#resultsprice').text(data.totalprice);
$('#resultsduration').text(data.totalduration);
//...
}
});
What is actually returned from the AJAX call? If it's a JSON object containing the various values, you can set each one to various HTML elements. Something like this:
success: function(data) {
$('#resultsprice').html(data.TotalPrice);
$('#resultsduration').html(data.TotalDuration);
// etc.
}

Cant Post JSON Object using Jquery.post()

I have the following object that gets created in my javascript application.
poll_data[active_question] = {
'question': $('div.question_wrap textarea').attr('value'),
'answers': [
$('div.answer_wrap input#0').attr('value'),
$('div.answer_wrap input#1').attr('value'),
$('div.answer_wrap input#2').attr('value'),
$('div.answer_wrap input#3').attr('value'),
$('div.answer_wrap input#4').attr('value'),
$('div.answer_wrap input#5').attr('value')
]
};
active_question is set to 'poll', 0, 1, 2, 3, 4, or 5 depending on the question being worked on at the moment. I am trying to post this object to a php script using the following JS code.
$.ajax({
url: '/somewebsite/poll/create?json=show',
type: 'POST',
// dataType: 'json',
data: poll_data,
contentType: 'application/json; charset=utf-8',
success: function(data) {
alert(data);
}
});
My PHP code is very simple.
echo json_encode($_POST); exit;
When I run the script and click the button that triggers the submission of the data, I receive the alert (so the actual ajax code works), but the result from my PHP script is just an empty array. I think that this is an issue with the way the object is constructed, but I am not sure, and have not been able to find a work around.
Thanks in advance.
Okay, a few things:
poll_data is not a valid JSON object. You would have to use poll_data[active_question], which IS a valid JSON object. jQuery should serialize this correctly. Remove the contentType -- I am pretty sure that is for php (not positive) but your code wouldn't work for me until I removed it. Finally, the appending of json=show to the query string doesn't do anything..it will just be ignored.
A couple minor things too: you can use .val() instead of .attr('value'), and have you looked into .serialize() to create your post data for you?
do this on server
$data;
$data->question=$_POST['question']
$data->answer=$_POST['answers']
echo json_encode($data);
do this for ajax request
$.ajax({
url: '/somewebsite/poll/create?json=show',
type:'POST',
//modified data proprty
data:poll_data[active_question],
success: function(data) {
alert(data);
}
});

Jquery Ajax Returned Array - how to handle in Javascript

If someone could assist me please. I'm doing a jquery Ajax post, for some reason the Json object isn't working so just returning a php array instead
$.post
(
"classes/RegisterUser.php",
$("#frmRegistration").serialize(),
function(data)
{
alert(data);
}
);
The data is returned to Javascript 100% as
array
(
[key]=>value
[Name] => SomeOneName
[Surname] => SomeOneSurName
)
How would i go about getting the value of Surname in Javascript?
Thanks for your assistance?
Regards
Expanding on The MYYN's answer, after you get your script to return JSON, you must specify that you're receiving JSON and act accordingly. You can do this with .ajax():
$.ajax({
type: 'post',
url: 'classes/RegisterUser.php',
data: $("#frmRegistration").serialize(),
dataType: 'json',
success: function(obj) {
// This alerts SomeOneSurName
alert(obj.Surname);
}
});
Maybe your PHP script should return json (right now it seem to return something like var_dump($some_ary);. A proper way to do this is via php's json_encode.

Categories