Converting form variables to Json object

I am using the following way to convert form fields to JSON object .

I am trying to send it using Ajax call but having CORS related issue. Calling a simple webservice using PHP Curl works fine.

Is there a way I could convert form variables into JSON object using PHP and then pass it along to a web service?

http://php.net/manual/en/function.json-encode.php

http://php.net/manual/en/book.curl.php

Thanks. Before doing that, I was planning to convert the form variables into arrays. and before I convert form variables into arrays, I was thinking of printing some of my variables when a user clicks on submit button. So I made some changes to accomplish it like this :

 <form  id = "myform" action="" method="post">
    First name: <input type="text" name="FirstName" value="Mickey"><br>
    Last name: <input type="text" name="LastName" value="Mouse"><br>
   <button name = "submittest" type = "submit test">Submit Test </button>
 </form>

And I did the following :

<?php 
	
	     if (isset($_POST['submittest'])) {
			$example = $_POST['FirstName'];
			$example2 = $_POST['LastName'];
			echo $example . " " . $example2;
		}
	
	
	?>

But it still refreshes the page which I don’t want. Is it possible to display the form values instantly as soon as the submit button is clicked?

Thanks

Not using PHP, because by nature that runs on the server, so it will either give a page refresh, or you need to call it via Ajax.

I see. I am actually having CORS issue when using Ajax and hance trying to get things done using PHP but it looks like I will have to find some other alternative.

I believe that for testing purposes there are browser add-ons that will help with CORS, but it doesn’t help for actual production. I’m having a similar issue at the moment, as it happens.

Yes, there are plugins I have used before. Won’t be helpful with production :slight_smile:

What you are doing is called a “php proxy”. If you search on google for that term there are a few available that you can probably use for entire your project with having to write your own or replicate the same code over and over. Seems like you are heading down a path with a lot of potential for errors and duplicate logic which can be avoided using a package already availe on GitHub or composer.

This looks like what you need.

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