How do I execute a PHP function using ajax? I have multiple functions on my script page but I want to call a single function.
<?php
function one(){return 1;}
function two(){return 2;}
?>
$("#form").on('submit',(function(e){
e.preventDefault();
$.ajax({
url: "process.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(response){
alert(response);
}
});
}));
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<form action="" method="POST" id="form">
<input type="text" name="text" id="text" />
<button type="submit" id="submit">Upload</button>
</form>
Use Get param "action"
$("#form").on('submit', (function(e) {
e.preventDefault();
$.ajax({
url: "process.php?action=one",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(response) {
alert(response);
}
});
}));
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<form action="" method="POST" id="form">
<input type="text" name="text" id="text" />
<button type="submit" id="submit">Upload</button>
</form>
Then in your process.php file, just catch the "action"
function one(){
return 1;
}
function two(){
return 2;
}
if ( isset($_GET['key']) && !empty(isset($_GET['key'])) ) {
$action = $_GET['key'];
switch( $action ) {
case "one":{
return 1; // or call here one();
}break;
case "two":{
return 2; // or call here two();
}break;
default: {
// do not forget to return default data, if you need it...
}
}
}
You can call a specific function of your PHP code via AJAX by following few changes in your AJAX call and PHP code.
Eg:
AJAX:
$.ajax({
url: "yourphpfile.php",
data: "function=one", // or function=two if you want the other to be called
/* other params as needed */
});
Then in yourphpfile.php code,
<?php
function one(){return 1;}
function two(){return 2;}
if(isset($_GET['function'])) {
if($_GET['function'] == 'one') {
function one() // call function one
} elseif($_GET['function'] == 'two') {
//function two() // call function two
}
}
?>
Related
I have called a jquery function in form onSubmit
if the status is false, then don't allow form submission
but currently, it is going to submitted page
here is my whole code
php form
echo "<form name='formulaire' id='my_form' method='POST' action='presale_pay.php' onSubmit='return veriftel();'>";
echo "<input type='text' name='promocode' placeholder='Enter Promo Code' id='promo'><div id='result'></div>";
echo "<p> <input type='submit' value='CONFIRM'></form>";
promocheck.php
<?php
include("include/control.php");
if (SessionValide ($session, $bd))
{
$data=array();
$promo=$_POST["promo"];
$party=$bd->ligneSuivante($bd->execRequete("SELECT * FROM promocodes WHERE promocode='$promo' AND used_nbr<=valid_nbr"));
if(!empty($party))
{
$data["status"]=true;
$data["percentage"]=$party["percentage"];
}
else {
$data["status"]=false;
}
echo json_encode($data);
}
?>
function veriftel(e)
{
$.ajax({
type: 'post',
url: 'promocheck.php',
data:{promo:$("#promo").val()},
dataType: 'json',
success: function (data) {
if(data.status==false)
{
$("#result").html("<font color=red>Invalid promocode</font>");
return false;
}
else
{
return true;
}
}
});
}
please help me to prevent form submit
should work like this
function veriftel(e)
{
e.preventDefault();
$.ajax({
type: 'post',
async: false,
url: 'promocheck.php',
data:{promo:$("#promo").val()},
dataType: 'json',
success: function (data) {
console.log(data);
if(data.status==false)
{
$("#result").html("<font color=red>Invalid promocode</font>");
console.log("false");
return false;
}
else
{
console.log("true");
return true;
}
}
});
}
also the php code should pass the event to the function
echo "<form name='formulaire' id='my_form' method='POST' action='presale_pay.php' onSubmit='return veriftel(event);'>";
The problem is that the following ajax call is asynchronous one. Your code will not wait till you get response from the server, hence the function returns before the completion of ajax call and response.
To avoid the following problem, you'll have to make your ajax call synchronous. Add aysnc:false to make it syncronous
$.ajax({
type: 'post',
async: false, //syncronous call
url: 'promocheck.php',
data:{promo:$("#promo").val()},
dataType: 'json',
success: function (data) {
}
Please note that making the call synchronous will cause the javascript execution to freeze in the webpage.
The code works on until I reach the action.php where I post my input. The issue is that the Post never reaches the action.php and all I get is a blank variable.
using: https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js
<script type="text/javascript">
function submitdata()
{
var name=document.getElementById('name');
$.ajax({
type: 'post',
url: 'action.php',
data: {
'name':name
},
cache:false,
success: function (data) {
$('#msg').html(data);
}
});
return false;
}
</script>
<form onsubmit="return submitdata();">
<input type="text" name="name">
<input type="submit" value="Check">
</form>
<p id="msg"></p>
action.php:
<?php
$name=$_POST['name'];
echo "Response: ".$name;
?>
EDIT:
Fixed it by adding:
var name=document.getElementById('name').value;
and
input type="text" id="name" instead of name="name"
Your "name" is DOM object. To get value use:
var name=document.getElementById('name').value;
You now submit not a string, but Object and this may be the reason why it fails.
Try to add the dataType on your ajax request
make it 'text'
$.ajax({
type: 'post',
url: 'action.php',
dataType: 'text',
data: {
'name':name
},
cache:false,
success: function (data) {
$('#msg').html(data);
}
});
I have an object that contains parameters . I want to upload an image to a server but just using javascript.
how can I do that?
<input id="imgItem" type="file" class="form-control">
<input type="text" id="title">
<input type="text" id="description">
<button onclick="handle();">
<script>
function handle(){
var params={
title:document.getElementById('title').value,
desc: document.getElementById('description').value,
img://i don't know what I must do,
};
postItem(params, function(data){
alert(JSON.stringify(data));
});
}
function postItem(param, callbackFunction){
$.ajax({
url:myUrl,
data:param,
type:'POST',
contentType:'application/x-www-form-urlencoded',
xhrFields:{withCredentials: false},
success: function(response){
callbackFunction(response);
}
});
}
</script>
You can use FormData
var data = new FormData();
data.append('title', document.getElementById('title').value);
data.append('desc', document.getElementById('description').value);
$("input[type='file']").each(function (index) {
try {
data.append($(this).attr('name'), $(this)[0].files[0], $(this).attr('name'));
} catch (ignore) {}
});
$.ajax({
method: 'POST',
url: url,
data: data,
cache: false,
contentType: false,
processData: false
}).done(function () {
//your code here
}).fail(function (xhr, status, error) {
//your code here
}).always(function () {
//your code here
});
Or use it as regular form submission and fill in title and description values in submit event.
I'm not sure what has gone wrong, but for some reason the success function in Ajax isn't calling the function. I'm asking it to call after the PHP is completed.
For the PHP I have $test = 'Hi'; echo json_encode($test);
Here is my code for the main page:
<?php
session_start();
if(!isset($_SESSION["b2_in"])){
header("Location: b2.php");
}
?>
<script>
$(document).ready(function(){
$("form input:submit").click(function() {
$.ajax({
type: "POST",
url: 'b2_send.php',
data: $('form').serialize(),
dataType: 'json',
//beforeSend: function(){ $("#send").val('Sending...');},
success: function(data) {
TestFunction();
},
statusCode: {
403: function(e) {
$("say").highlight();
$("#message").html(e.responseText);
}
}
});
return false;
});
});
function TestFunction(){
$("#message").val("");
}
</script>
<say>
<form>
<input type="text" name="message" class="Message" id="message"/>
<input type="submit" name="send" value='Say' id="send"/>
<span id="message" style="font-weight:bold;color:red;"></span>
</form>
</say>
Try this
span is a block element of DOM and hence to set data to it, you need to use $(id).html(data); and not val()
Also you should have different id for each elemnt in the dom, it always pick the first id that it gets in the dom, and in your case it is
<input type="text" name="message" class="Message" id="message"/> so it will change the value of this element
<script>
$(document).ready(function(){
$("form input:submit").click(function() {
$.ajax({
type: "POST",
url: 'b2_send.php',
data: $('form').serialize(),
dataType: 'json',
//beforeSend: function(){ $("#send").val('Sending...');},
success: function(data) {
TestFunction();
},
statusCode: {
403: function(e) {
$("say").highlight();
$("#message").html(e.responseText);
}
}
});
return false;
});
});
function TestFunction(){
$("#message").html("");
}
</script>
I'm writing application where I need to upload file ajax I used jQuery.form library but the action go to the controller with empty list of files I don't know why here is my code html:
<form id="well-log-form" method="post" enctype="multipart/form-data">
<div class="fileUpload btn btn-primary">
<span>Well Logs</span>
<input type="file" id="well-logs" class="upload" />
</div>
</form>
and Js Code is :
document.getElementById("well-logs").onchange = function () {
var _url = "/Importer/WellLogUpload";
var options = {
beforeSubmit: showRequest,
url: _url,
type: 'post'
};
$('#well-log-form').ajaxSubmit(options);
};
function showRequest(formData, jqForm, options) {
return true;
}
function showResponse(responseText, statusText, xhr, $form) {
// $("body").append(responseText);
}
could any one help, I think it should work but I don't know why it is not working.
try this in jquery, it will post your file.
//#file is the id of { <input type="file" id="file"> }
$("#file").change(function () {
var file_data = $(this).prop("files")[0];
var form_data = new FormData();
form_data.append("file", file_data)
$.ajax({
url: "your url",
type: "post",
data: form_data,
contentType: false,
processData: false,
success: function (path) {
//on success
}
});
});