Cross origin help

've been working on a lookup using a third party API, so someone
completes a form, submits it, this then looks up the record at the third
party and returns an array.

I’ve got it working on 2 seperate pages but i’d like to roll it into
one page and remove the need for a refresh, I looked at converting the
code and using and xhr request to get the data but the thrid party have
said it wont work because they don’t support Cross Origin data/lookups.

I know tha PHP and Javascript are totally different and that PHP is
executed server side but is there a way to use OnClick on the button to
pass the form data using php get the results then pass that to
javascript?

any help or pointers would be greatly appreciated

so in short i wanted to be able to condense these 2 pages into one so
they enter the lookup details, click submit, it then runs the lookup
from page 2 and fills in the second form.

Code is as followS:
page 1:

<?php
//login and get authtoken
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://thirdpartyurl.com",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "{\r\n\"grant_type\" : \"client_credentials\",\r\n\"client_id\" : \"NEWTOCODE\",\r\n\"client_secret\": \"PASSHERE\"\r\n}\r\n",
  CURLOPT_HTTPHEADER => array(
    "accept: application/json",
    "authorization: Bearer da97e45a4690fb34fe409571a40ef325412d576b",
    "cache-control: no-cache",
    "content-type: application/json",

  ),
));

//  $response = curl_exec($curl);


curl_close($curl);


?>

<div id="content" class="full-width" style="padding-left: 100px;">
<p>For demo purposes only </p>


       <form method="post" action="page2.php"> 
  <label for="Name">Name</label>  <input type="text" name="Name" value=""> <br/>
  <label for="email">Email</label>  <input type="text" name="Email" value=""> <br/>
 <input type="submit" value="Submit">
</form> 

    </div>

Page 2:

<?php
$NAME1= $_POST["name"];
$Email= $_POST["email"];
$curl = curl_init();
// complete lookup using posted data
curl_setopt_array($curl, array(
  CURLOPT_URL => "https://thirdpartyurl.com/lookup",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "{\r\n   \"NAME\": \"$NAME1\",\r\n   \"EMAIL\":\"$EMAIL1\"\r\n}",
  CURLOPT_HTTPHEADER => array(
    "accept: application/thirdpartyurl.com.v2+json",
    "authorization: Bearer 6323arad0",
    "cache-control: no-cache",
    "content-type: application/thirdpartyurl.com.v2+json",

  ),
));

$response = curl_exec($curl);

curl_close($curl);


$userData = json_decode($response, TRUE);


?>
<form>
 <label for="Name">Name</label>  <input type="text" name="Name" value=""> <br/>
  <label for="Email">Mileage</label>  <input type="text" name="Email" value=""> <br/>
 <label for="add1">address1</label>  <input type="text" name="add1" value=""> <br/>
 <label for="add2">address2</label>  <input type="text" name="add2" value=""> <br/>
</form>

<script type="text/javascript">
// pass PHP array to JavaScript array
var userDetails = <?php echo $response ?>;



var name = userDetails['user']['personal']['name'];
var email= userDetails['user']['personal']['email'];
var add1= userDetails['add1'];
var add2 = userDetails['add2'];


//populate new form
document.getElementsByName("Name")[0].value = name;
document.getElementsByName("Email")[0].value = email;
document.getElementsByName("add1")[0].value = add1;
document.getElementsByName("add2")[0].value = add2;
</script>

Take a look at ajax

Sure there is. As Guido suggests, use Ajax. It’ll probably make sense to use jQuery, too, as that offers a lot of syntactic sugar. I wrote a tutorial on this a while ago, which should help. Read that and let us know if you have any questions.

1 Like

thanks i’ll have a look!

Thanks for the tutorial link, very useful, what do i need to put in submit.php?

Well, you would process whatever data you are receiving and return a response based on that.

Thanks i’ve tried that with the following in the submit.php file, and it just returns "i received " and not the value from the form, if i replace $value2 = $_POST[“value”]; with $value = “hello”; it prints “I received hello”

<?php $value = $_POST["value"]; echo "I received '" . $value . "'"; ?>

Got a link where we can see this in action?

sure its http://industro.co.uk/test/test.php

contents are:

<!DOCTYPE html>
      
      
        <html lang="en">
      
      
          <head>
      
      
            <meta charset="utf-8">
      
      
            <title>AJAX demo</title>
      
      
          </head>
      
      
          <body>
      
      
            <input type="text" id="myTextField" />
      
      
            <button id="ajax">Submit AJAX request</button>
      
      
        

      
      
            <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
      
      
            <script>
      
      
              $("#ajax").on("click", function(){
      
      
                var text = $("#myTextField").text();
      
      
        
      
      
                $.ajax({
      
      
                  type: "POST",
      
      
                  url: "submit.php",
      
      
                  cache: false,
      
      
                  data: { "value" : text },
      
      
                  success: function(response){
      
      
                    alert("The server says: " + response);
      
      
                  },
      
      
                  error: function(response){
      
      
                    alert ("Ajax Error");
      
      
                    console.log(response);
      
      
                  }
      
      
                });
      
      
              });
      
      
            </script>
      
      
          </body>
      
      
        </html>

and

<?php

$value = $_POST["value"];
echo "I received '" . $value . "'";

?>

This:

var text = $("#myTextField").text();

should be:

var text = $("#myTextField").val();

thanks, i tried that and still get the same problem.

think i’ve solved it i added name=“myTextField” and that seems to have sorted it.

I’m glad you got it solved, but adding a name attribute shouldn’t make the slightest difference.

That’s what i thought but it seems to have done the trick.

It now seems to be executing my php correctly so i just need to work out how to get the details it returns into a second form on the test.php page.

Would i be right in thinking that i can replace

success: function(response){
      
      
                    alert("The server says: " + response);
      
      
                  }

with

 success: function (response) {
        document.getElementById("name").innerHTML = data[0];
        document.getElementById("age").innerHTML = data[1];
        document.getElementById("location").innerHTML = data[2];}

or something along those lines?

Yup, but you’re including jQuery so you might as well use it.

Any tips?

document.getElementById("name").innerHTML = data[0];

could be

$("#name").html(data[0]);

Other than that, learn JavaScript, then learn jQuery.

Off-topic but something you may want to consider doing if and when it’s possible.

My personal preference is to use associative key values instead of numeric.
eg. instead of

document.getElementById("name").innerHTML = data[0];
document.getElementById("age").innerHTML = data[1];
document.getElementById("location").innerHTML = data[2];

this instead

document.getElementById("name").innerHTML = data['name'];
document.getElementById("age").innerHTML = data['age'];
document.getElementById("location").innerHTML = data['location'];

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.