0

I know this question has been asked a lot as I have been googling since morning but I just can't think what's going on in my code.

I have a index.php (which is my website) that uses forms to receive information from user, then invokes a javascript file separately which in turn invokes another backend php file (this backend php file queries a database using mysql and does some stuff).

The problem is I am not sure what information is getting passed to the backend php from my js. I have just learnt jQuery and Ajax so I really don't know what is that small mistake I am making.

From my understanding, the backend php does its stuff and passes the value to javascript to be displayed on the web page. But my data is not getting sent / displayed. I am getting a error 500 internal server error.

Here are the pieces of code that are currently is question:

Javascript:

var data1 = {week:week, group:grp_name};

$.ajax({
    dataType: "json",
    type: "POST",
    url : "php/remindUsers.php",
    success : function(response){
                alert ("success !");
            },
    error : function(response){
           console.log(response);
           alert("fail!");
     }

   })
});

PHP backend (remindUsers.php):

<?php

if (isset($_POST['week'])) {
   $week = $_POST['week'];
}

if (isset($_POST['group'])) {
  $group_name = $_POST['group'];
}

  echo $week;
?>

I am ommiting out the sql code pieces because they work fine.

Edit: Now my status code is 200, response text is also ok . My response text shows a weird "enter' sign next to the actual response text expected. Is this normal ? And it is still going into the error block , not the success block of code.

5
  • Something is going wrong in your remindUsers.php. You need to view the network activity in your browser's developer tools and look at the exact response, or debug your remindUsers.php file. Commented Oct 10, 2014 at 19:22
  • remindUsers.php is the PHP backend file i have mentioned. I am just trying to display the data sent from js to php.I have edited the code for clarity. Commented Oct 10, 2014 at 19:24
  • Right and the 500 server error you are getting is coming from that PHP page, not from JavaScript. You are not making a successful ajax call from that PHP page if you are getting a 500 server error. Commented Oct 10, 2014 at 19:26
  • Yes. But I cant see what is going wrong, I am just trying to display the data. is there another method to do it ? Commented Oct 10, 2014 at 19:27
  • remove the html from remindUsers.php, The concept of async call it to change the page dynamically, ask for data and get json/xml response. Commented Oct 10, 2014 at 19:56

6 Answers 6

1

I can not fully answer your question because I need more debug information about whats going on but theres 2-3 things about your code bugging me a little that might fix your bug.

First, use isset in your backend like this:

if (isset($_GET['your_input_name'])) {
    $someData = $_GET['your_input_name'];
}

The isset part is very important here. Set it up and try it again. If you stop having a 500 error. Its probably because your data was never send to your backend or because your not checking the good input name.

Second, About input name. I can see in your code that you send:

var data1 = {week:week, group:grp_name};

So in your backend you should use the name of the value like this to retrieve your data:

$week = $_POST("week");

Third, I am not a json pro but maybe your json is not valid. Even if he is ok I suggest you build a "cleaner" one like this:

var data = [
        { 'name' : 'week', 'value' : week}
    ]; 

And finally, if you are using forms to send data to php then you can use something like that :

 var myForm = $("#myForm").serializeArray();

 $.ajax({
  url: 'yourUrl',
  type: "GET",
  data: myForm,
  dataType: 'json', 
  success: function(res){
      //your success code

  },
  error: function(){
    //your error code
  }
});

I hope this helps.

Sign up to request clarification or add additional context in comments.

2 Comments

Hey. That helped a bit. Now I am getting status check OK and status 200, but it is execting the error block, not the success block of code. ANy ideas?
This question is resolved. I have posted an answer and you answer helped me a lot. Thanks :-)
1

You can't have these tags <body>,... in your PHP response over json.

It must be only:

<?php
 $week = $_POST("data");
 $json =  json_decode($week);
 echo json_encode($json);
?>

Remove the comment on

//data : {week :week}

And set a variable week with a valid value:

data : {week :week}

and so:

$.ajax({
dataType: "json",
type: "POST",
url : "php/remindUsers.php",
data : {week :week} ,
success : function(response){
            console.log(response);
        },

In order to see what is the shape of response.

Comments

0

You are doing a couple things wrong. First, you don't want to stringify your data before sending it to the server. You want to send JSON, so your commented line is the correct one. There is also a problem with the PHP. The data going to the server will look like:

{week: "Something"}

So in your PHP, you want to access the data like:

$_POST["week"];

3 Comments

I had actually earlier tried out what you said. That didn't work then and not now also. Hence i used stringify.
As @thiago said, you can't have any HTML in your PHP file if you are hitting it with AJAX
I just commented out the html tags. Didn't matter. Same problem.:-(
0

USE THIS

PHP

   $week = $_POST['data'];
    $json = json_encode($week);
    echo $json;

JS

 $.ajax({
        dataType: "json",
        type: "POST",
       url : "php/remindUsers.php"
        //data : {week :week} ,
        data:  {data:{week:'week', group:'grp_name'}} ,
        success : function(response){
            alert ("success !");
        },
        error : function(response){
            alert("fail!");
        }

    })

3 Comments

minor mistake. But that didn't help.
I checked the console. status returned is 200, status check is OK. But still i cant see anything getting displayed on the web page.
0

I would say wrap the php in a function and echo the json. Also its good to check if there was POSTed data, and if not return an error message. This is not tested, but will hopefully point you in the right direction.

 <?php

 function getJSON() {

     if (isset($_POST["data"] && !empty($_POST['data'])  ) {
         $week = $_POST["data"];
         $json =  json_decode($week);
         echo $json;
     } else {
         echo "There was a problem returning your data";
     }
 } 

 getJSON();

 ?>

Actually as I write this, I realized you could try these headers in your AJAX POST:

accepts: 'application/json',
contentType: 'application/json',
dataType: 'json'

Hope that helps.

Comments

0

It worked. I figured out the answer thanks to another SO post.

TIL : Even if server response is ok, the error condition will be triggered because the data returned to javascript from php is not json,since i had explicitly mentioned dataType: "json" in the ajax request.

Link here:

Ajax request returns 200 OK, but an error event is fired instead of success

Thanks folks for helping me and steering me in the right direction. Cheers!

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.