I have one AJAX call. I need to pass some parameters to my function. This is my AJAX call.
$.ajax({
url: 'lib/function.php',
data: {
action: 'getStoreSupplyItems',
id: store_id,
indent: 1
},
success: function(output) {
//alert(output);
$('#response').html(output);
}
});
Here is my back end function definition that I am trying to call:
function getStoreSupplyItems($category = '')
{
global $db;
$data = $_REQUEST;
$category = (!empty($category) ? ' AND cim.item_group_code IN ("'.$category.'") ' : '');
if ($data['id'] != "")
{
$store = $data['id'];
}
else
{
$store = $_SESSION['user']['store']['id'];
}
How can I pass some arguments to the function? The parameter that I want to pass is something like '12,5,6'.
You can put a switch statement in your php file and then call the function passing the arguments. Like this
switch($_REQUEST["action"]){
case "getStoreSupplyItems" :
getStoreSupplyItems("2,12,5");
break;
}
In your getStoreSupplyItems function you can get the value as a param and also use other get params by $_REQUEST or $_GET.
I hope this is what you looking for.
To pass your data you have to make a call like this:
$.ajax({
method: "POST",
url: "lib/function.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
then, in your PHP function you have to access to params via $_POST['name'] and $_POST['location']
Related
I am trying to return the parameter of a laravel route to an ajax response. This is my
public function getPermissions(Request $request)
{
//$v = request()->route()->parameters('profile');
$v = request()->route()->parameters();
return var_dump($v);
}
JS:
function getPermissions() {
let data_permissions = '';
$.post({
url: '/permisos',
async: false,
success: (res) => {
console.log(res)
}
});
}
This is my route:
http://base-laravel.test/profiles/1/edit
In the console returns an empty array.
I intend to obtain the 1 that they see on the route. Suggestions?
You have not added the data to send from Laravel to Ajax Controller. You can pass the data inside the object of the data like
$.post({
url: '/permisos',
type: "POST",
data: {
id: '{{$user->id}}' // Suppose you need to pass the user id to the controller
},
async: false,
success: (res) => {
console.log(res)
}
});
When retrieving the id in the AjaxController, you can simply use the Request $request variable.
public function getPermissions(Request $request)
{
//dd($request->all())
//dd can be use to die and dump the all variable values
return $request->id;
}
Viewing in the console, it will display the Ajax Request Id.
You can use this way
$data = $this->route('parameter_to_access');
return $data
I try to do an ajax request with wordpress. So I've created a simple js request:
$.ajax({
url: '?',
type: 'POST',
data: {
'pr_post': post,
'pr_rating': rating
},
success: function (response) {
console.log(response);
}
});
Here is my function to handle the request.
function pr_request()
{
if (isset($_REQUEST['pr_post']) && isset($_REQUEST['pr_rating']) && isset($_REQUEST['pr_user'])) {
$post = $_REQUEST['pr_post'];
$rating = ($_REQUEST['pr_rating'] > 5 ? 5 : $_REQUEST['pr_rating']);
$user = get_current_user_id();
if (!pr_has_user_already_voted($user, $post)) {
global $wpdb;
$table = $wpdb->prefix . 'mitmach_ratings';
$wpdb->query($wpdb->prepare("insert into $table values (null, $post, $rating, '$user');"));
wp_send_json(['message' => 'success']);
} else {
wp_send_json(['message' => 'duplicate'], 403);
}
}
}
As you see I call the get_current_user_id() function. This function always returns true even if the user logged in. How can I get the user id in my handler without sending it via ajax?
For a start check docs - WP Ajax.
You need to send action key
Notice how the 'action' key's value 'my_action', defined in our JavaScript above, matches the latter half of the action 'wp_ajax_my_action' in our AJAX handler below. This is because it is used to call the server side PHP function through admin-ajax.php. If an action is not specified, admin-ajax.php will exit, and return 0 in the process.
$.ajax({
url: '?',
type: 'POST',
data: {
action : 'pr_post',
pr_rating : rating
},
success: function (response) {
console.log(response);
}
});
and call like this:
add_action( 'wp_ajax_pr_request', 'pr_request' );
add_action( 'wp_ajax_nopriv_pr_request', 'pr_request' );
function pr_request() {
// Code
}
I have written a php script
cch.php
$stmtcheck = $mysqli->prepare("SELECT id FROM members WHERE email=? AND unlock_code=?");
$stmtcheck->bind_param("si", $_SESSION['unlockemail'], $_POST['code']);
$stmtcheck->execute();
$stmtcheck->bind_result($id);
$stmtcheck->fetch();
$stmtcheck->close();
And jquery for submitting form is
recover.php
$("#formUnlock").submit(function(e)
{
e.preventDefault();
$.ajax(
{
url: '../scripts/cch.php',
method: 'POST',
data: $(#formUnlock).serialize(),
success: function()
{
alert("unlocked");
}
});
});
Now what I want to check whether $id has some value or not! How would I fetch the $id variable to my main script?
In cch.php, if you want to pass only an id to the javascript, you can print id
echo $id;
What ever data is received on ajax response will be passed as parameter to the success callback function. Either you have to execute the success actions inside the succes call back OR You have to write a function to be executed on ajax success and call that function and pass the params
$("#formUnlock").submit(function(e)
{
e.preventDefault();
$.ajax(
{
url: '../scripts/cch.php',
method: 'POST',
data: $(#formUnlock).serialize(),
success: function(responseData)
{
if (responseData == '' )
{
alert("Sorry failed");
}
else
{
alert("Success");
}
}
});
});
Is there a way to make a function that converts default ajax function.
This is the ajax function i have
$.ajax({
type: "POST",
url: "http://" + document.location.host + '/userajax',
data: 'type=register&name=' + name,
beforeSend:function() {
},
success: function(response) {
}
});
This is what i want it to look like
ajax('url', {
method: 'get',
parameters: {
name: $('#name').val()
},
beforeSend: function() {
},
success: function(transport) {
}
});
Ive tried to search on the internet but did not find anything
Sure, you can create the function like this:
function ajax(url, params){
// everything is now available here
console.log( url ); // output: http://www.google.com
// you can get the data of the params object like this
console.log( params.method ); // output: get
// you can execute the beforeSend like this:
params.beforeSend();
// additionally you might want to check everything.
// maybe if the method is NOT set, you want it to always use GET
switch(arguments.length) {
case 1: url = throw new Error('Url should be set');
case 2: params.method = 'get';
case 3: break;
default: throw new Error('illegal argument count')
}
}
You would call this like:
ajax('http://www.google.com', {
method: 'get',
parameters: {
name: $('#name').val()
},
beforeSend: function() {
// some function
},
success: function(transport) {
// some function
}
});
This certainly is possible, it's just a bit of work. Some of the basics you need:
First of all, you need a good understanding of the XMLHTTPRequest API, you can find more info on that on MDN.
Next, finding out how to do a callback, that is actually quite simple, you can pass an anonymous function reference as an option or attribute for a function. That goes like this:
function doSomething(variable, callback){
variable = variable + ' something'; // just doing something with the variable
callback(variable);
}
// then call the function with a callback (anonymous function)
doSomething('doing', function(result){ alert(result); });
You should get an alert that says 'doing something'.
And finally you should know how to read an object, passed as 'options' in the ajax function. Say you have a function like this:
function foo(url, options){
console.log(url);
console.log(options.method);
console.log(options.parameters.name);
}
// call it like this
foo('https://google.com/', {
method: 'get',
parameters: {
name: 'myName'
}
});
That should log the url, method and parameters in the console.
Now from here, you should have all the pieces to put the puzzle together. Good luck!
I don't think so. but you can do this:
$(document).ready(function(){
var parameters = {
name: $("#name").val(),
desc: $("#desc").val()
};
$.ajax({
url: 'path/to/file',
data : parameters,
beforeSend: beforeSubmit,
dataType: "json",
type : 'POST',
})
.done(function(data) {
})
.fail(function() {
console.log("error");
})
})
Also note I don't set the function for the beforeSend directly in the call, I will create an externe function which gives me more freedom.
so I could do this:
function beforeSubmit(){
if(something !== 'somethingelse'){
return false; //ajax call will stop
}else{
return true; //ajax call
}
}
I created array like this ["9", "ques_5", "19", "ques_4"]. Now I want to send it from JS to PHP but I'm not getting proper results. My JS code is:
$(".button").click(function(e) {
e.preventDefault();
$.ajax({
type : 'post',
cache : false,
url : 'test/result.php',
data : {result : stuff},
success: function(resp) {
alert(resp);
}
});
});
In the above code stuff is an array which contains records. How can I send this array with above code and then in PHP I want to process this array like ques_5 is the key and 9 become the value for that key.
You can pass the data to the PHP script as a JSON object. Assume your JSON object is like:
var stuff ={'key1':'value1','key2':'value2'};
You can pass this object to the php code in two ways:
1. Pass the object as a string:
AJAX call:
$.ajax({
type : 'POST',
url : 'result.php',
data : {result:JSON.stringify(stuff)},
success : function(response) {
alert(response);
}
});
You can handle the data passed to the result.php as :
$data = $_POST["result"];
$data = json_decode("$data", true);
//just echo an item in the array
echo "key1 : ".$data["key1"];
2. Pass the object directly:
AJAX call:
$.ajax({
type : 'POST',
url : 'result.php',
data : stuff,
success : function(response) {
alert(response);
}
});
Handle the data directly in result.php from $_POST array as :
//just echo an item in the array
echo "key1 : ".$_POST["key1"];
Here I suggest the second method. But you should try both :-)
If you want to send key value pairs, which is what I am seeing, it would be better to use a PHP JSON library (like this one... http://php.net/manual/en/book.json.php)
Then you can send actual key value pairs, using JSON format like...
{"ques_5" : "19", "ques_4": "19"}
Try this
var array = ["9", "ques_5", "19", "ques_4"];
console.log(array.join(","));
above code will output string with comma separated like 9,ques_5,19,ques_4then paste it to ajax call.
And then in php explode that string.
Other possible solutions.
First
var obj = { 'item1': 'value1', 'item2': 'value2' };
$.ajax(
{
type: 'post',
cache: false ,
url: 'test/result.php',
data: { result : JSON.stringify(obj) },
success: function(resp)
{
alert(resp);
}
});
Second
var a = $.JSON.encode(obj);
$.ajax(
{
type: 'post',
cache: false ,
url: 'test/result.php',
data: { result : a },
success: function(resp)
{
alert(resp);
}
});
In PHP File
<?php
$json = $_POST["data"]
var_dump(json_decode($json));
?>
You can send the array in json format to the php and then use json_decode function to get back the array like
In ajax call you have to send json for that you need to first make array of the values so that you get it in right form
so that you json look like {"ques_5":"9","ques_4":19}
and use in ajax call
data: JSON.stringify(`your created json`),
contentType: "application/json; charset=utf-8",
dataType: "json",
IN PHP it look like
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
?>
I would like to share a complete example that works for me in order to avoid making each JavaScript function for each PHP function
// on the HTML side a simple JavaScript call from a link
<a href="javascript:CargaZona('democonllamada', 'tituloprin', {'key1':'value1','key2':'value2'})" >test</a>
<div id='tituloprin' >php function response here!</div>
// on JavaScript side
function CargaZona(fc, div, params) {
var destino = "#" + div;
var request = $.ajax({
url : "inc/phpfunc.php",
type : "POST",
data : {
fc : fc,
params : JSON.stringify(params)
},
dataType : "html"
});
request.done(function (msg) {
$(destino).html(msg);
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
}
// on phpfunc.php page
<?php
$params = "{'key1':'value1','key2':'value2'}";
$fc = 'def';
if (isset($_POST['fc'])) { $fc = $_POST['fc']; }
if (isset($_POST['params'])) { $params = $_POST['params']; }
switch ($fc) {
default:
call_user_func($fc,$params);
}
function democonllamada($params) {
$params = json_decode("$params", true);
echo "ok llegaron".$params['key1'];
}
?>