LinuxQuestions.org
Welcome to the most active Linux Forum on the web.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 06-14-2016, 05:21 PM   #1
pizzipie
Member
 
Registered: Jun 2005
Location: Hayden, ID
Distribution: Ubuntu 20.04
Posts: 441

Rep: Reputation: 12
Sending data from AJAX call to PHP - can't read data


Hi,

Trying to send php file the data which was returned by a call to AJAX.

If I print_r($_GET) (returned from the php file attached below)

array Array ( [myData] => [object Object] )

If I var_dump($_GET) This is what is returned.

array array(1) { ["myData"]=> string(0) "" }

If I echo $_GET['Name'];

Notice: Undefined index: Name in /home/rick/DB-Web/db/Update.php on line 50 is returned.

If I echo $_GET[0]['Name'];

Notice: Undefined offset: 0 in /home/rick/DB-Web/db/Update.php on line 50
is returned


The data returned by AJAX (as shown by firebug ) is as follows:

[{"Name":"George Hopper","Nickname":"Hop","DOB":"1985-05-22","POB":"Koneville, MI","Birth_Record":"A-9023"
,"Recorded_Date":"1985-05-24","Birth_Certificate":"KM-B5099","SS_No":"145-39-9912","Mother_Name":"Alice
Jones Hopper","Mother_DOB":"1960-11-27","DL":"QT90-Idaho","DL_Expiry":"2020-11-17","Passport_No":"P01865"
,"PP_Expiry":"2020-08-15","Next_Kin":"Children: Pete Hopper, Mary Hopper Thompson, Willian J. Hopper"
}]

How can I retrieve the data to work with in the php file?

Code:
$('#rev').click(function () {
 	
 	var param="update"
 	
 	doAjax(param, nName);
 	
 function doAjax(param, nName) {
	
	$.ajax({
		type: "POST",
		url: "getfields.php",
		data: {"param":param, "nName":nName},
		dataType: "json",
		success: sendTbl
	}); // ajax	
 	
 	
 function sendTbl(data) {


 window.location.href="Update.php?myData="+data[0];
 // can send data or data[0] same answer
	
} // sendTbl	

} // doAjax	

}); // #rev

Code:
<?php

set_include_path( '../include' );
error_reporting(-1);
ini_set("display_errors", true);

    
echo gettype($_GET)."\n\n";

print_r($_GET);


?>
 
Old 06-14-2016, 06:30 PM   #2
keefaz
LQ Guru
 
Registered: Mar 2004
Distribution: Slackware
Posts: 6,552

Rep: Reputation: 872Reputation: 872Reputation: 872Reputation: 872Reputation: 872Reputation: 872Reputation: 872
I didn't follow how ajax data is sent and retreived, but if received in php script as json, you have to decode it first
PHP Code:
<?php
set_include_path
'../include' );
error_reporting(-1);
ini_set("display_errors"true);

// decode in associative array
$myData json_decode($_GET['myData'], true);

print_r($myData);

// or write it in a file
file_put_contents('/path/to/writable/dir/debug.txt'print_r($myDatatrue));
?>
Edit, reading the javascript code, it is not clear what you want to achieve...
functions should be written outside the click(function) block
I don't figure out the meaning of: window.location.href="Update.php?myData="+data[0];

...ok I get it, you want to send first element (= the whole data array/object from firebug output) of data array (retreived from ajax call) as GET method to Update.php when the ajax call to getfields.php is completed

Why not send data to Update.php with ajax as POST like in the first ajax call?

Code:
function doAjax(param, nName) {
	$.ajax({
		type: "POST",
		url: "getfields.php",
		data: {"param":param, "nName":nName},
		dataType: "json",
		success: sendTbl
	}); // ajax	
 }
 
function sendTbl(mData) {
	$.ajax({
		type: "POST",
		contentType: "application/json",
		url: "Update.php",
		data: mData,
		dataType: "json"
	}); // ajax	
	
} // sendTbl	


$('#rev').click(function () {
 	var param="update"
 	doAjax(param, nName);
}); // #rev
Update.php
PHP Code:
<?php
function getData() {
    
$myData json_decode(file_get_contents('php://input'), true);
    
file_put_contents('/path/to/writable/dir/debug.txt'print_r($myDatatrue));
}

getData();
?>
}

Last edited by keefaz; 06-14-2016 at 07:17 PM.
 
Old 06-14-2016, 07:31 PM   #3
sundialsvcs
LQ Guru
 
