Laravel Accessing JSON Post - php

I am struggling to post JSON data to Laravel. I have tried a number of ways to access the data in my controller, however, it returns []. I am not sure what I am doing wrong. I would greatly appreciate any help!
console.log(JSON.stringify(data)) output:
[{"ContactFirstName":"John","FamilyLastName":"Doe"}, {"ContactFirstName":"John","FamilyLastName":"Doe"}]
The AJAX Script:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$.ajax({
url: POST_URL,
type: 'POST',
dataType: "json",
data: data,
success: function (data) {
console.log(data);
alert(JSON.stringify(data));
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
}
});
The Laravel Controller:
$json = Request::json()->all();
return $json;
It returns []. I have tried Input::all() too and had no luck.

$JSON = file_get_contents('php://input');

Related

laravel 5.6 default login with ajax gives 422 Unprocessable Entity

I am using laravel 5.6 and I am trying to login with ajax. I have set all the things =>csrf ajax setup and also passing token, but I am still getting this when all credentials are right:
THis is my ajax code
$(document).ready(function () {
$('#sign-in-form').submit(function(ev) {
ev.preventDefault();
formData = $('#sign-in-form').serialize();
$.ajax({
url: '{{route('login')}}',
type: 'POST',
data: formData,
dataType: 'JSON',
beforeSend: function () {
// element.value='Processing...';
},
success: function (result, status, xhr) {
console.log(result);
},
error: function (xhr, status, error) {
alert(error);
}
});
})
});
There is nothing wrong with your codes. The message is the result of validations. To solve your issue you may need to enter at least 6 characters or more for your password and that should work.
Hope that helps.

return a json value from an mvc controller method in php

i would like to get an json type value from an mvc controller method. everything is correct but an error occures'.
my jquery ajax function:
function user_login(uname,pass){
$.ajax({
url: 'http://localhost/s/login_request',
type:'POST',
data:{uname:uname,pass:pass},
dataType:"json",
cache: false,
})
.done(function(response){
//do something
alert('1234');
})
.fail(function(jqXHR,textStatus){
alert(JSON.stringify(jqXHR));
});
}
and here is my php code(mvc controller method):
function login_request(){
header('Content-Type: application/json');
echo json_encode(array('testvalue'));
}
when i run the code, the .fail section executed and the following value was returned:
{"readyState":4,"responseText":"[\"testvalue\"]","status":200,"statusText":"OK"}
how can i solve this? thanks...
Try using
$.ajax({
url: 'http://localhost/s/login_request',
type:'POST',
data:{uname:uname,pass:pass},
dataType:"json",
cache: false,
success: function(data) { },
fail: function(xhr, status) { alert(JSON.stringify(xhr)) },
error: function() { },
complete: function() { alert('1234') }
});

Can't call ajax POST request inside FB.api

For Facebook login I'm using this code
FB.api('/me', {fields: 'birthday,cover,devices,email,first_name,gender,id,last_name,link,location,name,name_format,timezone,verified,website,locale'}, function(response) {
$.ajax({
url: '/login/facebook',
type: 'POST',
data: { fb: response, window: window.ui},
dataType: 'json',
success: function (data) {
console.log(data);
},
error: function (xhr, ajaxOptions, thrownError){
notice(xhr);
notice(ajaxOptions);
}
});
});
If i'm calling without {fields: '...'} its working but when added fields ajax sending GET request to server instead of post, how to get response with desired fields from FB.API and post it to server?
I fixed this problem with little change in code instead of url: '/login/facebook', I wrote url: '/login/facebook/', just / at the end and problem solved !
Did you try?
FB.api('/me', 'post', {fields: 'birthday,cover,devices,email,first_name,gender,id,last_name,link,location,name,name_format,timezone,verified,website,locale'}, function(response) {
$.ajax({
url: '/login/facebook',
type: 'POST',
data: { fb: response, window: window.ui},
dataType: 'json',
success: function (data) {
console.log(data);
},
error: function (xhr, ajaxOptions, thrownError){
notice(xhr);
notice(ajaxOptions);
}
});
});

how to add header while posting a url and raw data in php

