how i call javascript function in ajax callback function and how i can pass arguments to this javascript function like field name or something
'#ajax' => array(
'callback' => 'ajax_javascript_function',
'wrapper' => 'd-div-autocomplete-textfield-div',
'method' => 'replace',
'event' => 'blur',
'effect' => 'fade',
'progress' => array('type' => 'throbber', 'message' => ''),
),
You need to pass those variables to a server with javascript ajax JSONP. There are many ways, but here are 2 examples:
With plain querystring:
$.ajax({
type: "GET",
dataType: "jsonp",
url: "some.php?callback=mycallback",
data: "name=John&location=Boston",
success: function(response){
alert( "Data received: " + received);
},
error: function(e){
alert(e);
}
});
with object for querystring parameters
$.ajax({
type: "GET",
dataType: "jsonp",
url: "some.php?callback=mycallback",
data: {
"name" : "John",
"location" : "Boston"
}
success: function(response){
alert( "Data received: " + response );
},
error: function(e){
alert(e);
}
});
Your PHP code must output its response with the callback you asked for in this javascript (I used 'mycallback'). If you are not writing the PHP(or some kind of server side code) then that server must be agreeing to return responses wrapped with the callback function you asked for it to use. This way, the response gets into your javascript because you told it what function would be callable. This is called JSONP architecture. It works because the one thing that you can request Cross-Domain is a script.
PHP
echo "mycallback('" + $data + "');";
Good luck, read more here: http://api.jquery.com/jQuery.ajax/
Related
I'm getting 403 error in my plugin develop when I try to use ajax calls. I had disabled all plugins and activated default theme, no works. I have no cache plugin, and I have no server cache.
I get:
403
Forbidden
Access to this resource on the server is denied!
PHP
add_action('wp_ajax_actualizar_jornada', 'actualizar_jornada' );
add_action('wp_ajax_nopriv_actualizar_jornada', 'actualizar_jornada');
function actualizar_jornada() {
$postdata = $_POST;
echo $postdata;
wp_die();
}
LOCALIZATION SCRIPT
wp_register_script('lmfront-js', plugin_dir_url( __FILE__ ) . '../includes/js/lmfront.js');
wp_localize_script('lmfront-js', 'strings', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'lstJugadoresParticipantesPlaceholder' => __('Find Players', 'leaguemanagement'),
'lstEquiposTeamsPlaceholder' => __('Find Teams', 'leaguemanagement'),
));
wp_enqueue_script('lmfront-js');
JS
$('.btn-update-jornada').on('click', function(){
var idjornada = parseInt($(this).data('idjornada'));
var data = {
'action': 'actualizar_jornada',
'idjornada': idjornada,
'marcador_local': parseInt($('#resultado-local-' + idjornada).val()),
'marcador_visitante': parseInt($('#resultado-visitante-' + idjornada).val()),
};
$.ajax({
type : "post",
url : strings.ajaxurl,
data : data,
error: function(response){
console.error(response);
},
failure: function(response){
console.error(response);
},
success: function(response) {
console.log(response);
}
});
});
I have a form, when submitted, invokes an AJAX request. This ajax request performs back-end validation on the inputs. If an error is detected, it displays the error messages. So if the user fills out 30 fields, and one is not valid, I would like to return all those inputs with an error message.
My Laravel Code:
Route::post('/roa', function() {
$m = Request::except('_token');
$name = "form1_sections/" . $m['nextTab'] . "_form";//next view name
$name2 = "form1_sections/" . $m['currentTab'] . "_form";//current view name
$var= parse_str($m['inputs'], $output);//data from ajax is a string
if ($m['currentTab']=='section2'){//i'm only doing validation on one section right now
//to simplify the code.
$rules = [
'TB1_course.*' => 'required'
];
$validator=Validator::make($output, $rules);
if ($validator->passes()){//if no error, return the next view
return ["view" => view("$name")-> render(), "value"=>1, "inputs"=>$output];
}
return ["view" => view("$name2")->withInput($output)->withErrors($validator) -> render(), "value"=>1, "inputs"=>$output];
}
return ["view" => view("$name") -> render()];
});
My Ajax request:
$('#form').on('submit', function (e) {
var formData = $('#form').serialize();
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'POST',
url: '/roa',
dataType: 'json',
data: {inputs: formData, nextTab: relatedTabID, currentTab: tabID},
success: function(data){
$('#tabShow').html((data.view));
},
error: function () {
alert('error');
}
});
});
I am successfully able to receive all the error messages, but the withInput($output) for some reason is not working. Thank you for all your help.
'view' => view('template')->withInput()?
I try to send an HTTP POST request from ajax to PHP, but I have a syntax error that I don't understand..
Is there anyone who can help me ?
index.php
var key = "keytest";
$.ajax({
url: 'requests.php',
type: 'post',
contentType: 'application/json',
dataType: 'json',
data: '{"uniqueKey" : '+key+'}',
success:function( rep ) {
$('#content').html(rep.content);
},
error:function(a,b,err){
console.log(err);
}
});
requests.php
header('Content-type: application/json');
$uniqueKey = filter_input(INPUT_POST, 'uniqueKey');
$key = "newKey";
$retour = array('key' => $key);
echo json_encode($retour);
Don't build JSON by hand, use JSON.stringify
data: JSON.stringify({uniqueKey: key}),
Php does not populate $_POST(INPUT_POST) when the request body is JSON, only for application/x-www-form-urlencoded or multipart/form-data
To get json you'll have to read it from php://input
$json = file_get_contents('php://input');
$obj = json_decode($json);
$uniqueKey = $obj->uniqueKey;
Also you code only responds with a key value but the ajax request expects a content value. You should change the dataType to text to see if you get back what you expect.
$.ajax({
url: 'requests.php',
type: 'post',
contentType: 'application/json',
dataType: 'text',
data: JSON.stringify({uniqueKey: key}),
success:function( rep ) {
$('#content').html(rep);
},
error:function(a,b,err){
console.log(err);
}
});
How can i send extra parameters on my GRID POST.
This is my tranport config:
transport: {
read: {
dataType: "json",
url: "/user/list",
type: "POST"
}
}
I need to send a dynamic extra information ( especial filters XD).
I will set a script variable before any submit on grid.
Any Help?
Question is discussed multiple times on the internet. You should use the Data function. Here is even more information. You can also pass the parameters directly to the read method of the dataSource.
$('#myGrid').data().kendoGrid.dataSource.read({foo:42})
You can add extra parameters using Data("addParameter")
#(Html.Kendo().Grid<Project.Models.UserModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(item => item.UserId).Title("UserId").Width(100);
columns.Bound(item => item.UserName).Title("UserName").Width(200);
})
.Sortable()
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(5)
.Read(read => read.Action("list", "user").Data("addParameter"))
)
<script>
function addParameter()
{
return {
UserId: 10 //Your value here
};
}
</script>
Here is another alternative to send parameters to the AJAX call, and also to log the Request and Response.
read: function (options) {
var jsonData = {
"ID": $('#ID').val(),
"ObjectType": $('#dropObjectType :selected').val()
};
console.log("REQ: " + JSON.stringify(jsonData));
$.ajax({
type: "POST",
url: "/api/internal/SomeService",
data: jsonData,
success: function (result) {
console.log("RES: " + JSON.parse(JSON.stringify(result)));
You can also send the above jsonData in this way:
$("#grid").data("kendoGrid").dataSource.read(jsonData);
And assign it to the data: (and log it):
read: function (options) {
console.log("REQ: " + JSON.stringify(options.data));
$.ajax({
type: "POST",
url: "/api/internal/SomeService",
data: options.data,
I am trying to receive a json object back from php after sending data to the php file from the js file.
All I get is undefined.
Here are the contents of the php and js file.
data.php
<?php
$action = $_GET['user'];
$data = array( "first_name" => "Anthony",
"last_name" => "Garand",
"email" => "anthonygarand#gmail.com",
"password" => "changeme");
switch ($action) {
case 'anthonygarand#gmail.com':
echo $_GET['callback'] . '('. json_encode($data) . ');';
break;
}
?>
core.js
$(document).ready(function(){
$.ajax({ url: "data.php",
data: {"user":"anthonygarand#gmail.com"},
context: document.body,
data: "jsonp",
success: function(data){renderData(data);}
});
});
function renderData(data) {
document.write(data.first_name);
}
It looks like you have two data options set in the Ajax function. Instead of the line
data: "jsonp",
You need
dataType: "jsonp"
As you're not actually passing the PHP file any information.
Another couple of things, make sure you're getting valid JSON (jsonlint.com), we had a similar issue and it turned out we had the wrong kind of quotes.
Lastly: You MAY need to JSON.parse(data) to see convert it to an object at Javascript's end.