Ime Ime
Ime Ime

Reputation: 131

Ajax to php and then php to Ajax

I have index.php with html form, user enters data, submits form (with ajax/jquery), server calls REST service with form params, parses response and sends result (array as json) to javascript on that same index.php. The part that is not working in my code is sending response back to javascript. It sends hardcoded array json for testing purpose but fails with dinamic response from REST. REST itself is ok and return correct data with var_dump().

index.php

<?php

//index.php

...

//submiting form

<script language ="javascript" type = "text/javascript" >

    function submitForm()
    {
       $("#gl_forma").submit();
    }

</script>

...

if(!empty($params['arg1']) )
{
    $result = call_rest_service($connection, $params);//its ok

    //send POST to ajax.php that is just for echoing to javascript
    $response = sendPost('http://127.0.0.1/mysite/ajax.php', $result);
}
//function to send POST
function sendPost($url, $data)
{   
    $options = array(
        'http' => array(
        'method'  => 'POST',
        'content' => json_encode($data),// here encodes it
        'header'=>  "Content-Type: application/json\r\n" .
        "Accept: application/json\r\n"
        )
    );

    $context  = stream_context_create( $options );
    $result = file_get_contents( $url, false, $context );
    return $response = json_decode($result);        
}

...

<script language ="javascript" type = "text/javascript" >
//get back data from php to js

//#search_button the same button that submited form

$(document).ready( function() {
    $('#search_button').click(function() {
          $.ajax({
          type: 'POST',
          url: 'ajax.php',
          data: 'id=testdata',
          dataType: 'json',
          cache: false,
          success: function(result) {
            alert(JSON.stringify(result));//alerts the hardcoded array for testing, but wont real results
          },
          });
    });
});
 </script>

ajax.php - just for echoing results to javascript

<?php

    //ajax.php

    $data = file_get_contents('php://input');//catch POST
    $_REQUEST = array();    
    file_put_contents('file.txt', $data, FILE_APPEND );//it writes, just for debuging...
    echo $data;//its encoded already

Upvotes: -1

Views: 174

Answers (1)

user3141603
user3141603

Reputation:

try:

$(document).ready( function() {
    $('#search_button').click(function() {
          $.ajax({
          type: 'POST',
          url: 'ajax.php',
          data: 'id=testdata',
          dataType: 'json',
          cache: false
          }).done(function( result ) {
               alert(JSON.stringify(result));//alerts the hardcoded array for testing, but wont real results
          });
    });
});

Upvotes: 1

Related Questions