i have to pass header information while posting a url and want to pass raw data in the url can any on help me on this
i have tried
function test(){
alert("test");
$.ajax({
type:"POST",
beforeSend: function (request)
{
request.setRequestHeader("X-APIKEY", "y5q9q1at8u-1uf4bao2yq-bsjdj3gh1g-u9ymh1t2f8-tt85pn4r50");
},
url: "https://backoffice.hostcontrol.com/api/v1/domain-is",
data: {"domain": "mahrosh.com"},
processData: false,
success: function(msg) {
alert(msg);
$("#results").append("The result =" + StringifyPretty(msg));
}
});
}
its not returning me results
You can add header variables as per given in below described code
function test(){
alert("test");
$.ajax({
type:"POST",
headers: { 'X-APIKEY': 'y5q9q1at8u-1uf4bao2yq-bsjdj3gh1g-u9ymh1t2f8-tt85pn4r50'},
url: "https://backoffice.hostcontrol.com/api/v1/domain-is",
data: {"domain": "mahrosh.com"},
processData: false,
success: function(data) {
alert(JSON.stringify(data));
},
error: function(data){
alert(JSON.stringify(data));
}
});
}
If server gives error in response than you have idea about it so i added the error section as well ...

How to get JSON vars from PHP script

I have a problem:
I have a JS function which sending data to php script, then PHP script returning JSON data from database QUERY and I want to get values returned from PHP script.
<script type="text/javascript">
<!--
jQuery('#wysz2').submit(function() {
var myData = {
"rodzaj_konta": jQuery('#rodzaj_konta').val(),
"miejscowosc": jQuery('#miejscowosc').val()
};
jQuery.ajax({
url: 'http://somescript.php?action=results',
type: 'GET',
data: myData,
dataType: 'json',
beforeSend: function() {
jQuery('#loading').html('<p>loading...</p><img src="loading.gif" />'); //Loading image during the Ajax Request
},
error: function(xhr, textStatus, errorThrown) {
alert("Error: " + (errorThrown ? errorThrown : xhr.status));
},
contentType: "application/json; charset=utf-8",
success: function(data) {
alert(data);
}
});
return false;
});
//-->​
</script>
The PHP script returning data in proper format using:
header('Content-Type: application/json');
echo json_encode($data);
When I'm trying to alert(data), I get always a null.
How to get this returned JSON data ?
EDITED:
It's strange, because I have changed sending method to POST.
PHP returning JSON:
[{"nazwa":"Test","nazwa_firmy":"Testowa","ulica":null,"numer_domy":"2A","numer_mieszkania":"11","kod_pocztowy":"00-189","miejscowosc":"Warszawa","telefon":"213-123-132","nip":"112-312-31-31","regon":"231232133","adres_www":"http:\/\/www.gogl.epl","rodzaj_uzytkownika":"serwis"}]
But my JQUERY AJAX Script still returning null.
So my script now looks like this:
<script type="text/javascript">
<!--
jQuery('#wysz2').submit(function() {
var myData = {
rodzaj_konta: jQuery('#rodzaj_konta').val(),
miejscowosc: jQuery('#miejscowosc').val()
};
jQuery.ajax({
url: 'http://somedomain.com/skrypt.php?action=wyniki_wyszukiwania',
type: 'GET',
data: myData,
dataType: 'json',
contentType: "application/json; charset=utf-8",
jsonp: "jsoncallback",
beforeSend: function() {
jQuery('#loading').html('<p>ładowanie...</p><img src="loading.gif" />');//Loading image during the Ajax Request
},
error: function (xhr, textStatus, errorThrown) {
alert("Error: " + (errorThrown ? errorThrown : xhr.status));
},
success: function (data) {
alert(JSON.stringify(data));
console.log(data);
}
});
return false;
});
//-->
</script>
Any ideas ?
you are constructing your variables while sending in a wrong way semicoluns for object names is not there according to definitions
try this
var myData = {
rodzaj_konta: jQuery('#rodzaj_konta').val(),
miejscowosc: jQuery('#miejscowosc').val()
};
and while alerting your json data try
alert(JSON.stringify(your_json_obj));
Try to alert the object of the result...
Means if json in the format {"responseCode":"001","responseMsg":"success"}
Then alert data.responseCode
In success of your ajax function try something like this
var objParams1 = $.parseJSON(data);
console.log(objParams1);
alert(objParams1.Testowa)

Categories