POST Request not working using Ajax in Laravel - javascript

I tried implementing ajax post request in laravel 4, but I am unable to obtain the post data. I have tried implenting both input::get() and input::all().
Here is the ajax code:
$.ajax({
url :url,
type:'POST',
data:{username:username},
dataType:'JSON',
success:function(data){
console.log(data);
}
});
Controller Class code:
class UserController extends Controller
{
// Obtain the response text
protected function _make_response( $response_str, $type = 'application/json' ) {
$response = Response::make( $response_str );
$response->header( 'Content-Type', $type );
return $response;
}
// User Login Function
public function loginAction()
{
// $setting_name = Input::get( 'username' );
$username = Input::get('username');
$response = array(
'username' =>$username,
);
return $this->_make_response( json_encode( $response ) );
}}
I am not able to paste the image here. So I am pasting the result that obtained from Firebug.
POST http://localhost/d/dthKerala/public 200 OK 117ms
Object {...}
But I change the request Type to GET. I am able to obtain the data.
GET http://localhost/d/dthKerala/public?username=render 200 OK 119ms
Object {username="render"}
How can I be able to obtain POST data ?

The mistake you made is sending data with a field value pair called => . Just change data to have a name "username" with value username
$.ajax({
url :url,
type:'POST',
data:{"username":username},
dataType:'JSON',
success:function(data){
console.log(data);
}
});
Hope this helps.

$.ajax(
{
url :url,
type:'POST',
dataType:'JSON',
data:{'username':username},
success:function(data){
console.log(data);
}
});

Will you be able to specify your route portion
Also I would like to suggest to use Response::json() instead of writing more line of codes:
public function loginAction()
{
return Response::json(array('str'=>$response_str))
}

Related

Passing value to php from local storage using Ajax

