简体   繁体   中英

Call a php function via Ajax Request

Im trying to code my homepage more structured. I have to work a lot with mysql db queries and I want to create for every table a own .php file with all necessary functions which I want to call via Ajax Request.

Therefore I got the following snippet by a stackoverflow answer:

$.ajax({ url: '/my/site',
         data: {action: 'test'},
         type: 'post',
         success: function(output) {
                      alert(output);
                  }
});

On the server side, the action POST parameter should be read and the corresponding value should point to the method to invoke, eg:

if(isset($_POST['action']) && !empty($_POST['action'])) {
    $action = $_POST['action'];
    switch($action) {
        case 'test' : test();break;
        case 'blah' : blah();break;
        // ...etc...
    }
}

My problem:

I want to assign form data as well via the data attribute and I don't know how I can do this. I tried the following (this was just a guess which didnt work):

var data = $(this).serialize();
$.ajax({ url: '/my/site',
         data: {action: 'test', data},
         type: 'post',
         success: function(output) {
                      alert(output);
                  }
});

serialize() will return the data from the form as a string . You can just append the rest of the string with your remaining queries.

Example:

<form id="form">
    <input name="form_name_1" value="form_value_1">
    <input name="form_name_2" value="form_value_2">
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
    var data = $('#form').serialize();
    data += '&action=test';

    $.ajax({
        url: '/my/site',
        data:data,
        type:'post',
        success:function(output) {
            alert(output);
        }
    });
});
</script>

You need to specify the data as a parameter

var data = $(this).serialize();
$.ajax({ url: '/my/site',
         data: {action: 'test', data: data},
         type: 'post',
         success: function(output) {
                      alert(output);
                  }
});

The data parameter of the ajax call expects an object, as defined the in ECMA/Javascript spec - eg a series of key/value pairs

The you can access it via $_POST['data']

Personally, I tend to json serialise it to avoid http quirks around arrays...

data: {action: 'test', data: JSON.stringify(data)}

then in PHP:

$data = json_decode(isset($_POST['data']) ? $_POST['data'] : "{}");

If data was posted, it will now be present in $data as a complex object, otherwise $data will contain an empty object

You can post your data as JSON object

$.ajax({
    type: "POST",
    url: "/some/url",
    data: JSON.stringify(jsobject),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(output){
      alert(output);
    }
});

and in the php script you just do json_decode to get the object or associative array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM