Swapnil Rajja
Swapnil Rajja

Reputation: 107

Having some issue with ajax and 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'];)

enter image description here

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.

Upvotes: 0

Views: 50

Answers (1)

Sujeet
Sujeet

Reputation: 3810

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;

Upvotes: 1

Related Questions