Reputation: 67
I was wondering if there is anyway to make this:
<form action="http[://localhost/.../script.php" method="POST">
a regular call. I don't want it to run on form submit, but instead I wan't it to run when I call a function.
Would I use jQuery or AJAX?
Upvotes: 0
Views: 3318
Reputation: 7843
You may use Fetch API on chrome to do so:
// building your form values
var data = new URLSearchParams();
data.set('var1', 'value 1');
data.set('var2', 'value 2');
// send to the endpoint
fetch("http://localhost/.../script.php", {
method: 'POST',
mode: 'no-cors',
cache: 'no-cache',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: data
}).then(function(response) {
// check the response object for result
// ...
});
Upvotes: 5
Reputation: 520
You could use AJAX to post data to your PHP script, which will then run.
Note that jQuery and AJAX are not alternatives for each other.
AJAX is an asynchronous HTTP request (which is what you want).
jQuery is a javascript library which you can use to make AJAX calls.
I would take a look at https://api.jquery.com/jQuery.post/
This is a shorthand function for making an ajax POST request. E.g.:
function triggerMyPhpScript(data) {
$.post("http://localhost/.../script.php", data, function(responseData) {
// do something with the response of your script
});
}
I also like the Fetch answer from Koala Yeung. This will also work fine on modern browsers. Keep in mind that if you want to support ancient browsers (e.g. internet explorer), you need to implement feature detection and a fallback in case fetch is not supported by the browser.
Upvotes: 0
Reputation: 565
You can use ajax to call the the php function and store its response.
$.ajax({url: "demo_test.txt", success: function(result){
$("#div1").html(result);
}});
Make sure u include jquery CDN
Upvotes: 0