I.m want to pass the values from js to php that is stored in local storage
js
let cartItems = localStorage.getItem("productsInCart");
var jsonString = JSON.stringify(cartItems);
$.ajax({
url:"read.php",
method: "post",
data: {data : jsonString},
success: function(res){
console.log(res);
}
})
php
<?php
print_r($_POST)
?>
on .php im getting just "array ()"
using #reyno's method with all the code in the same file called 'store_user_order.php'
<?php
if(isset($_POST["data"])) {
print_r($_POST["data"]);
} else {
?>
<button>SEND</button><br/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"> </script>
<script>
const cartItems = localStorage.getItem("productsInCart");
const jsonString = JSON.stringify(cartItems);
$("button").click(function() {
$.ajax({
url: 'store_user_order.php',
method: 'post',
data: {
data: jsonString
},
success: function(res) {
$('body').append(res);
},
error: function(err) {
$('body').append(err);
}
});
})
</script>
<?php } ?>
This should work if you have items in the localstorage
While testing, for checking values use method: "get", make sure that your test values aren't huge - you will see submitted values in the address bar.
For testing (php + MySQL) I always use this method:
success ? changes() : errors_list();`
I don't use js, so deal with syntax yourself, please.
on .php im getting just "array ()"
You received an empty $ _POST array - nothing was sent.
Because there was nothing to send, or there was an error sending

Retrieve JSON return from PHP called from AJAX

I'm trying to call an PHP file via POST and retrieve its result back in the calling AJAX code. But unfortunately it doesn't seem to work. After fiddling around with my code I either get "undefined", "a page reload" or "an error in the console that my parameter used in the success function isn't defined"
Here's the ajax code:
function postComment(formdata) {
if (formdata.comment != '') {
$.ajax({
type: 'POST',
url: '../../includes/post_comment.php',
data: formdata,
headers: {
'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'
},
success: postSuccess(data), // function to handle the return
error: postError // function to handle errors
});
} else {
alert('Empty please write something!');
}
}
function postSuccess(data) {
console.log(data);
$('#commentform').get(0).reset();
displayComment(data);
}
and here is my PHP handler:
$ajax = ($_SERVER['REQUESTED_WITH'] === 'XMLHttpRequest');
$added = add_comment($mysqli, $_POST); // contains an array
if ($ajax) {
sendAjaxResponse($added);
} else {
sendStandardResponse($added);
}
function sendAjaxResponse($added)
{
header("Content-Type: application/x-javascript");
if ($added) {
header('Status: 201');
echo(json_encode($added));
} else {
header('Status: 400');
}
}
this is what added looks like in PHP:
$added = array(
'id' => $id,//integer example: 90
'comment_post_ID' => $story_ID, //integer example: 21
'comment_author' => $author, //String example: Dominic
'comment' => $comment, //String example: This is a comment
'comment_date' => $date); //DateTime/String example: 08/02/2016 1970-01-01 00:00:00
UPDATES
I changed the ajax code to the following:
$.ajax({
type: 'POST',
url: '../../includes/post_comment.php',
success: postSuccess,
data: formdata,
headers: {
'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'
},
error: postError,
});
Now I get the full HTML-Code of the page calling this ajax function
I tried to set aysnc: false in the ajax request but it didn't help, always getting the html code of the source (calling the ajax function).
As for now I´m moving to a different approach which doesn´t need the return data. But thanks for the help
The browser tries execute server response because of
header("Content-Type: application/x-javascript");
change to
header("Content-Type: application/json");

(Wordpress / AJAX): Update attachment title, description and alt from frontend

Using wordpress with AJAX I'm trying to update attachment meta from frontend. For some reasons I get json response "NaN" or null. This is a form for logged users so I'm not using wp_ajax_nopriv_
In my functions.php
add_action('wp_ajax_update_portfolio', 'update_portfolio_function' );
function update_portfolio_function(){
$id = $_POST['pid'];
$title = $_POST['itemtitle'];
$description = $_POST['itemdescription'];
$attachment = array(
'ID' => $id,
'post_title' => $title,
'post_content' => $description
);
// now update main post body
wp_update_post( $attachment );
die();
$response = array('pid'=>$id,'title'=>$title);
echo wp_send_json($response);
exit;
}
And in my jQuery / AJAX I have:
function update_info(id, itemtitle, itemdescription)
{
jQuery.ajax({
method: 'post',
url : ajaxurl,
dataType: "json",
data: {
'action':'update_portfolio_function',
'pid' : id,
'itemtitle' : itemtitle,
'itemdescription' : itemdescription,
},
success:function(data) {
alert(data.pid + data.title); //Damn
},
error: function(errorThrown){
console.log(errorThrown);
}
});
//alert("a");
}
As response I want to check if id and title have been submitted correctly. As you can see I'm using an alert to print them. Values are well passed into the jQuery function but I don't think they're received from my php side (or badly processed) since I get "NaN" as response on data.pid and data.title. Can you help me?
EDIT
My request details
My fault. Oversight here:
add_action('wp_ajax_update_portfolio', 'update_portfolio_function' );
should be
add_action('wp_ajax_update_portfolio_function', 'update_portfolio_function' );
Fixed.

$_POST empty after ajax post called

So the purpose of me using this ajax post is to use some JS variables in a wordpress loop, so I can call a custom loop depending on what the variables are in the ajax post.
Below is the ajax call.
$('.collection-more').click(function() {
$.ajax({
type: 'post',
url: 'http://tmet.dev/wp-content/themes/muban-trust/single-collection.php',
data: { "test" : "hello" },
success: function( data ) {
console.log( data );
}
});
})
Currently I'm sending hard-coded data.
In my single-collection.php page:
<?php
print_r($_POST);
if(isset($POST['filters[Artist]']))
{
$filters_obj = $_POST['filters[Artist]'];
$filters_array = json_decode($filters_obj, TRUE);
for($i = 0; $i < sizeof($filters_array); $i++)
{
echo '<p>h'.$obj->name.'</p>';
}
}
?>
I'm using the print_r just to debug the problem, currently it returns:
Array()
The problem is that I cannot access the Json object called "test" within the single-collection.php
How do I access it?
Thanks in advance!
EDIT: Screenshot of firebug
From ajax to php :
this is the conventional way
var payload = {
smth1: "name",
smth2: "age"
};
and then when calling ajax
$.ajax({
url: "somephp.php",
type: 'POST',
data: payload,
dataType: 'json',
crossDomain: true
})
From phpPost to javascript:
right way getting the post parameters:
$fields = $_POST['fields'];
$usernameGiven = $fields['smth1'];
$passwordGiven = $fields['smth2'];
and when returning smthn to javascript
$result = array(
"something" => "something",
"something2" => $something2
);
echo json_encode($result);
Use $_POST['test'] to access the test parameter. Your print_r() shows that it is filled in correctly.
Your PHP code is accessing $_POST['filters[Artist]'] but there is no such parameter in the Javascript. If you pass:
data: { 'filters[Artist]': somevalue }
you can access it in PHP as $_POST['filters']['Artist'].

Laravel 4, jQuery .ajax, No post input received

I must be missing something, didn't think this would have been a issue.
I have a login form that has no connection to laravel form, although its on the same domain, and a POST route with laravel at "login".
I can change it to GET and everything works, but I would like to use POST.
/online/index.html
$("#login").click(function(e){
console.log( $("#loginForm").serialize() );
var request = $.ajax({
url: "../login/",
type: "POST",
data: { test : "someuser" },
dataType: "json"
});
request.done(function( data ) {
console.log("Complete");
console.log(data);
});
request.fail(function( jqXHR, textStatus ) {
console.log("Failed");
console.log(textStatus);
});
});
Route::post('login', array('as' => 'login', 'uses' => 'AuthController#doLogin'));
( which is below /online/ )
class AuthController extends Controller {
public function doLogin(){
$username = Input::get('username');
$password = Input::get('password');
return Response::json(Input::all());
}
}
In the javascript console, when you press login, it shows...
Complete
[]
When it should say something like this...
Complete
[ test => "someuser" ]
Using Laravel 4, jQuery 1.8.3. Any ideas would be great... Thanks!
I just removed the trailing slash in the Ajax request URL and everything worked as planned.

Categories

Resources