php for loop and storing in to arrays - php

I am trying to pass some values from javascript to a php file, thru ajax request and store each result(from for loop) in to an array using php.
queryData={"data":{"data_string":{"data":"medicine","default_field":"Content"}}}
testArgument=0;
$.ajax({
url:"test/queryManipulate.php",
type: 'POST',
datatype: 'json',
data: {field : queryData, start : testArgument},
success:function(jsonQuery)
{
alert(jsonQuery);
}
});
<?php
$i=0;
for ($from = 0; $from <= 50; $from+=10)
{
$object=json_decode($_POST["field"]);
$object->from=$from;
$object=json_encode($object);
$ch = curl_init("http://localhost:9200/algotree//_search");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $object);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$test= curl_exec($ch);
curl_close ($ch);
$newArray[$i]= $test;
$i++;
echo $newArray[2];
}
?>
MY for loop doesn't work. Am I using it the right way and also how do I store each result in to an array in php?

The first loop should be
<?php
for($from = $_POST["start"]; $from<50;$from+=10)
{
// other code
}
Note the $from += 10 not $from+10.

In javascript, before converting to json string ,we have to format data using array and objects like ,
data_string = new Object();
data = new Array();
data_string[data] = "medicine";
data_string[default_field] = "Content";
data.push(data_string);
then encode the data to json , will results like
{"data":{"data_string":{"data":"medicine","default_field":"Content"}}}
then pass to php file through ajax and then decode json using
json_encode(data); in php
then do further process..

Related

PHP: Assign array to variable

i've tried a lot of things to achieve this but none of them seem to
work. Im using PHP 7.4
Let's say i have this:
$othervar = array();
$var = array(1, 2, 3);
$othervar = $var;
THIS doesn't work for me, var_dump($othervar) returns
array(1) { [0]=> string(5) "Array" }
I've tried using array_push, i DON'T WANT to use array_merge because i
need to assign two arrays to one variable. This is what i need to do:
$variable = array();
$variable["type1"] = $data; //Array 1
$variable["type2"] = $otherData; //Array 2
This doesn't work either.
Barmar showed me here that this works so i must be doing it wrong somewhere else.
I'll explan the whole code:
To login to my webpage, i send a request trough AJAX request with jQuery.
function SendData(data, btn, actionOnSuccess, shouldReplace = false, elementToReplace = "", getServerData = true, htmlData = "") {
if (!loading)
{
ToggleLoading();
data.push({name: "action", value: $(btn).data("action")});
data.push({name: "attr", value: JSON.stringify($(btn).data("attr"))});
$.post("SendRequest.php", data)
.done(function (r) {
if (!r.success)
//ajax sent and received but it has an error
else
//ajax sent and it was successfull
})
.fail(function () {
//ajax call failed
});
}
else {
//This determines if some request is already executing or not.
}
}
"action" and "attr" are encrypted values that i send to reference some actions on the system (i'll show more here):
The code goes from AJAX to SendRequest.php where it executes an action let's say, login.
The first lines of SendRequest.php are:
require "Functions.php";
$apiAction = Decrypt($_POST["action"]); //Action
$actionData = json_decode(Decrypt($_POST["attr"])); //Attr
$finalPost = $_POST;
foreach ($actionData as $key => $value) { $finalPost[$key] = $value; }
$finalPost["loggedin_ip"] = $_SERVER['REMOTE_ADDR'];
$result = APICall($apiAction, $finalPost);
Then, this is what i want to achieve to communicate with my API:
function APICall($option, $data = array())
{
session_start();
$post = array("uData" => ArrayToAPI($_SESSION), "uPost" => ArrayToAPI($data));
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_URL, "https://apiurl?" . $option); //option is the ACTION to perform on API (let's say "login") it is an encrypted word on a data-attr atribute on every form/button that creates a communication with API.
$returned = curl_exec($ch);
curl_close ($ch);
$newData = json_decode($returned, true);
return $newData;
}
function ArrayToAPI($array)
{
$toApiData = array();
foreach ($array as $key=>$value) {
if (is_array($value))
$toApiData[$key] = ArrayToAPI($value);
else
$toApiData[$key] = Encrypt($value);
}
return $toApiData;
}
This is what i have on API side:
ob_start();
var_dump($_POST);
$result = ob_get_clean();
$api->EndRequest(false, array("errorDesc" => "a - " . $result));
function EndRequest(bool $task_completed, array $data = array())
{
$jsonData = array();
$jsonData['success'] = $task_completed;
$jsonData['data'] = $data;
header('Content-type: application/json; charset=utf-8');
echo json_encode($jsonData, JSON_FORCE_OBJECT);
exit;
}
This ALWAYS returns
array(2) { ["uData"]=> string(5) "Array" ["uPost"]=> string(5) "Array" }
I hope im more clear now, thanks.
The problem is with the request being sent out from your code because of this line:
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
CURLOPT_POSTFIELDS doesn't support multi-level arrays. Your array values (which the keys are pointing to) are cast to string, which ends up as Array. Use:
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
.. instead to "properly" serialize multidimensional arrays in a post request ("properly" as there are many ways to do just that, but it matches the expected PHP format - with [] to denote arrays).

