Having some issue with ajax and PHP - php

I am trying to get the ajax data in PHP variable. The code is working fine and I am able to get the ajax data in PHP variable.
My question is : Can I use the PHP variable for file_get_contents function again ?
My PHP code is like this
<?php
$html = file_get_contents('https://someurl.com');
if (isset($_POST['job']))
{
$job = $_POST['job'];
$attrb = $_POST['attrb'];
echo $job;
echo $attrb;
$htmlcontents = file_get_contents($attrb);
}
?>
And the Ajax code is as below
$(document).ready(function(){
$.post("test.php",
{
job: exactdatainner,
attrb: getattr
},
function(data,status){
var obj = data.split('http');
var title = obj[0];
var link = 'http' + obj[1];
$(".job").html(title);
$(".attribute").html(link);
});
});
This code works fine for the first step, sending data from ajax and receiving response and print the result in a Div.
Now I am trying to fetch the URL (this URL was created in first step and stored in a PHP variable. Code is : $attrb = $_POST['attrb'];)
As you can see that I am able to print the value in first step, but when I am trying to get the contents of URL again, it gives me the error.

Try below code, I tested and it's working. Returning a 404 response <h1>Sorry This Page is Not Available Now</h1> and I also verified the response by hitting the same url in the browser, so it's working.
file_get_contents() stops with a warning errors for non-2xx status codes.
You just need to fetch the contents even on failure status code maybe 404 or 500, for that you need to set ignore_errors => true,default is false.
echo file_get_contents(
'https://www.sarkariresult.com/force/navy-sst',
false,
stream_context_create([
'http' => [
'ignore_errors' => true
],
]) );
More information have a look on this question, second answer. here
Update
$url = 'https://html5andcss3.org/';
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n",
'ignore_errors' => true, //set to true for non 2XXX reponse codes
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents($a, false, $context);//pass the variable $url
echo $file;

Related

How can I store a returned google app script "doPost(e)" function in a variable in cURL?

I have written a doPost(e) function on google app script that will return a number depending on the data that is sent through. The script returns a number, somewhat like this:
Google App Script Code:
doPost(e)
{
/* Code that does stuff with the parameters */
var results = 3;
var result_output = JSON.stringify(results);
var output = ContentService.createTextOutput(result_output).setMimeType(ContentService.MimeType.JSON);
return output;
}
This is my cURL code which sends appropriate values and aims to store the returned output from the Google App Script code in a variable to be used later in the program:
function connect_to_GAS()
{
// Get cURL resource
$curl = curl_init();
// Set some options
curl_setopt_array($curl, array(
CURLOPT_URL => 'puturlhere',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array(
// add params here
)
));
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); // there is a redirect
// Send the request, save response to $resp
$resp = curl_exec($curl);
echo $resp;
}
When I return the $resp value it only ever returns "1" because the function was executed succesfully, but I can't get it to store the retuned value for some reason!!!
I have deployed it as a web app, and the Post function of the script does work, but my cURL side is not receiving the value as i'd like it to. Frustratingly, when I run my cURL script the value I need is displayed in the resultant web page but I have no way to access it.
Does anyone know how I can store the response????
Any help is MUCH appreciated!!
First thing is that when ever you make a changes in your script, then it need to be saved as a new version and published again to get
it effective.
You are returning a number, but not a json. Try returning a proper json.
For such cases I use guzzle.
The 1 that you are getting as result has nothing to do with variable being returned from gs file. That 1 indicates curl has gone success.
Sample Code
In gs file
function doPost(e){
//WHILE PRODUCTION
//var postData = JSON.parse(e.postData.contents);
//WHILE TESTING
//var postData = e.postData.contents;
return ContentService.createTextOutput(JSON.stringify({'status': 'success'})).
setMimeType(ContentService.MimeType.JSON);
}
function test(){
var payload = {
"key1": "value1",
"key2": "value2",
}
var e = {
postData: {
contents: payload
}
};
var returned = doPost(e);
}
In php file
<?php
session_start();
require_once '../vendor/autoload.php';
$client = new GuzzleHttp\Client(['verify'=>false]);
// Webapp link
$url = 'https://script.google.com/macros/s/yourwebapplink/exec';
$payload = json_encode(array("key1" => "value1", "key2" => "value2"))
$response = $client->request('POST', $url, ['json' => $payload]);
$body = json_decode($response->getBody());
print_r($body);
return;
?>
It is easy to install guzzle if you are using composer

How to test if a php post request with data from server (not directly from user) was successfully sent?