Registered: Feb 2004
Location: SE Tennessee, USA
Distribution: Gentoo, LFS
Posts: 10,642
Blog Entries: 4

Rep: Reputation: 3933Reputation: 3933Reputation: 3933Reputation: 3933Reputation: 3933Reputation: 3933Reputation: 3933Reputation: 3933Reputation: 3933Reputation: 3933Reputation: 3933
It is definitely useful to use the browser debugger ... "FireBug" in Firefox, or what have you ... to L-O-O-K ... A-T the actual data that is being sent and received. (By that I mean, "exactly what bytes were sent from the client to the host, and then, exactly what bytes came back?")

Armed with this information, you can do things such as "writing a little JavaScript program" (or maybe, doing it in the browser's console-window ...) that takes "this character string" and does with it whatever you think is supposed to happen next.

In this way, you ought to be able to fairly-quickly figure out where the problem lies.
 
Old 06-14-2016, 08:28 PM   #4
pizzipie
Member
 
Registered: Jun 2005
Location: Hayden, ID
Distribution: Ubuntu 20.04
Posts: 441

Original Poster
Rep: Reputation: 12
The data returned by AJAX (as shown by firebug ) is as follows:

[{"Name":"George Hopper","Nickname":"Hop","DOB":"1985-05-22","POB":"Koneville, MI","Birth_Record":"A-9023"
,"Recorded_Date":"1985-05-24","Birth_Certificate":"KM-B5099","SS_No":"145-39-9912","Mother_Name":"Alice
Jones Hopper","Mother_DOB":"1960-11-27","DL":"QT90-Idaho","DL_Expiry":"2020-11-17","Passport_No":"P01865"
,"PP_Expiry":"2020-08-15","Next_Kin":"Children: Pete Hopper, Mary Hopper Thompson, Willian J. Hopper"
}]

in the AJAX success: it is referred to as 'data'


I want to send this to Update.php

How to do this?

Are you saying window.location.href="Update.php?myData="+data; won't work?

Sending it thru another AJAX call didn't work.
 
Old 06-15-2016, 05:08 AM   #5
keefaz
LQ Guru
 
Registered: Mar 2004
Distribution: Slackware
Posts: 6,552

Rep: Reputation: 872Reputation: 872Reputation: 872Reputation: 872Reputation: 872Reputation: 872Reputation: 872
It could work but I would url encode it
Code:
var encData = encodeURIComponent(data);
window.location.href = "Update.php?myData=" + encData;

Last edited by keefaz; 06-15-2016 at 05:09 AM.
 
Old 06-15-2016, 04:24 PM   #6
pizzipie
Member
 
Registered: Jun 2005
Location: Hayden, ID
Distribution: Ubuntu 20.04
Posts: 441

Original Poster
Rep: Reputation: 12
Thanks keefaz,

I tried your last response and it did work, however, I think you are right in using an AJAX call to do this.

I have a real problem in trying to get AJAX 'data' to be interpreted in my server Update.php code.

I am trying to send data to Update.php with a json string:

{"Name":"Hop", "DL":"QT90-Idaho", "DL_Expiry":"2020-11-17", "PassPort_No":"P01865", "PP_Expiry":"2020-08-15"} (this is a valid JSON string)

The response I get from PHP is:
All of the Update.php code plus the response from:

var_dump($_POST);
echo "\n\n";
print_r($_POST);
echo $_POST["Name"];

array(0) {
}


Array
(
)
<br />
<b>Notice</b>: Undefined index: Name in <b>/home/rick/DB-Web/pizzidb/Update.php</b> on line <b>50</b
><br />

Could you please show me how to access the data in array(0) or is it simply not there?

Thanks R
Attached Thumbnails
Click image for larger version

Name:	post-json-data.png
Views:	54
Size:	18.1 KB
ID:	22117   Click image for larger version

Name:	response.png
Views:	42
Size:	8.6 KB
ID:	22118  
 
Old 06-15-2016, 05:33 PM   #7
keefaz
LQ Guru
 
Registered: Mar 2004
Distribution: Slackware
Posts: 6,552

Rep: Reputation: 872Reputation: 872Reputation: 872Reputation: 872Reputation: 872Reputation: 872Reputation: 872
Usually in php you get the posted json like:
PHP Code:
$myData json_decode(file_get_contents('php://input'), true);
var_dump($myData); 
In the ajax call, you set contentType parameter to "application/json"
 
Old 06-15-2016, 05:38 PM   #8
pizzipie
Member
 
Registered: Jun 2005
Location: Hayden, ID
Distribution: Ubuntu 20.04
Posts: 441

Original Poster
Rep: Reputation: 12
I said in my last post "
Quote:
I tried your last response and it did work, however, I think you are right in using an AJAX call to do this.
I was wrong! When I run var_dump($_GET); after using window.location.href = "Update.php?myData" + str; I get as a response:

array(1) {
["myData{"Name":"Hop",_"DL":"QT90-Idaho",_"DL_Expiry":"2020-11-17",_"PassPort_No":"P01865",_"PP_Expiry"
:"2020-08-15"}"]=>
string(0) ""
}
<br />
<b>Notice</b>: Undefined index: myData in <b>/home/rick/DB-Web/pizzidb/Update.php</b> on line <b>49
</b><br />

I'm assuming array(1) refers to one array and it's named myData, so why doesn't mydata['Name'] work.

Where did ==> string(0) "" come from?

Going nuts, R
 
Old 06-15-2016, 07:48 PM   #9
keefaz
LQ Guru
 
Registered: Mar 2004
Distribution: Slackware
Posts: 6,552

Rep: Reputation: 872Reputation: 872Reputation: 872Reputation: 872Reputation: 872Reputation: 872Reputation: 872
php sees the whole json object as a key in $_GET array, string(0) is buggous value
Also, there are some added underscores after commas (,_"DL":"QT90-Idaho...) maybe replacing spaces...
I think passing json array as get variable is not the way to go

Where does "myData" come from?

If you insist to pass json with get, you can convert your json data to get variables in javascript before calling window.location, like
Code:
var getDataArr = [];
for (var key in data) { // or data[0], I don't know how data is structured
    getDataArr.push(key+'='+encodeURIComponent(data.key)); // or data[0].key
}

window.location.href="Update.php?"+getDataArr.join('&');

Last edited by keefaz; 06-15-2016 at 07:57 PM.
 
Old 06-15-2016, 09:32 PM   #10
pizzipie
Member
 
Registered: Jun 2005
Location: Hayden, ID
Distribution: Ubuntu 20.04
Posts: 441

Original Poster
Rep: Reputation: 12
I'd like to use the Ajax call as you suggested. I produced the data to pass as follows:

$.each ...... {
uData.push(" ""+field+"": ""+encodeURI(value)+""");
}

This created:

object uData "DL": "QT90-Idaho", "DL_Expiry": "2020-11-17", "PassPort_No": "P01865", "PP_Expiry": "2020-08-15"

An object named uData.

Now, how can I pass this in AJAX as a POST where 'data:' is uData' to Update.php.

If I pass it, as above, the result of var_dump($_POST); is: array(0) { }
src is shown as undefined=&undefined=&undefined=&undefined=
 
Old 06-16-2016, 12:25 PM   #11
keefaz
LQ Guru
 
Registered: Mar 2004
Distribution: Slackware
Posts: 6,552

Rep: Reputation: 872Reputation: 872Reputation: 872Reputation: 872Reputation: 872Reputation: 872Reputation: 872
POST and GET variables are passed in the form: key1=value&key2=value&key3=value

So you code becomes:
Code:
$.each ...... {
  uData.push(field+"="+encodeURIComponent(value));
}
// then convert to string by joining each uData element with a '&' character
var uDataString = uData.join('&');

// use this uDataString for data parameter value in your post ajax call

Last edited by keefaz; 06-16-2016 at 12:28 PM.
 
1 members found this post helpful.
Old 06-16-2016, 04:24 PM   #12
pizzipie
Member
 
Registered: Jun 2005
Location: Hayden, ID
Distribution: Ubuntu 20.04
Posts: 441

Original Poster
Rep: Reputation: 12
Thanks, keefaz, for your continued support. I really appreciate your staying with me on this and sorry that this is not getting resolved!!!

I'm beginning to think this is not just me being ignorant. I have done a fair amount of programming and have not had these problems before. I don't pretend to know much more than beginning intermediate, however.

I tried the call to Update.php with AJAX in two ways.

I did as you suggested in your last post with the results, case 1. and case 2.

In both cases the data posted to Update.php shows in firebug as data-as-posted.png.

I niether case does the data show up in the request.done function, showReturn.

function showReturn(data) {

alert("in showReturn "); <========== this does appear properly case 1. only

$.each(data, function (field, value) { <========== this does not appear creates TypeError: invalid in operand obj case 1.
alert(field+": "+value);
});
}

Comments appreciated.

R

case 1. Comment out - dataType:

var request = $.ajax({
type: "POST",
url: "Update.php",
data: uDataString
//dataType: "json" dataType commented out

}); // ajax

response-notype.png


case 2. Using dataType: "json"

var request = $.ajax({
type: "POST",
url: "Update.php",
data: uDataString
dataType: "json" dataType set to "json"

}); // ajax


Throws "Request failed - parsererror "

response-withtype.png
Attached Thumbnails
Click image for larger version

Name:	data-as-posted.png
Views:	47
Size:	22.0 KB
ID:	22122   Click image for larger version

Name:	response-notype.png
Views:	48
Size:	27.2 KB
ID:	22123   Click image for larger version

Name:	response-withtype.png
Views:	45
Size:	21.1 KB
ID:	22124  
 
Old 06-16-2016, 04:40 PM   #13
keefaz
LQ Guru
 
Registered: Mar 2004
Distribution: Slackware
Posts: 6,552

Rep: Reputation: 872Reputation: 872Reputation: 872Reputation: 872Reputation: 872Reputation: 872Reputation: 872
Yep it works, the data have been sent and received by Update.php, see Response tab

Now Update.php has to send data back with json type if your ajax expects json depending on dataType value, eg if you set dataType to json, the ajax callback expects a response encoded in json.

In php you just echo json at the end of script
PHP Code:
$response = Array('exit' => 'success''mykey' => 'some value...');
echo 
json_encode($response); 
BTW, I just re-read documentation for ajax:
https://api.jquery.com/jQuery.ajax/

A function to convert json array to string is superfluous as data can accept array and jquery will convert it as a query string automatically

Last edited by keefaz; 06-16-2016 at 04:49 PM.
 
Old 06-16-2016, 05:07 PM   #14
sundialsvcs
LQ Guru
 
Registered: Feb 2004
Location: SE Tennessee, USA
Distribution: Gentoo, LFS
Posts: 10,642
Blog Entries: 4

Rep: Reputation: 3933Reputation: 3933Reputation: 3933Reputation: 3933Reputation: 3933Reputation: 3933Reputation: 3933Reputation: 3933Reputation: 3933Reputation: 3933Reputation: 3933
"Once again, I repeat ..." ...

... in any such situation, start(!) by using the web-browser's debugging facilities to LQQK(!!) at the bytes(!) that the two computers-in-question are actually sending to one another.

If possible, do the same with any other, existing, interaction with this same web-server, which is known to already work, and that you are in the position to observe. ("Hey, d00d, they did it right. 'Go and do likewise!'")

If you confine yourself to looking at the situation only from the point-of-view of "one communicating party or the other," you cannot readily see "which one (or both?) of the two is screwing up!"

"You, as a human(!) outsider," can readily eavesdrop upon something that neither digital party can so-readily see. "Make the very best of it." (The hair follicles time you save will be your own.)

(And if you have not yet learned to prize "hair follicles," someday you will!)

Last edited by sundialsvcs; 06-16-2016 at 05:41 PM.
 
Old 06-16-2016, 11:09 PM   #15
pizzipie
Member
 
Registered: Jun 2005
Location: Hayden, ID
Distribution: Ubuntu 20.04
Posts: 441

Original Poster
Rep: Reputation: 12
Quote:
eg if you set dataType to json, the ajax callback expects a response encoded in json.
keefaz, is this not what I did? (AJAX call with dataType:"json",)

On server end:

foreach($_POST as $key => $value) { $rows[$key]=$value; }


Array <========= print_r($rows);

(
[DL] => QT90-Idaho
[DL_Expiry] => 2020-11-17
[PassPort_No] => P01865
[PP_Expiry] => 2020-08-15
)

echo json_encode($rows);

On Client End:

function showReturn(data) { <======== back from Update.php

alert("in showReturn "); <======= does not display

$.each(data, function (field, value) {
alert(field+": "+value);
});
} // showReturn

Request failed: parsererror
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
PHP - in-data from AJAX call will not work in SYSTEM() - using bash same data works pizzipie Programming 6 06-28-2014 12:30 AM
Can't display data returned from AJAX call pizzipie Programming 2 06-17-2014 01:37 PM
Read System Call is getting blocked when tried to read the data from CDC device sanju.lnt Linux - Embedded & Single-board computer 0 09-11-2011 11:48 PM
[SOLVED] Serial port : Read data problem, not reading complete data anujmehta Linux - Networking 5 09-06-2010 06:10 AM
PPTP server sending the weird PPTP header data in 'Out-going-call-reply' varlu Linux - Networking 0 10-14-2009 06:53 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 07:48 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration