首页 > 解决方案 > Conditionally create URLwith php and pass to jquery.ajax

问题描述

I have a page with an ajax form and want to control which form the user is served based on an url argument. I can read the url arg and decide which form the user needs but cannot figure out how to pass the url from php to javascript.

for example the user visits page based on example.com/index.php?utm_source=test

Then I check for the code and define the form the user should use

$utm_source = $_GET['utm_source'];

if ($utm_source = 'test'){
  $formList='list[4]';
  $formUrl= 'https://www.example.com/?p=asubscribe&id=4' ;
  }
else {
  $formList="list[2]";
  $formUrl="https://www.example.com/?p=asubscribe&id=2";

Still in the header I add the url to ajax using json_encode

function submitForm() {
  successMessage =
    "success.";
  data = jQuery("#subscribeform").serialize();
  jQuery.ajax({
    type: "POST",
    data: data,
    url: <?php echo json_encode("$formUrl") ?>;,
    dataType: "html",
    success: function (data, status, request) {
      jQuery("#result")
        .empty()
        .append(data != "" ? data : successMessage);
      jQuery("#email").val("");
    },
    error: function (request, status, error) {
      alert("error.");
    },
  });
}

However the url that is generated is https:\/\/www.example.com\/?p=asubscribe&id=4

I also try the http_build_query($data) but it doesn't include the https://domain, the form needs full url.

How can I fix the \/\/ issues so it's a valid URL?

标签: phpjqueryajax

解决方案


推荐阅读