Simulate jQuery.ajax request in PHP - 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);

Related

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;

post json to a codeigniter method in controller, formerly post was made in jquery

I need to post a json to a method in codeigniter 2.2.0, that post was made in a view with a jquery-ajax, like this:
function envia_mail_ajax(numero, form_data, ruta){
var iddiv="#mail_"+numero;
window.setTimeout(
function(){
$.ajax({
url: "<?php site_url('emailmasivo'); ?>/" +ruta+ "/" +numero,
cache: false,
type: 'POST',
data: form_data,
dataType: "json",
success: function(html){
$( iddiv ).append(html.mensaje+"\n"+'<br />');
}
});
}, 600);
}
and it was used like this (within a loop over i):
envia_mail_ajax(i,
{para:correos_e[i],id_masivos:id_masivos_e[i],id_mat_referencia:id_mat_referencia_e[i],
id_tipouser:id_tipouser_e[i],nombre:nombres_e[i], sexo:sexos_e[i], matricula:matriculas_e[i], passa:passa_e[i],id_cuenta:cuenta_id},
"<?php echo $r_ajax; ?>");
now, I´m writing all that in such a way that no view will be needed, in order to make it possible to run it from the terminal´s commands line, essentially, this is telling me to POST to the controller´s method "<?php echo site_url('emailmasivo'); ?>/" +ruta+ "/" +numero the data in form_data; to do this I wrote a method based in a lecture I found here POST json to PHP, my method is:
function procesaInfo($Arreglo, $numero){
$url = $Arreglo['r_ajax'];
$ch = curl_init(echo site_url('emailmasivo') . $url . "/" . $numero);
$jsonData = array(
'para' => $Arreglo['lista_mails']['correos_e'][$numero],
'id_masivos' => $Arreglo['lista_mails']['id_masivos_e'][$numero],
'id_mat_referencia' => $Arreglo['lista_mails']['id_mat_referencia_e'][$numero],
'id_tipouser' => $Arreglo['lista_mails']['id_tipouser_e'][$numero],
'nombre' => $Arreglo['lista_mails']['nombres_e'][$numero],
'sexo' => $Arreglo['lista_mails']['sexos_e'][$numero],
'matricula' => $Arreglo['lista_mails']['matriculas_e'][$numero],
'matriculas_e' => $Arreglo['lista_mails']['passa_e'][$numero],
//'id_cuenta' => $Arreglo['lista_mails']['cuenta_id'][$numero]
'id_cuenta' => $Arreglo['id_cuenta']
);
$jsonDataEncoded = json_encode($jsonData);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
}
the problem is that when I try to use that method like this:
function proceso_envia($nuevoArreglo){
$hola = "hola";
//echo $cuenta_id = $nuevoArreglo['id_cuenta'].PHP_EOL;
//print_r($nuevoArreglo['lista_mails']['correos_e']);
if(count($nuevoArreglo['lista_mails']['correos_e']) != 0){
$j = 0;
for($i = $nuevoArreglo['ini'] ; $i < count($nuevoArreglo['lista_mails']['correos_e']) ; $i++){
if($nuevoArreglo['lista_mails']['correos_e'][$i] != NULL){
$j = $j+1;
sleep(1);
echo "si llega!".PHP_EOL;
$this->procesaInfo($nuevoArreglo, $i);
}
}
}
}
it seems that no data are being POST to my method, and worst, not even the method is being reached, how do I know? well, I used an echo "I´m here!"; at the very beginning of the proceso_envia function, and nothing was displayed... am I doing it right? how do I post correctly data to a CI method in a controller? thanx i.a. for your help!

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.

php for loop and storing in to arrays

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..

Using jQuery to parse XML returned from PHP script (imgur.com API)

Here's my jQuery:
var docname = $('#doc').val();
function parseXml(xml)
{
$(xml).find("rsp").each(function()
{
alert("success");
});
}
$('#submit').click(function() {
$.ajax({
type: "GET",
url: "img_upload.php",
data: "doc=" + docname,
dataType: "xml",
success: parseXml
});
return false;
});
Note that #doc is the id of a form text input box and #submit is the submit button's id. If successful, I'd like a simple "success" javascript popup to appear.
Here's img_upload.php with my API key omitted:
<?php
$filename = $_GET["doc"];
$handle = fopen($filename, "r");
$data = fread($handle, filesize($filename));
// $data is file data
$pvars = array('image' => base64_encode($data), 'key' => <MY API KEY>);
$timeout = 30;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://imgur.com/api/upload.xml');
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars);
$xml = curl_exec($curl);
curl_close ($curl);
?>
When directly accessed with a GET argument for "doc", img_upload.php file returns the following XML format:
<?xml version="1.0" encoding="utf-8"?>
<rsp stat="ok">
<image_hash>cxmHM</image_hash>
<delete_hash>NNy6VNpiAA</delete_hash>
<original_image>http://imgur.com/cxmHM.png</original_image>
<large_thumbnail>http://imgur.com/cxmHMl.png</large_thumbnail>
<small_thumbnail>http://imgur.com/cxmHMs.png</small_thumbnail>
<imgur_page>http://imgur.com/cxmHM</imgur_page>
<delete_page>http://imgur.com/delete/NNy6VNpiAA</delete_page>
</rsp>
What's the problem here?
Here's the Imgur API page for reference.
var docname = $('#doc').val();
Exactly where is this in your code and when will it be evaluated?
My guess is that it's executed either when the <script> tag has been parsed or you've wrapped it in a $(document).ready() handler. Either way it get's evaluated before the user has actually typed something into the input/text control and docname will therefore be '' or even null all the time. You want the script to fetch the value not until the user has pressed the submit button.
Try it with
$('#submit').click(function() {
$.ajax({
type: "GET",
url: "img_upload.php",
data: "doc=" + $('#doc').val(),
dataType: "xml",
success: parseXml
});
return false;
});
edit: Even better, make the data property an object and let jquery handle the escaping of the value.
data: {doc: $('#doc').val()}
It could be that you have not set the header in the php script - this should be your first line.
header('Content-Type: text/xml');

Categories