JSON: Update base64 string using url JSON

I'm new to JSON Code. I want to learn about the update function. Currently, I successfully can update data to the database. Below is the code.
<?php
require_once "../config/configPDO.php";
$photo_after = 'kk haha';
$report_id = 1;
$url = "http://172.20.0.45/TGWebService/TGWebService.asmx/ot_maintainReport?taskname=&reportStatus=&photoBefore=&photoAfter=". urlencode($photo_after) . "&reportID=$report_id";
$data = file_get_contents($url);
$json = json_decode($data);
$query = $json->otReportList;
if($query){
echo "Data Save!";
}else{
echo "Error!! Not Saved";
}
?>
the problem is, if the value of $photo_after is base64 string, which is too large string, it will give the error:
1) PHP Warning: file_get_contents.....
2) PHP Notice: Trying to get property 'otReportList' of non-object in C:
BUT
when I change the code to this,
<?php
require_once "../config/configPDO.php";
$photo_after = 'mama kk';
$report_id = 1;
$sql = "UPDATE ot_report SET photo_after ='$photo_after', time_photo_after = GETDATE(), ot_end = '20:30:00' WHERE report_id = '$report_id'";
$query = $conn->prepare($sql);
$query->execute();
if($query){
echo "Data Save!";
}else{
echo "Error!! Not Saved";
}
?>
The data will updated including when the value of $photo_after is in base 64 string.
Can I know what is the problem? Any solution to allow the base64 string update thru json link?
Thanks
// ...
// It's likely that the following line failed
$data = file_get_contents($url);
// ...
If the length of $url is more than 2048 bytes, that could cause file_get_contents($url) to fail. See What is the maximum length of a URL in different browsers?.
Consequent to such failure, you end up with a value of $json which is not an object. Ultimately, the property otReportList would not exist in $json hence the error: ...trying to get property 'otReportList' of non-object in C....
To surmount the URL length limitation, it would be best to embed the value of $photo_after in the request body. As requests made with GET method should not have a body, using POST method would be appropriate.
Below is a conceptual adjustment of your code to send the data with a POST method:
<?php
require_once "../config/configPDO.php";
# You must adapt backend behind this URL to be able to service the
# POST request
$url = "http://172.20.0.45/TGWebService/TGWebService.asmx/ot_maintainReport";
$report_id = 1;
$photo_after = 'very-long-base64-encoding-of-an-image';
$request_content = <<<CONTENT
{
"taskname": $taskname,
"report_id": $report_id,
"photoBefore": $photoBefore,
"photo_after": $photo_after,
"reportStatus": $reportStatus
}
CONTENT;
$request_content_length = strlen($request_content);
# Depending on your server configuration, you may need to set
# $request_headers as an associative array instead of a string.
$request_headers = <<<HEADERS
Content-type: application/json
Content-Length: $request_content_length
HEADERS;
$request_options = array(
'http' => array(
'method' => "POST",
'header' => $request_headers,
'content' => $request_content
)
);
$request_context = stream_context_create($request_options);
$data = file_get_contents($url, false, $request_context);
# The request may fail for whatever reason, you should handle that case.
if (!$data) {
throw new Exception('Request failed, data is invalid');
}
$json = json_decode($data);
$query = $json->otReportList;
if ($query) {
echo "Data Save!";
} else {
echo "Error!! Not Saved";
}
?>
sending a long GET URL is not a good practice. You need to use POST method with cURL. And your webservice should receive the data using post method.
Here's example sending post using PHP:
//
// A very simple PHP example that sends a HTTP POST to a remote site
//
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.example.com/tester.phtml");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"postvar1=value1&postvar2=value2&postvar3=value3");
// In real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
// http_build_query(array('postvar1' => 'value1')));
// Receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close ($ch);
// Further processing ...
if ($server_output == "OK") { ... } else { ... }
Sample code from: PHP + curl, HTTP POST sample code?
And all output from the webservice will put in the curl_exec() method and from there you can decode the replied json string.

