Create array from PHP SQL query and pass it to ajax - javascript

I'm trying to get my results from a SQL query into an array in javascript. I'm trying the following:
PHP:
$query = mysqli_query($connection, "select a, b, c from table");
$result_a = array();
$result_b = array();
$result_c = array();
while($row = mysqli_fetch_array($query)) {
$result_a[] = $row['a'];
$result_b[] = $row['b'];
$result_c[] = $row['c'];
}
echo json_encode(array('a'=>$result_a,'b'=>$result_b, 'c'=>$result_c ));
javascript:
$.ajax({
type: "POST",
url: "http://mywebsite.com/data.php",
data: dataString3,
cache: false,
error: function(){},
success: function(data){
alert (data.a);
alert (data.b);
alert (data.c);
},
});
return false;
The PHP arrays have the data I'm looking for but the alerts in javascript are undefined. Any help would be appreciated.

In PHP you echo data in json format json_encode(array('a'=>$result_a,'b'=>$result_b, 'c'=>$result_c ));
So if you want to use the json as an object directly in the ajax success function, you need tell the ajax call "You are expecting a json object coming bakc!";
So you should modified js code to this:
$.ajax({
type: "POST",
url: "http://mywebsite.com/data.php",
data: dataString3,
cache: false,
dataType : "json", // <------here, auto parse json for you
error: function(){},
success: function(data){
alert (data.a);
alert (data.b);
alert (data.c);
}
});
Or in the success function, manually parse json before use;
$.ajax({
type: "POST",
url: "http://mywebsite.com/data.php",
data: dataString3,
cache: false
error: function(){},
success: function(data){
var obj = jQuery.parseJSON(data); // <---- here, manual parse
alert (obj.a);
alert (obj.b);
alert (obj.c);
}
});

Related

Jquery and AJAX post to php data attribute?

Hello I have the following AJAX code:
var formData = new FormData($('form')[0]);
$.ajax({
url: 'saveImage.php', //Server script to process data
type: 'POST',
data: formData,
processData: false,
success: function(data){
console.log(data);
}
});
It works great and it loads up the PHP page it the background like it should:
<?php
include_once "mysql_connect.php";
$imageName = mysql_real_escape_string($_FILES["Image1"]["name"]);
$imageData = '';
$imageext = '';
if($imageName != null){
$imageData = mysql_real_escape_string(file_get_contents($_FILES["Image1"]["tmp_name"]));
$imageType = mysql_real_escape_string($_FILES["Image1"]["type"]);
$imageSize = getimagesize($_FILES["Image1"]["tmp_name"]);
$imageType = mysql_real_escape_string($_FILES["Image1"]["type"]);
$FileSize = FileSize($_FILES["Image1"]["tmp_name"]);
$imageext = mysql_real_escape_string($imageSize['mime']);
}
$query=mysql_query("INSERT INTO pictures (`id`, `imagedata`, `imageext`) VALUES ('', '$imageData', '$imageext');");
echo $imageext;
?>
The only problem is that the PHP page cant find the variable Image1 which is the name of the input in the form. Have I done something wrong. I was thinking that maybe in the data parameter in the Ajax it would be something like this but correct:
data: "Image1"=formData,
Is that a thing, if not why cant my PHP see that input field?
You forgot cache and contentType properties in your Ajax function. Try that it should work :
var formData = new FormData($('form')[0]);
$.ajax({
type: "POST",
url: "saveImage.php",
processData: false,
contentType: false,
cache:false,
data: formData,
success: function(data){
console.log(data);
}
});

No alert from Ajax call

I´m trying to alert some data from a Ajax call. Can anyone spot what I am doing wrong?
PHP
while($row = $stmt->fetch()){
echo json_encode($row);
}
echo "Done!";
Result from Json_encode / Network Preview
{"flakId":"21098-10_flak-2"}{"flakId":"21098-10_flak-1"}Done!
JS
if(chosenObjNr){
alert('I CAN see this alert')
$.ajax({
url:'php/update.php',
type: 'POST',
data: 'chosenObjNr=' + chosenObjNr,
dataType: 'json',
error: function (data){ alert("failed, i can see this!");},
success: function(data){
alert('I cannot see this alert!');
alert(data);
var data0;
data0 = data[0];
alert(data0);
var falkId;
flakId = data[0];
alert(flakId);
console.log(data);
}
});
};
RESULT
No alert and nothing in the console.
The problem is, that the success part of the ajax never will run. You defined the dataType as a json, so it expecting json. Your PHP is echos 2 json and an unwanted string.
So, to check what is your error add the fail function as Sina sad in the comment:
if (chosenObjNr) {
alert('I CAN see this alert')
$.ajax({
url: 'php/update.php',
type: 'POST',
data: 'chosenObjNr=' + chosenObjNr,
dataType: 'json',
}).done(function (data) {
alert('I cannot see this alert!');
//Do what you want to do here
}).fail(function (msg) {
alert('An error occured: ' + msg.statusText);
});
}
And, if you want to fix your .php remove the echo 'Done'; part, and add your records to an array, and when its done, encode it to json:
$return = array();
while ($row = $stmt->fetch()) {
$return[] = $row;
}
echo json_encode($return);

Getting a particular value from ajax response

I am using ajax with masonry
Ajax code: This ajax is used to get data from
$.ajax({
type: "get",
url: "some.php",
dataType: "text",
success: function(data) {
if (data && data.length > 0) {
$items = $(data);
$grid.append( $items )
.masonry('appended', $items);
$(this).find(".loading").hide();
}
}
Php Part: This is just a small or sufficient part of php file to understand the problem
$b= "sv";
echo "asjdgsajd";
echo "a";
echo $b;
now i am getting everything correctly but i want to use say value of $b for setting a attribute value and also other values as content but how can i particularly get value of $b?
Thankyou
Change the dataType to json.
$.ajax({
type: "get",
url: "some.php",
dataType: "json",
success: function(data) {
//data will hold an object with your response data, no need to parse
console.log('Do whatever you want with ' + data.b + '.');
}
In some.php do the following:
$response =array(
'b' => "sv",
'a' => "asjdgsajd",
'c' => "a"
);
echo json_encode($response);
echo $b;
The items of the associative array will end up as properties of a javascript object, that you can use in your success callback (or done function as success is deprecated).
Try using json and change your php to send the json response that way you can send more content and access them on client side as you need it.
PHP Script :
$outArr=array("b"=>"sv","content1"=>"asjdgsajd","content2"=>"a");
$jsonResponse=json_encode($outArr);
echo $jsonResponse;
In AJAX function you can access your data like this:
$.ajax({
type: "get",
url: "some.php",
dataType: "text",
success: function(data) {
if (data && data.length > 0) {
data=$.parseJSON( data ); //parse response string
b=data.b;//value of b
content1=data.content1;//value of content1
$("#exampleDiv").attr("id",b).html(content1); //set the attribute and content here for an example div
}
}
})

send multidimensional array to php using ajax as json and receive html text to show in a div

First part is completed, The data is successfully sent to php using ajax as json (I did it by following an answer to an already posted question on this site).
Now how to access these values in php, and after using the string in abc[2] as sql query and printing the result in php(second page) using html in a table format (in second page), how to receive that response after ajax call completes in first page to show it in a div in first page.
Actually I am not asking about the procedure of running query and displaying values.
I am facing problem in accessing these array values in php and displaying them back in first page using ajax.
whenever I return some value from first page (using echo or print function), I receive an alert about syntax error: unexpected tocken after the ajax call comes back from second page. The code in first page is
var abc= {};
abc[0] = {};
abc[0]['name'] = 'first col';
abc[0]['width'] = 123;
abc[1] = {};
abc[1]['name'] = 'second col';
abc[1]['width'] = 456;
abc[2]="abcdefghijklmnopqrstuvwxyz";
$.ajax(
{
type: "POST",
url: "query.php",
data: {abc: abc},
dataType: "json",
beforeSend:function()
{
// Do something before sending request to server
},
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
},
success: function(data)
{
alert(data);
}
});
I don't know exactly...
you can try this one..
$param = cleanAll();
You can do it in this way :
Send parameter to your query.php file using ajax.
In query.php file write logic to process on posted data save/edit/fetch data from/to DB
and create html to print in div and echo that html
Inside your ajax call when success put that html to div which is returned from query.php.
Here are few changes on your ajax code:
Array will like this
var abc= {abc :[{name:'first col',width:123},{name:'second col',width:456},{name:"abcdefghijklmnopqrstuvwxyz",width:456}] };
Ajax will like this
$.ajax(
{
type: "POST",
url: "query.php",
data: abc,
dataType: "json",
beforeSend:function()
{
// Do something before sending request to server
},
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
},
success: function(my_html)
{
$('#my_div').val(my_html);
}
});
Code is not tested but it should work.
As I understand from my recent experiment, array will be placed to object before converting to JSON. Below my code:
JavaScript:
...
var read_numbers = new Array();
...
function read_ajax_done(num, num_in_word){
rec_count_in_cache = rec_count_in_cache + 1;
var number = {"num" : "", "word" : ""}; // Object type
number.num = num;
number.word = num_in_word;
read_numbers[rec_count_in_cache-1] = number; // Array is multidimensional
}
function save_to_db(read_numbers) {
var object_read_numbers = {"read_numbers" : read_numbers}; // Array placed to object
JSON_read_numbers = JSON.stringify(object_read_numbers); // Object converted to JSON
request = $.ajax({
type : "POST",
url : "post.php",
data : {read_numbers : JSON_read_numbers}
});
request.done(function(msg) {
alert("Respond: "+ msg);
});
request.fail(function(jqXHR, textStatus) {
alert("Function inaccessible: " + textStatus)
});
}
PHP:
if (isset($_POST["read_numbers"])) {
$read_numbers = json_decode($_POST["read_numbers"], TRUE);
.....
$response = $read_numbers["read_numbers"][n]["word"];
}
echo $response;
Second Page PHP
<?php
//need for displaying them back to the $.ajax caller
header('Content-type: application/json');
//accessing data
$post = $_POST['abc'];
/*
* how to access multid array
* $post[0]['name'] = 'first col'
* $post[0]['width'] = 123
* $post[1][name] = 'second col'
* $post[2] = 'abcdefghijklmnopqrstuvwxyz'
*/
//now to pass them back to your $.ajax caller
echo json_encode($post);
?>
First Page
$.ajax(
{
type: "POST",
url: "query.php",
data: {abc: abc},
dataType: "json",
success: function(data)
{
//prints your response variable
console.log(data);
}
});

jquery json post not working

Well, im trying to post a variable in jquery to my controller. But it seems that the posting is not successful. I am not getting any value when i try to retrieve it in my controller. It says undefined index. Here's what I have:
my jquery:
$(document).ready(function(){
$('.buttons').click(function(){
var data = $(this).attr("value");
// var test = 'test';
jQuery.ajax({
url:'<?php echo $this->Html->url(array('controller'=>'maps','action'=>'instantiateButtonValue'));?>',
type: 'POST',
async: false,
data: data,
dataType: 'json'
// success:function(data){
// alert(data);
// },
// error:function(data){
// alert(data);
// }
});
});
});
my controller:
function instantiateButtonValue(){
echo $_POST['data'];
// $this->set('data','some');
// $this->render('json');
}
I think you should enclose with " quotes instead of ' quotes in URL.
From PHP you should encode as JSON instead of direct echo, to retrieve the value by JQuery.
like below
echo json_encode($_POST['data']);
i got an idea from this link here
$(document).ready(function(){
$('.buttons').click(function(){
var data = $(this).attr("value");
// var test = 'test';
jQuery.ajax({
url:"<?php echo $this->Html->url(array('controller'=>'maps','action'=>'instantiateButtonValue'));?>",
type: 'POST',
async: false,
data: {data:data},
dataType: 'json'
});
});
});

Categories

Resources