简体   繁体   中英

call a php function with a click of a button

how do you call a php function with ajax or javascript or jquery?

this is my php script

function submitmessage() {
    $sent = date(y-m-d-h-m-s);
    $message = $_POST['message'];
    $query = "INSERT INTO chatbox (from,to,message,sent)                            
    VALUES('$fullname','$to','$message','$sent')";
    mysql_query($query) or die(mysql_error());
}

Have the file that the AJAX call connects to be available on the server.

So lets say your function is in the file: functions.inc.php

You could have a php file that includes the functions.inc.php and calls the submitmessage function.

ajax_responder.php:

require_once 'functions.inc.php';    

if(!empty($_POST)) {
    submitmessage();
}

Now you can use the URL to the ajax_responder.php to submit messages.

With jQuery included or written into the page with form:

function submitmessage(){
    $.post("url_path/ajax_responder.php", { fullname: document.chatbox.fullname.value, message: document.chatbox.message.value } );
}

Then, instead of submitting a form, you change your submit button into a button that calls the submitmessage javascript:

<button onclick="submitmessage()">Submit Message</button>

As a side note, for security, I recommend that you do something more with the POST data to ensure that you do not get SQL injection . Since you are already using mysql functions you could try mysql_real_escape_string .

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