Laravel Broadcast using pusher. ToOthers not working - laravel

$.ajaxSetup({
headers:{
'X-Socket-Id': Echo.socketId()
}
});
I also tried
var socket_id= Echo.socketId();
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
/* the route pointing to the post function */
url: '/event',
headers: { 'X-Socket-Id': socket_id }
type: 'POST',
/* send the csrf-token and the input to the controller */
data: {
_token: CSRF_TOKEN,
message: 'a message'
},
//dataType: 'JSON',
/* remind that 'data' is the response of the AjaxController */
success: function (data) {
$(".writeinfo").append(data.msg);
}
});
also laravel is supposed to add the x-socket-id header if im not mistaken without me doing it manually. according to this site
https://github.com/laravel/echo/blob/master/src/echo.ts
it contains this
registerjQueryAjaxSetup(): void {
if (typeof jQuery.ajax != 'undefined') {
jQuery.ajaxPrefilter((options, originalOptions, xhr) => {
if (this.socketId()) {
xhr.setRequestHeader('X-Socket-Id', this.socketId());
}
});
}
}
Also in my broadcast i made sure i used ->toOThers()
it works fine on vue its, in blade where it does not want to work, it sends to everyone on the channel. I was thinking its because im using ajax i needed to add a header with socket ID but no im not so sure.

Related

Laravel 8 Method Not Allowed 405 Ajax CRUD

I fixed my csrf
I fixed my route , route clear too
but still error show up .
I'm doing ajax form in modal :
My Route
Route::post('increp/store',[\App\Http\Controllers\IncrepController::class,'store'])->name('increp.store');
My ajax
// Create article Ajax request.
$('#submit_increp').click(function(e) {
e.preventDefault();
var data = $("#main-form").serialize();
$.ajax({
url: "{{ route('increp.store') }}",
type: 'POST',
data: data,
dataType: 'json',
beforeSend:function(){
$(document).find('span.error-text').text('');
},
success: function(result) {
if(result.errors) {
console.log(result.errors);
$('.alert-danger').html('');
$.each(result.errors, function(key, val) {
$('span.'+key+'_error').text(val[0]);
});
} else {
$('.alert-danger').hide();
$('.alert-success').show();
}
}
});
});
I doing this for days, i dont have idea how to fix this errors .
Network tab
Console tab

WordPress ajax call with add_filter

I have a WordPress function that works exactly how I want. The function below changes the email recipient in Contact Form 7 to abc#aol.com.
Now I need to use AJAX to update the email recipient to a dynamic value.
function wpcf7_dynamic_email_field($args) {
if(!empty($args['recipient'])) {
$args['recipient'] = str_replace('%admin%', 'abc#aol.com', $args['recipient']);
return $args;
}
return false;
}
add_filter('wpcf7_mail_components', 'wpcf7_dynamic_email_field');
Here's my AJAX call. I do not know how to tell the call to initiate the wpcf7_dynamic_email_field() function. Can that be done?
$.ajax({
url: ajaxurl, // or example_ajax_obj.ajaxurl if using on frontend
data: {
'action': 'update_team_page_contact_form',
'emailAddress' : emailAddress
},
success:function(data) {
// This outputs the result of the ajax request
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});

Not getting post data in controller from ajax

I am posting my form data to A controller but when I post data I am not getting in the controller when I call print_r($_POST); its returning null array I don't know what I have missed
Please let me know what inputs you want from my side
var data2 = [];
data2['user_firstname'] = user_firstname;
data2['user_lastname'] = user_lastname;
data2['user_phone'] = user_phone;
data2['user_email'] = user_email;
data2['user_username'] = user_username;
data2['user_password'] = user_password;
console.log(data2);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "http://localhost/shago/register/submit",
data: { 'data2': data2 },
// dataType: "text",
success: function(resultData) { console.log(resultData); }
});
controller code
public function submit()
{
print_r($_POST);
}
You can use the following
public function submit(Request $request)
{
dump($request);
}
Try adding Request as parameter on your submit function
public function submit(Request $request)
{
print_r($request);
}
Also, do you really need to pass your information as an array?
You could just create a new object and pass that as well.
var data2={
'user_firstname': user_firstname,
'user_lastname': user_lastname,
'user_phone': user_phone,
'user_email': user_email,
'user_username': user_username,
'user_password': user_password
};
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "http://localhost/shago/register/submit",
data: data2,
success: function(resultData) { console.log(resultData); }
});
You need to inject Request Class injection into submit method. This can help you:
public function submit(\Illuminate\Http\Request $request)
{
dd($request->all()); // will print all data
}
of if you don't want to inject Request then this code may helps you
public function submit()
{
dd(request()->all()); // will print all data
}
Good Luck !!!
Maybe the request was intercepted by Laravel CSRF Protection policy.In order to prove it, you should add request URL in VerifyCsrfToken middleware file, like following:
protected $except = [
'yoururl'
];
If you can get the data you expect in your controller, then I am right.
Thanks all i found error in when i am sending array data now i have modified code and its working fine
see code
$.ajax({
url: "register/submit",
type: "post",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {'user_firstname':user_firstname,'user_lastname':user_lastname,'user_phone':user_phone,'user_email':user_email,'user_username':user_username,'user_password':user_password},
success: function(result){
console.log(result);
}
});
}

Ajax GET for external api without CSRF checking

In my laravel 5.3 application I have enable CSRF checking globally for all ajax requests.
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
But I have an ajax GET request for an external api as follows.
$.ajax({
url: "https://api.xxxxxxxxxxx/v1/" +code+ "?api_key="+API_KEY,
type: "GET",
dataType: "text",
success: function (data) {
},
error: function (msg) {
}
});
I need to avoid CSRF checking here. I have tried two ways but nothing works for me. In VerifyCsrfToken.php
1st way
class VerifyCsrfToken extends BaseVerifier
{
protected $except = [
'https://api.xxxxxxxxx/v1/*'
];
}
2nd way
class VerifyCsrfToken extends BaseVerifier
{
if ( ! $request->is('https://api.xxxxxxxxx/v1/*'))
{
return parent::handle($request, $next);
}
return $next($request);
}
Please figure it out, how to solve this issue.
Finally, I figured out a way within javascript. We can delete the particular header before ajax call, then reassign the header again.
delete $.ajaxSettings.headers["X-CSRF-Token"];
$.ajax({
url: "https://api.xxxxxxxxxxx/v1/" +code+ "?api_key="+API_KEY,
type: "GET",
dataType: "text",
success: function (data) {
},
error: function (msg) {
}
});
$.ajaxSettings.headers["X-CSRF-Token"] = $('meta[name=_token]').attr('content');
You can override the ajaxSetup in that ajax call like this.
$.ajax({
url: "https://api.xxxxxxxxxxx/v1/" +code+ "?api_key="+API_KEY,
type: "GET",
dataType: "text",
headers : {},
success: function (data) {
},
error: function (msg) {
}
});
Although, you shouldn't use ajaxSetup.
The settings specified here will affect all calls to $.ajax or Ajax-based derivatives such as $.get(). This can cause undesirable behavior since other callers (for example, plugins) may be expecting the normal default settings. For that reason we strongly recommend against using this API. Instead, set the options explicitly in the call or define a simple plugin to do so. : https://api.jquery.com/jquery.ajaxsetup/
This should help
$.ajax({
type:'GET',
url:"https://api.xxxxxxxxxxx/v1/" +code+ "?api_key="+API_KEY,
data:{_token: "{{ csrf_token() }}",
},
success: function( msg ) {
}
});

Joomla 2.5 Ajax component not working

I've been trying for ages to get Json working in Joomla and I just can't do it. I think I've tried every combination of URL etc so any help would be great:
this is for the admin side structure looks like
admin
-controllers
--orderitem.php
-views
--orderitem
---tmpl
----orderitem.php
-controller.php
function updateNow(newrefresh) {
var dataJSON = JSON.encode (newrefresh);
var request = new Request.JSON({
method: 'post',
url: 'index.php?option=com_customersitedetails&view=orderitem&task=refreshscreen&format=raw',
data: {
json: dataJSON
},
onComplete: function(jsonObj) {
alert("Your form has been successfully submitted ");
}
}).send();
};
Although runs the alert box it doesn't retun JSON just
View not found [name, type, prefix]: orderitem, raw, customersitedetailsView
Any ideas where I can start? thanks
You're missing views/orderitem/view.raw.php containing a CustomersitedetailsViewOrderitem class.
views/orderitem/view.raw.php
class CustomersitedetailsViewOrderitem extends JViewLegacy
{
public function display($tpl = null)
{
$response = 'Your magic response here';
echo $response;
JFactory::getApplication()->close();
}
}
You can look here for proper ajax call in joomla
How to Write PHP in AJAX
inside your controllers you should have a file "mycall.json.php" this file will process and return a json format of your ajax call
Joomla doesn't gives a build in AJAX as part of it's system. my answer is from Josef Leblanc course in lynda.com
http://www.lynda.com/Joomla-1-6-tutorials/Joomla-1-7-Programming-and-Packaging-Extensions/73654-2.html
As I said :
Write this i the frontend JS :
$.ajax({
type: 'GET',
url: 'index.php',
data: {option: 'com_componenetname', task: 'taskname.youroperation', format: 'json', tmpl: 'raw'},
dataType: 'json',
async: true, // can be false also
error: function(xhr, status, error) {
console.log("AJAX ERROR in taskToggleSuceess: ")
var err = eval("(" + xhr.responseText + ")");
console.log(err.Message);
},
success: function(response){
// on success do something
// use response.valuname for server's data
}
,
complete: function() {
// stop waiting if necessary
}
});
in the backend you should have a file under com_componentname/controllers/taskname.json.php
the file should look like this
class ComponentnameControllerTaskname extends JControllerLegacy (Legacy only J3.0)
{
public function __construct($config = array())
{
parent::__construct($config);
$this->registerTask('operationname', 'functionname');
}
public function functionname() {
// do something in backend
echo json_encode(array(''var1' => val1, 'var2' => val2 ) );
}
}
nibra - I use this in all my joomla sites and its working perfect. your comment was wrong, pease give me my credit back

Resources