RTC222
RTC222

Reputation: 2323

php echo returns fail to jQuery

Below is jQuery code to pass form data to a php file. I'm using a very simple file just to test this. The jQuery code returns success and failure messages, but the failure message is the one that fires. It looks like the problem is in the php file, or in the data encoding.

This is the php file echo_test.php:

<?php
  $str = "Hello world!";
  echo $str;
?>

This is the jQuery code that sends html form data to the php file:

<form>
  <!-- form fields omitted for brevity -->
  <div class="btn_div">
    <button href="google.com" class="btn_joinnow" id="btn_submit"   style="color:rgb(255,255,255)">Click to submit data</button>
  </div>
</form>
$("#btn_submit").on("click", function(event) {
  event.preventDefault();
  var datastring = JSON.stringify({
    title: 'foo',
    body: 'bar',
    userId: 1
  });
  console.log("Okay, I'm starting");

  return $.ajax({
    type: "POST",
    url: "echo_test.php",
    data: { post: datastring },
    success: function (response) {
      console.log(response);
    },
    error: function (error) {
      console.log("Okay, I failed" + error);
    }
  });
});

(The data [ title: 'foo', body: 'bar', userId: 1 ] are just placeholders.)

The dev console reports: Okay, I failed[object Object] so it didn't work.

The dev console also says:

XML Parsing Error: no root element found Location: (file location) Line Number 4, Column 1:

Is the problem with jQuery or PHP?

Thanks for any ideas.

Upvotes: 2

Views: 95

Answers (2)

Saghir
Saghir

Reputation: 2445

You need an HTTP server that processes PHP code and answers with responses to HTTP requests. Your ajax request does not get the response correctly for some reason. That reason is url: "echo_test.php" which is the file probably with wring url. You will have to put the file in accessible URL (maybe your local machine) and request it. There are quick solutions like XAMPP for Windows, Linux or Mac that quickly installs HTTP server with PHP module for ready-to-use environment along with database management system as well.

Upvotes: 2

Robert
Robert

Reputation: 20286

The error means that expected response was XML but most likely it was empty. Try changing the "URL" for example to "/echo_test.php" and try opening this url via browser to see what's the content

Upvotes: 0

Related Questions