开发者

set ajax response to php variable

开发者 https://www.devze.com 2023-03-01 02:25 出处:网络
I have 2 pages javascript.js and php.php In my javascript.js page I am getting an ajax response like this

I have 2 pages javascript.js and php.php

In my javascript.js page I am getting an ajax response like this

$j(document).ready(function() { 
    $j('#button').click( function () {  开发者_开发问答            
       var data = {
        _method  :   'POST',
        'd[0][1]':    $j('#div').val(),
       };                                            
       $j.post('/path/file',  data,  function(response) {   
          var response = respone
       });
    });  
});

in my php page I want to set the variable $response to the ajax response. How would I do that


See: http://api.jquery.com/jQuery.post/

$.ajax({
  type: 'POST',
  url: url,
  data: data,
  success: success
  dataType: dataType
});

You'll need to specific a return dataType. Example:

$.ajax({
  type: 'POST',
  url: '/my_url',
  data: data,
  success: function( response_data ){
    alert( response_data.variable1 );
  },
  dataType: "json"
});

Then in php:

$my_array = array(
    'variable1' => 1,
    'variable1' => 2
);
header( 'Content-Type: application/json' );
echo json_encode($my_array);
exit();

HTH


Php is server side, and Javascript is client side... You can't set a PHP variable from ajax on the page you've already loaded. What you can do is, call another PHP page with the relevant information, and then get generated html, and show it on your current page.

That's how Ajax works.


In your /path/file:

<?php
$response = $_POST["your_post_variable"];
echo "'$response' has been set.";
?>

Cleaner JS:

$j(document).ready(function() { 
    $j("#button").click(function () {   
        var data = { _method: "POST", "d[0][1]", $j("#div").val() };                                            

        $j.post("/path/file",  data,  function(response){
            alert(response);
        });
    });
});


I guess I should mention this on the odd chance you're very new to ajax or php and it's what you meant.

If the php script you're calling via ajax has a variable $response and all you want to do is send the contents of that variable back as your ajax response - just make sure there is no other output preceding these lines (in your php script) and use

echo $response;
die;


Try echo json_encode($variable);

Also, try using jQuery's $.ajax method.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号