1

I am trying to make an ajax call from my react component to a php file in which I am expecting the php file to return a specific output but instead I get an entire source code. Can someone help?

This is what I have on my react component.

import React from 'react';
import {Link} from 'react-router';


export default class BikePage extends React.Component {
    onFormSubmitSuccess(e) {
      e.preventDefault();
    $.ajax({
      url: 'php/new_user.php',
      type: "GET",
      success: function(data) {
        console.log('success')
        console.log(data);
      }.bind(this),
      error: function(xhr, status, err) {
        console.log('error')
      }.bind(this)
    });
  }

  render(){
    return (
      <button onClick={this.onFormSubmitSuccess.bind(this)} >click here</button>
    )
  }
}

This is whats on my php file.

<?php
//Function to check if the request is an AJAX request
$return = 'hello'
echo json_encode($return);
?>

All I am trying to test is to get the "Hello" on my console. but instead I get the entire php file.

3 Answers 3

3

In your case, you are using json_encode() in PHP for getting response, and not using DataType:json, you just need to use DataType as json like:

dataType: "json",

Your json output should be looks like: "message"

Modified Ajax:

$.ajax({
url: 'php/new_user.php',
type: "GET",
dataType: "json",
success: function(data) {
    console.log('success');
    console.log(data); // will print "message"
}.bind(this),
error: function(xhr, status, err) {
    console.log('error');
}.bind(this)
});
Sign up to request clarification or add additional context in comments.

5 Comments

I simply added datatype json and now i get an error. I console log the status, err and xhr and it does not responde with anything. The xhr response with an object and its a status 200 with a response text <?PHP↵$data = 'hello'↵header('Content-Type: application/json');↵echo json_encode($data);↵?> . The status is Syntax error unexpected tocken < in JSON and the err message is parseerror
@BrianBier: why are u using header('Content-Type: application/json');?
I was just testing to see if that was the problem. but its not.
@BrianBier: chk browser console
Those error messages are coming from the browser console. Is there a way around it.
2

First of all 'hello' is not json encodable you need to use for example array('result' => 'hello').

If you gets php file's content it seems that you don't use working local server.

Comments

1

You need to set header in your PHP to send JSON results

Try this

<?PHP
$data = 'hello'
header('Content-Type: application/json');
echo json_encode($data);
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.