my task is to post data from server and not directly from a user(with its ip address). i hope you can help! :)
Code first:
<?php
add_action('init', function() {
if (isset($_POST['form_submitted'])) {
$data = ($_POST);
// send data via post request to server
$destinationUrl = getenv('VALIDATION_URL_DESTINATION'); // get URL from enviromnent variable
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($destinationUrl, false, $context);
// if status code 200
if ($http_response_header[0] == "HTTP/1.1 200 OK") {
echo "<p>Post data successfully sent.</p>";
} else {
// if status code not 200 -> wp_mail()
$to = getenv('VALIDATION_EMAIL'); // get email adress from enviromnent variable
wp_mail($to, "", strip_tags("Post data could not be sent."), "");
// redirect to form and display error message
}
}
});
?>
By submitting a form I get some date through a php request. I would like to send this data to a certain destination url and email myself if the status code is not "200" and display an error message to the last visited page (form.php).
I have certain questions:
How can i test locally if my code is correct and really sends the data trough a post request? Do I have to use a second server to test it? (I work with valet or mampp and wordpress)
How can I force the script to display a message on the last visited page?
How can a third person knowing about the structure the data was sent access to the data? For example: He/She fills out the form and submits. If the data was successfully sent it be nice if the data were in a certain format like
?first_name=lorem&last_name=ipsum&...

PHP POST request via AJAX returns source code

I am trying to send POST and retrieve data from that POST. Instead I get the source code of my AJAX script (ajax.php).
<?php
$params = array('action' => 'LOL');
$query = http_build_query($params);
$contextData = array(
'method' => 'POST',
'content' => $query
);
$context = stream_context_create(array('http' => $contextData));
$result = file_get_contents(
'ajax.php',
false,
$context
);
var_dump($result);
?>
What gives?
The typical use of ajax is to have a call from javascript (in the client browser), submit a request to the server. The server would then run some code (e.g. written in php) and return a result that the client code then uses to do something useful (or not do anything - that's possible just as well).
You seem to only have php code that's trying to call "ajax.php" ...
as to why you get the code, instead of it executing: file_get_contents read the content of a file ...
More info: http://php.net/manual/en/function.file-get-contents.php

AJAX request to PHP - Handling response data

Im working on some AJAX login function, making a request via PHP.
I am wondering how do I return data via the PHP so that I can handle it like the code mentioned below. I only worked on the javascript side and not the PHP server side so I am confused now.
I want to get a value/values stored in the response like data.name , data.sessionID , data.listOfnames
Is the data a JSON Object by itself?
Thanks!
The code below was used before and has been verified to work.
function retrieveVersion(){
var URL = RSlink + "/updates";
$.ajax({
headers : {
"Content-Type" : "application/json; charset=UTF-8",
"sessionid" : result
},
type : "GET",
url : vURL,
statusCode : {
0 : function() {
hideLoadingMsg();
showError(networkError, false);
},
200 : function(data) {
currentVersion = String(data.version);
updatesArray=data.updates;
});
}
}
});​
Suppose you have a php file for handling ajax calls. It should be available by this url - vURL.
In this file you need to create an array.
Something like this:
$data = array('data' => array('version' => yourversion, 'updates' => yourupdates));
Then you need to convert this object into json string. You can do this using json_encode() function
echo json_encode($data);
One thing to keep in mind: You need to echo your data and only. If somewhere in your file you will have some other echo-es, the result string returning to your ajax-funtion might be broken.

AJAX POST request to external domain using jQuery

I'm trying to do an AJAX POST request to an external domain from a post metabox in WordPress.
I know that it's not possible to do it directly because of cross domain access errors. As far as I know it's also not possible to do it simply by using PHP code like
if ( isset ( $_POST( 'button_name' ) ) ) { .. }
since all the metaboxes are inside the wordpress post form.
So this is what I came up with:
I use the wp_localize_script() function to make the php variables available in the js-file (this works). The localized variable is ajax_request_args.
The javascript file looks like this:
jQuery(document).ready(function($) {
$('#button').click( function() {
$.ajax({
type: "POST",
url: php_post.php,
data: ajax_request_args,
success: function(data) {
alert(data["success"] + " " + data["code"]);
},
dataType: 'json'
});
});
});
The php_post.php looks similar to this:
if (is_ajax()) {
...
if (isset($_POST["arg_1"]) && !empty($_POST["arg_1"])) {
$response = wp_remote_post( $external_url, array(
'method' => 'POST',
'body' => $args,
'headers' => array( 'Content-Type' => 'application/x-www-form-urlencoded' ),
'timeout' => 90,
'blocking' => true
) );
$return = $_POST;
$return['success_message'] = $response['success_message'];
$return['code'] = $response['code'];
$return["json"] = json_encode($return);
echo json_encode($return);
}
}
The AJAX request works without the POST request in the php file, for example when I set
$response['success_message'] = 'success';
$response['code'] = '1234';
and delete the wp_remote_post()part.
The POST request to the external domain also works when I call it directly using a button click like
<?php
if (isset( $_POST['test-maintenance-btn'])){
...
$response = wp_remote_post( $external_url, array(
'method' => 'POST',
'body' => $args,
'headers' => array( 'Content-Type' => 'application/x-www-form-urlencoded' ),
'timeout' => 90,
'blocking' => true
) );
}
?>
<form method="post">
<input type="submit" id="test-btn" name="test-btn" value="<?php _e('Execute', 'textdomain'); ?>">
</form>
The weird thing is that it doesn't work in connection. The Javascript should post to the php file which posts to the external server and returns the result to the ajax post request.
When I try to do the wp_remote_post (even if I don't use the result) I always get "NetworkError: 500 Internal Server Error" in the console.
Could you help me find the problem and help me with the correct approach? Thanks in advance for your help.

Categories