0

I wish you can help me. I send data from php to Javascript with Json.

PHP

add_action('wp_ajax_myfilter', 'evenements_filter_function'); 
add_action('wp_ajax_nopriv_myfilter', 'evenements_filter_function');


function evenements_filter_function(){ 
....
        $arrayTest[] = array(
        'name' =>$name,
        'address' => $address,

        );


    $my_json_str_test = json_encode($arrayTest);
    $params = array(
    'data' => $my_json_str_test
    );  
     wp_send_json($params);
}

javaScript

$('#filter_evenement').submit(function(){
jQuery.ajax({
            url:ajaxurl,
            dataType: 'json',
            data :"&action=myfilter",
            type:"GET", 
            success:function(data){console.log(data);
                var dataArray = jQuery.parseJSON(data);//parse JSON

            },
            fail: function( jqXHR, textStatus, errorThrown ) {  
            }
        });
});

When I submit my form my Json value are always the same. Is it not possible to update json data ? I can only send one time ? Because I tried to add an other wp_send_json($array) just after the other and json data are not updated. How can I update json data send ?

Thanks you :)

  • to modify datas, firstly you have to send them to the PHP script in "data" of the AJAX call. Then, in the PHP script, you read $_GET to get the datas. – mmm Oct 29 '17 at 9:50
  • I want to send data from PHP to Javascript by Ajax. My data to send is the array in "evenements_filter_function ". I send my data to Javascript and it's work but when I call an over time my function datas are the same. So Can I update value json ? – steph Oct 29 '17 at 21:04
0

You don't need to specify datatype in your AJAX call. Also, WP handles AJAX a bit differently, primarily:

$('#filter_evenement').submit(function(){
 jQuery.ajax({
        url:ajaxurl,
        type:"POST", 
        data : {action: "evenements_filter_function", val1: "value1", val2: "values2"},
        success:function(data){console.log(data);
            var dataArray = jQuery.parseJSON(data);//parse JSON

        },
        fail: function( jqXHR, textStatus, errorThrown ) {  
        }
    });
 });

data has to contain action which specifies the WP AJAX handler function in the backend. You can also pass all values you need to send here (e.g val1, val2) Your evenements_filter_function() is not utilizing any data from AJAX call, it's just sending a response. But to access the values you'd check $_POST['val1'].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.