How PHP get the content from web service?

I have a problem in getting the content/array from web service to my php code. When I type in the url in browser like http://server1-xeon.asuscomm.com/currency/?amount=1.20,from=MYR,to=SGD, then the result in the browser is displayed like this: [ 1.20MYR , 0.39SGD ]. My PHP code looks like this:
$ch = curl_init('http://server1-xeon.asuscomm.com/currency/?amount=1.20,from=MYR,to=SGD');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$content = curl_exec($ch);
curl_close($ch);
echo $content;
Unfortunately, I get nothing use the code above. Looking for help.
Thanks.
UPDATED
$data=array(
'amount'=>1.2,
'fromCurrency'=>'MYR',
'toCurrency'=>'SGD'
);
$data_string = json_encode($data);
$ch = curl_init('http://server1-xeon.asuscomm.com/currency/WebService.asmx/YaHOO_CurrencyEx');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array('Content-type: application/json'));
$content= curl_exec($ch);
curl_close($ch);
$obj = json_decode($content);
echo $obj;
This page contains dynamic content, loaded by JavaScript. You can see it in Google Chrome for example by access view-source:http://server1-xeon.asuscomm.com/currency/?amount=1.20,from=MYR,to=SGD.
If you look closer to the source code of the page (file http://server1-xeon.asuscomm.com/currency/JQuery/app_converter.js) you'll see, that it uses this code to get exchange data under the hood:
$.ajax({type: "POST",
url: "WebService.asmx/YaHOO_CurrencyEx", // important: it's a relative URL!
data: "{amount:" + amount + ",fromCurrency:'" + from + "',toCurrency:'" + to + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {},
success: function (data) {
$('#results').html(' [ ' + amount + from + ' , ' + data.d.toFixed(2) + to + ' ] ');
});
So, actually you can make such request in PHP to avoid access dynamic content on the http://server1-xeon.asuscomm.com/currency/?amount=1.20,from=MYR,to=SGD page.
UPD:
I've added a more complete explanation.
By the time the page on http://server1-xeon.asuscomm.com/currency/?amount=1.20,from=MYR,to=SGD is loaded, a JavaScript code on this page (it means that it's executed on the client side, in a browser, not on your server) parses URL parameters and makes AJAX POST request to the URL http://server1-xeon.asuscomm.com/currency/WebService.asmx/YaHOO_CurrencyEx. It passes a JSON payload {amount:1.20,fromCurrency:'MYR',toCurrency:'SGD'} and gets a response like this {"d":0.390360}. So, you can just make a direct POST request to the http://server1-xeon.asuscomm.com/currency/WebService.asmx/YaHOO_CurrencyEx via curl, passing an amount, fromCurrency and toCurrency in JSON body and then decode received JSON response using json_decode($content);.
How data should look? Add this to your code from "UPDATED" and run:
$array["MYR"] = 1.2;
$array["SGD"] = doubleval($obj->d)
// Print simple array (print source for example)
echo "<pre>";
print_r($array);
echo "</pre>";
// Print true JSON-array
print_r(json_encode($array));
In web browser you will see:
Array
(
[MYR] => 1.2
[SGD] => 0.39036
)
{"MYR":1.2,"SGD":0.39036}
Can't understand your problem at this moment.
If you want print only returned value (digits), do it: echo $obj->d;

script not showing any alert

here i am supposed to call a web service in php and the return json of the web service is stored in a variable called $response,then i am passing that json to javascript ,here i am parsing the json and depending on the type of the employee and each type have differebt attributes i am alerting all ,when i have did the same function in another page for testing it was working where i have given value to var txt='' by hardcoding , when i have integrated the php web service with the one i havew tried nothing is having ,i am confused there is no error showing with javascript console.
<?php
session_start();
$regid=$_SESSION['product_registration_id'];
//echo $regid;
$details=array(
'product_registration_id'=> "$regid");
//coverting the vlaues collected from form into json
//calling the web service
$url='webservice url';
$data=$details;
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($details));
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
$response= curl_exec($ch);
echo ("The Server Response is:" .$response);
curl_close($ch);
json_decode($response);
$json_a=json_decode($response,true);
echo $json_a[expired];
echo $json_a[account_detail][0];
?>
</div>
<script>
var txt = '<?php echo $response ?>';
alert(txt);
//var jsonData = eval ("(" + txt + ")");
var jsonData = JSON.parse(txt);
for (var i = 0; i < jsonData.employees.length; i++) {
var counter = jsonData.employees[i];
//console.log(counter.counter_name);
alert(counter.type);
if(counter.type=="0")
{
alert(counter.building_name);
alert(counter.org_name);
alert(counter.user_name);
alert(counter.name);
alert(counter.loc_name);
alert(counter.email_id);
alert(counter.password);
}
if(counter.type=="1")
{
alert(counter.user_name);
alert(counter.name);
alert(counter.password);
alert(counter.email_id);
}
if(counter.type=="2")
{
alert(counter.building_name);
alert(counter.org_name);
alert(counter.user_name);
alert(counter.opr_code);
alert(counter.name);
alert(counter.loc_name);
alert(counter.email_id);
alert(counter.password);
}
if(counter.type=="3")
{
alert(counter.building_name);
alert(counter.org_name);
alert(counter.machine_type);
alert(counter.activate_status);
alert(counter.machine_name);
alert(counter.entrance_exit_name);
alert(counter.entrance_or_exit);
alert(counter.loc_name);
alert(counter.activation_code);
}
}
</script>
if you want the php array to be an array in javascript you must:
<?php echo json_encode($response) ?>
this does not need to be parsed in javascript, it will already be an array because the echo will return something in the likings of {'message': 'hellew world'} of ['value1','value2'] which in javascript is an array or an object definition.
So remove the parsing in javascript.
If response contains a quote you will get a js syntax error. Nothing from there on will be processed. So... no alerts. Check the response. Escape the quotes.

Simulate jQuery.ajax request in PHP

I have to simulate AJAX request in PHP, exactly as is in jQuery. My current code is here:
Original AJAX call (mustn't be modified)
$.ajax({
type: "POST",
url: "/someFile.php",
data: data,
success: function(response) {
some_code_here;
},
error: function() {
some_code_here;
}
});
Current PHP code - trying to simulate JS's code behaviour above
function _misc_test() {
$data = json_decode("xxx"); // The "xxx" is placeholder for the same string, as is in data var in JS above
$ajaxResponse = _make_post_request('/someFile.php', $data);
print_r($ajaxResponse);
}
function _make_post_request($url, $data) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
And unfortunatelly, the PHP code doesn't seems to generate exactly the same packets like JS code - that's what I need. Can anyone give me a hand please?
EDIT: maybe it's important, that data variable in JS holds complex JS object like this one:
{"options":{"userIP":"89.102.122.16","playerType":"flash","playlistItems":[{"Type":"Archive","Format":"MP4_Web","Identifier":"209 452 80139\/0042","Title":"Nezn\u00e1m\u00ed hrdinov\u00e9","Region":"","SubtitlesUrl":"http:\/\/img2.ceskatelevize.cz\/ivysilani\/subtitles\/209\/209452801390042\/subtitles-1.txt","Indexes":null,"Gemius":{"Param":[{"Name":"materialIdentifier","Value":"209 452 80139\/0042"},{"Name":"testParam","Value":"testValue"}]}}],"previewImageURL":null}}
in js : data: $('form').serialize();
in php :
How to post data in PHP using file_get_contents?
$jsonstr = '{"options":{"userIP":"89.102.122.16","playerType":"flash","playlistItems":[{"Type":"Archive","Format":"MP4_Web","Identifier":"209 452 80139\/0042","Title":"Nezn\u00e1m\u00ed hrdinov\u00e9","Region":"","SubtitlesUrl":"http:\/\/img2.ceskatelevize.cz\/ivysilani\/subtitles\/209\/209452801390042\/subtitles-1.txt","Indexes":null,"Gemius":{"Param":[{"Name":"materialIdentifier","Value":"209 452 80139\/0042"},{"Name":"testParam","Value":"testValue"}]}}],"previewImageURL":null}}';
print_r(
$data = json_decode($jsonstr ,true)
);
$data_url = http_build_query ($data);
$data_url = str_replace("amp;","",$data_url); //fix for & to &
$data_len = strlen ($data_url);
$url = 'http://domain.com/returnPost.php';
$result = file_get_contents ($url, false,
stream_context_create (
array ('http'=>
array ('method'=>'POST'
, 'header'=>"Connection: close\r\nContent-Length: $data_len\r\n"
, 'content'=>$data_url
))
)
);
print_r(
$result
);
in returnPost.php
print_r($_POST);

Categories