I am trying to make an ajax call from my react ponent 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 ponent.
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.
I am trying to make an ajax call from my react ponent 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 ponent.
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.
Share Improve this question asked Nov 1, 2016 at 13:10 BrianBrian 1111 gold badge4 silver badges13 bronze badges3 Answers
Reset to default 3In 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)
});
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.
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);
?>