Atomic Rooster Atomic Rooster - 18 days ago 5
Ajax Question

React JS - Trigger PHP after onClick event

I was trying to call PHP script through AJAX call from the react js script or when a submit button is clicked in the react component. I did this using normal HTML and JQuery but find it difficult to implement the same using react.

One of the user explained the normal flow of input and display it as alert. But i want that input values to be sent to the PHP script. The JQuery code for that is :

$('#button').click(function () {
alert("first")
$.ajax({

type: "GET",
crossDomain: true,
url: "http://localhost:8085/Folder1/login.php",
data: {

stime: $("#demo1").val(),
etime: $("#demo2").val(),
desc: $("#servername").val()
},

success: function(data){
alert(data)
$('#resultip').html(data);
},
error:function(data)
{
alert("Data sending failed");
}
});


I am new to react and unable to get any document which explains this to do in react. Any help is highly appreciated.

https://jsfiddle.net/69z2wepo/34020/

Answer

You can make a GET request to your PHP script on submit event in React JS, you can put your AJAX call inside handleSubmit()

Also since you are making a GET request you don't have to make it JSON you can send the params directly to your external script, the params will be appended to the url like this GET /test_url.php?first_name=John&last_name=Doe You can then access these params in your PHP code using $_GET['first_name']

handleSubmit(event) {
    event.preventDefault();
    var data = this.state;
   $.ajax({

        type: "GET",
        crossDomain: true,
        url: "http://localhost:8085/Folder1/login.php",
        data: {

            stime: $("#demo1").val(),
            etime: $("#demo2").val(),
            desc: $("#servername").val()
        },

        success: function(data){
            alert(data)
            $('#resultip').html(data);
        },
        error:function(data)
        {
            alert("Data sending failed");
        }
    });
  },

You can check the console to see the GET request to your script,

Here is the updated fiddle: https://jsfiddle.net/9qewutqk/2/

Comments