This question already has answers here:
Receive JSON POST with PHP
(12 answers)
Closed 9 months ago.
I am trying to pass data to my php page:
<?php
var_dump($_POST);
if (isset($_POST['goal']) && isset($_POST['amount'])){
$goal = $_POST['goal'];
$amount = $_POST['amount'];
$array = array(
"goal" => $goal,
"amount" => $amount
);
echo json_encode($array);
}
However as a result of var_dump $_POST I keep getting an empty array, for some reason my ajax doesn't pass the neccessary data. I tried console.logging the value of fields that I am using and their value is correct it's just that data doesn't pass on the php page.
ajax:
<script type="text/javascript">
$(document).ready(function () {
//use button click event
$("#goalBTN").click(function (e){
e.preventDefault();
let amount = $("#amount").val();
let goal = $("#goal_name").val();
$.ajax({
method: "post",
url: "target-modal-code.php",
data:JSON.stringify( {
amount: amount,
goal: goal
}),
contentType:"application/json",
success: function (response){
$("#response").text(response);
console.log(amount);
console.log(goal);
},
error: function(response) {
alert(JSON.stringify(response));
}
})
});
});
</script>
And my form is inside a modal :
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="enrollLabel">Change your goal</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form action="target-modal-code.php" name="target-form" id="target-form">
<div class="modal-body">
<form action="">
<div class="mb-3 input-control">
<label for="amount">Cost</label>
<input type="number" class="form-control" id="amount" name="amount"
placeholder="Amount">
<small class="message" id="message-password"></small>
<br>
</div>
<div class="mb-3 input-control">
<label for="goal_name">Goal</label>
<input type="text" class="form-control" id="goal_name" name="goal_name"
placeholder="Goal">
<small class="message" id="message-password"></small>
<br>
</div>
</form>
</div>
<p class="response" id="response"></p>
<div class="modal-footer">
<div class="response">
</div>
<button type="button" id="goalBTN" class="btn btn-warning">Save changes</button>
</div>
</form>
</div>
</div>
Updated answer after some live testing with Network tab in firefox web dev tools
The problem is that the current ajax code is not sending any of the elements because of wrong content-type. Let it detect content-type automatically. For jq ajax, default seems to be contentType: application/x-www-form-urlencoded even if you don't provide it specifically.
So, this worked:
<script type="text/javascript">
$(document).ready(function () {
//use button click event
$("#goalBTN").click(function (e){
e.preventDefault();
// let amount = $("#amount").val();
// let goal = $("#goal_name").val();
var formData = {
amount: $("#amount").val(),
goal_name: $("#goal_name").val(),
};
$.ajax({
method: "post",
url: "target-modal-code.php",
// datatype:"json",
//data:JSON.stringify(formData),
data: formData,
//contentType:"application/json",
//encode: true,
success: function (response){
$("#response").text(response);
// console.log(amount);
// console.log(goal);
console.log(formData);
},
error: function(response) {
alert(JSON.stringify(response));
}
})
});
});
</script>
After little bit of fiddling, I noticed that it works if you DON'T provide it contentType at all. Otherwise, AJAX won't send GET or POST params to the server.... dont know why. I know it's weird but that's how it is in jquery ajax.
I have intentionally kept the comments for you to see what all I have tried.
So to summarize,
Don't stringify the form data,
Don't provide contentType to ajax
request.
Cheers.!
format send ajax:
$.ajax({
...
data : {
foo : 'bar',
bar : 'foo'
},
...
});
in your case: change data send format like:
data: {
amount: amount,
goal: goal
}
Related
I'm new to ajax and hoping someone can help figure out how to add two form inputs. I have a hidden input that is getting the total sheets from a database. I also have an addSheets input that is getting the total of sheets to add. I'm posting code from my modal as well as the ajax and action. Any advice is greatly appreciated.
(index)
<html>
<body>
<div class="modal fade" id="addSheetsModal">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Add Paper</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body px-4">
<form action="" method="post" id="form-addSheets-data">
<input type="hidden" name="id" id="id">
<input type="hidden" name="sheets" id="sheets">
<div class="form-group">
<input type="text" name="addSheets" class="form-control" id="addSheets" placeholder="">
</div>
<div class="form-group">
<input type="submit" name="addSheetQty" id="addSheetQty" value="Add Paper" class="btn btn-success btn-block">
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
<script language="javascript" type="text/javascript">
// AJAX Edit Paper - Receive (Gets ID)
$("body").on("click", ".receiveBtn", function(e){
e.preventDefault();
r_edit_id = $(this).attr('id');
$.ajax({
url:"action.php",
type:"POST",
data:{r_edit_id:r_edit_id},
success:function(response){
data = JSON.parse(response);
console.log(data);
$("#id").val(data.id);
$("#sheets").val(data.sheets);
}
});
});
// Edit Paper - Update (Sums)
$("#addSheetQty").click(function(e){
if($("#form-addSheets-data")[0].checkValidity()){
e.preventDefault();
$.ajax({
url:"action.php",
type:"POST",
data: $("#form-addSheets-data").serialize()+"&action=addSheetQty",
success:function(response){
console.log(response);
Swal.fire({
title: 'Sheets added successfully!',
icon: 'success',
showConfirmButton: false,
timer: 1500
})
$("#addSheetsModal").modal('hide');
$("#form-addSheets-data")[0].reset();
showAllPapers();
}
});
}
});
</script>
<?php
// ACTION
if(isset($_POST['r_edit_id'])){
$id = $_POST['r_edit_id'];
$row = $db->getPaperById($id);
echo json_encode($row);
}
if(isset($_POST['action']) && $_POST['action'] == "addSheetQty"){
$id = $_POST['id'];
$sheets = $_POST['sheets'] + $_POST['addSheets'];
$db->updateSheetQty($id,$sheets);
}
?>
In the database the sheets column is varchar(255). In the php_error.log I'm getting this response: PHP Warning: A non-numeric value encountered in /Applications/MAMP/htdocs/PaperInventory/action.php on line 116 which is this line ($sheets = $_POST['sheets'] + $_POST['addSheets'];) in my code above.
Thanks for any input and help understanding this.
I have a payment page that has a multi-step form. In the "step 1" the user inserts his information like nama, surname, etc, then billing information.
So, in the "step 1" I have fields like name, surname, etc. I want in each step collect all information with jQuery so that is possible to send an ajax request to the server to validate the information when the "go to step 2" button is clicked.
My doubt is about how to properly store this step1 data inserted by the user to be possible to send it to the server. For example in the step 1 Im getting the values like:
var name = $('#name').val();
Then how to send the data to the server using an ajax post request?
step 1 html
<div class="tab-pane fade show active clearfix" id="step1" role="tabpanel" aria-labelledby="home-tab">
<h6>User Info</h6>
<form method="post" action="">
{{csrf_field()}}
<div class="form-group font-size-sm">
<label for="name" class="text-gray">Name</label>
<input type="text" required class="form-control" value="{{ (\Auth::check()) ? Auth::user()->name : old('name')}}">
</div>
<!-- other form fields -->
<input type="submit" id="goToStep2" href="#step2"
class="btn btn-primary btn float-right next-step" value="Go to step 2"/>
</form>
</div>
For the ajax part when "Go to step 2" is clicked I created a route 'storeUserInfo', but do you know how to send the data to the PaymentController?
$("a[id='goToStep2']").on('click', function(){
$.ajax({
url: '{{ route('products.storeUerInfo',null) }}',
type: 'POST',
success:function(result){
),
error: function(error) {
console.log(error.status)
}
});
});
This is a complete solution for form with file element
HTML
<div class="tab-pane fade show active clearfix" id="step1" role="tabpanel" aria-labelledby="home-tab">
<h6>User Info</h6>
<form method="post" action="" id="page-form">
{{csrf_field()}}
<div class="form-group font-size-sm">
<label for="name" class="text-gray">Name</label>
<input type="text" required class="form-control" value="{{ (\Auth::check()) ? Auth::user()->name : old('name')}}">
</div>
<!-- other form fields -->
<input type="submit" id="goToStep2" href="#step2"
class="btn btn-primary btn float-right next-step" value="Go to step 2"/>
</form>
</div>
JS
$(function () {
'use strict'
var page_form_id = "page-form";
$('#a[id='goToStep2']').on('click', function () {
$('#' + page_form_id + ' .error').html("");
$('#' + page_form_id + ' .form-group').removeClass("has-error");
var custom_form = $("#" + page_form_id);
var custom_params = custom_form.serializeArray();
var custom_files = $("#file")[0].files;
var custom_formData = new FormData();
for (var i = 0; i < custom_files.length; i++) {
custom_formData.append("file", custom_files[i]);
}
$(custom_params).each(function (custom_index, custom_element) {
custom_formData.append(custom_element.name, custom_element.value);
});
$.ajax({
method: "POST",
url: '{{ route('products.storeUerInfo',null) }}',
contentType: false,
processData: false,
data: custom_formData,
success: function (data, textStatus, jqXHR) {
setTimeout(function () {
window.location.reload();
}, 3000);
},
error: function (data) {
var errors = data.responseJSON;
$.each(errors['message'], function (index, value) {
$('#' + add_form_id + ' .eMsg_' + index).html(value[0]);
$('#' + add_form_id + ' .eMsg_' + index).parent().parent().addClass("has-error");
});
}
});
});
});
If you use form to send something. Better Use submit form method on JQuery. And give return false on the end of the function.
To check is it working, you can use inspect element on your browser on the console tab. If you see something error status it's maybe your code has something wrong.
In other way you can go to the url manually, without hitting by ajax. So you must make sure it works, before you want to use ajax.
Instead of gathering all of the data into variables separately, use the form online to submit inside your ajax call. First, call preventDefault() on the Event, and then you can use this line in your ajax call:
data:$('#myForm').serialize(),
PS, you add the event object as a parameter in your click listener. Then you can call event.preventDefault();.
$("a[id='goToStep2']").on('click', function(){ var name = $('#name').val();
$.ajax({ url: '{{ route('products.storeUserInfo',null) }}/' + category_id, type: 'POST',
data:{ "name": name},success:function(result){ ), error: function(error) { console.log(error.status) } }); });
I have some problems with receiving data when using an ajax call to EDIT my data. I'm trying to get data that the user has filled in but every time my data is empty or 'null'. Do i need to pass data in ajax call? Or are there other ways in laravel to get the data?
My code at the moment as we speak:
showuser.blade.php
<div class="comments">
#if(count($user->cars))
<h1>Auto in reparatie</h1>
<hr>
#foreach($user->cars as $car)
<!-- Form to show each car and edit / delete the cars -->
<!--<form action="{{ action('CarController#edit', [$user->id, $car->id]) }}" method="POST">-->
<form>
<div class="form-group">
<label for="brand">Merk:</label><br>
<select name="brand">
#foreach($brands as $brand)
<option value="{{$brand->id}}"{{ $brand->id == $car->brand_id ? ' selected="selected"' : '' }}>{{$brand->brandname}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="year">Bouwjaar:</label><br>
<input type="text" value="{{$car->year}}" name="year">
</div>
<div class="form-group">
<label for="licentsplate">Kenteken:</label><br>
<input type="text" value="{{$car->licensplate}}" name="licenseplate">
</div>
<div style="float: left; width: 80px">
<input type="submit" class="btn btn-primary" value="Edit" id="{{$car->id}}" name="editcar" />
</div>
</form>
<form>
<div class="form-group">
<button class="btn btn-primary" name="deletecar" id="{{$car->id}}">Delete</button>
</div>
</form>
#endforeach
#endif
</div>
Script
<script type="text/javascript">
$( document ).ready(function() {
$('[name="editcar"]').click(function (e){
e.preventDefault();
$.ajax({
type: "POST",
url: '/users/{{$user->id}}/cars/'+this.id,
success:function(data){
if(!data.error){
location.reload(true);
}
}
})
});
});
</script>
Routes
Route::post('/users/{userId}/cars/{carId}', 'CarController#edit');
CarController.php
// Function to edit a car by ID
public function edit($userId, $carId)
{
$car = Car::where('id', $carId)->where('user_id', $userId)->first();
$car->brand_id = request('brand');
dd(request('year'));
$car->year = request('year');
$car->licensplate = ('licenseplate');
$car->save();
}
If I dump and die request('brand'), request('year'), request('licenseplate') i get 'null'.
EDIT:
If I dd $car in my controller, i get the car that i need. Means that there is no problemen finding the right car.
Thx for reading!
You aren't posting any data in the AJAX request. Pass the form values through in an object.
var form = $(this).find('form');
var licenseval = form.find('input[name=licenseplate]').val();
var yearval = form.find('input[name=year]').val();
var brandval = form.find('select[name=brand]').find(":selected").val();
$.ajax({
type: "POST",
data: {licenseplate: licenseval, year: yearval, brand: brandval}
url: '/users/{{$user->id}}/cars/'+this.id,
success:function(data){
if(!data.error){
location.reload(true);
}
}
});
Change following lines:
public function edit($userId, $carId)
to
public function edit(Request $request, $userId, $carId)
and use
use Illuminate\Http\Request;
after that you can get $userId, $carId to use inside the controller function.
As per your ajax call you are only calling the route
Route::post('/users/{userId}/cars/{carId}', 'CarController#edit');
but you are not passing any other value. Your application is working as expected.
$.ajax({
type: "POST",
url: '/users/{{$user->id}}/cars/'+this.id,
//data: dataObject, ----->Missing Data which you want to pass (brand, year, licenceplate)
success:function(data){
//...
}
})
You are iterating through multiple $cars you need to get current car's data and pass to ajax call.
I am stil having issues with my code the file is not being processed when permalinks are set to anything other than default.
<div id="thanks" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Redeem Points</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" class="contact" name="commentform" >
<div class="form-group">
<h3>You may only redeem the maxium points of : <?php echo $maxpoints;?></h3>
<input type="hidden" name="playerid" value="<?php echo $playerId;;?>" />
<input type="number" valuemax="<?php echo $maxpoints;?>" name="points" class="form-control" placeholder="How many points do you wish to redeem." />
<label class="control-label col-md-4" for="Comments">Comments?</label>
<input type="text" name="comments" />
</div>
<div class="form-group">
<div class="col-md-6">
<button class="btn btn-success" id="submit">submit</button>
Close
</div>
</div>
</form>
</div><!-- End of Modal body -->
</div><!-- End of Modal content -->
</div><!-- End of Modal dialog -->
</div><!-- End of Modal -->
I thought the inital issue was the but when i turn permalinks off it appears to work ok I really dont no what the issue is here thanks. The html above is in the file /wp-content/themes/gogreensoccer5/kids-dashbaord.php as well as the jquery below i am at a loss.
type: "POST",
url: "/bin/sendredeempoints.php",
<script>
$('#thanks').modal('show').on('shown.bs.modal', function () {
//Ajax Method Call starts here
var points = $("#points").val();
$("#send_btn").click(function () {
var dataString = 'points=' + points;
alert(dataString);//Remove this
return false;//Remove this
$.ajax({
type: "POST",
url: "/bin/sendredeempoints.php",
data: $('form.contact').serialize(),
success: function (msg) {
$("#thanks").html(msg)
$("#form-content").modal('hide');
},
error: function () {
alert("failure");
}
});
//Ajax Method Ends
}); //Click Function ends
}); //Modal event Ends
</script>
Stop with the downvoting whoever it is.
Edit
Got A bit further
added this to my functions but its still saying file not found :-(
function load_these_scripts() {
wp_register_script( 'your_script', get_bloginfo('template_directory').'js/redeempoints.js', false, false, true );
wp_localize_script( 'my_ajax_script', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
}
add_action("wp_ajax_php_function_name", "redeempoints");
add_action("wp_ajax_nopriv_php_function_name", "redeempoints");
function redeempoints() {
// Some stuff here
global $wpdb;
// $result = $wpdb->get_results( /* SQL code goes here */ );
// Do something with $result
}
You may only redeem the maxium points of :
" />
" name="points" class="form-control" placeholder="How many points do you wish to redeem." />
Comments?
</div>
<div class="form-group">
<div class="col-md-6">
<button class="btn btn-success" id="submit">submit</button>
Close
</div>
</div>
</form>
my js file
var formdata = $('form.contact').serialize();
var allData = {
action: 'redeempoints',
data: formdata
}
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : allData,
success: function(response) {
if(response.type == "success") {
// Do something
}
else {
// Do something else
}
}
});
You need to change the way you use AJAX alongside WordPress :)
First up, in your functions.php (or plugin file), you'll have to localize admin-ajax.php and register a JS file where you'll make the AJAX calls - looks like this:
add_action( 'wp_enqueue_scripts', 'load_these_scripts' );
function load_these_scripts() {
wp_register_script( 'your_script', 'URI_OF_JS_THAT_MAKES_THE_AJAX_CALLS/scripts.js', false, false, true );
wp_localize_script( 'my_ajax_script', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
}
Then in your scripts.js you need to make the AJAX calls like this:
Use this instead of the "data :"
$("#send_btn").click(function () {
var formdata = $('form.contact').serialize();
var allData = {
action: 'php_function_name',
data: formdata
}
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : allData,
success: function(response) {
if(response.type == "success") {
// Do something
}
else {
// Do something else
}
}
});
});
The action: "php_function_name" actually tells WP which function to call but you also need register that well. Do it like this, back in your functions.php (or plugin file):
add_action("wp_ajax_php_function_name", "php_function_name");
add_action("wp_ajax_nopriv_php_function_name", "php_function_name");
function php_function_name() {
// Some stuff here
global $wpdb;
$result = $wpdb->get_results( /* SQL code goes here */ );
// Do something with $result
}
Make sure you register the function with both "wp_ajax" & "wp_ajax_norpiv" otherwise it will only work for logged in users.
Cheers
First. This is an ajax post. Using jquery post its a bit different http://api.jquery.com/jquery.post/
Your question is about posting in jquery, not ajax. So lets modify your code a little:
<script>
$('#thanks').modal('show').on('shown.bs.modal', function () {
var points = $("#points").val();
$("#send_btn").click(function () {
var dataString = 'points=' + points;
alert(dataString);//Remove this
return false;//Remove this
var url = "/bin/sendredeempoints.php";
var data = $('form.contact').serialize(),
$.post( url, { data: data })
.done(function() {
$("#thanks").html(msg)
$("#form-content").modal('hide');
}).fail({
alert("failure");
});
});//Click Function ends
}); //Modal event Ends
</script>
Posting with ajax is a pain in the ass. Since there is Jquery .post() its very easy. Modify if it's not correct. Let me know if it helped.
I see you use alert(). Use console.log() instead. No annoying popups. you can see the data in developer tools console.
EDIT2
The error you get, means your url isn't correct. You are trying to post to a file instead to an url.
I suppose you have an index file or a file that includes other files.
Enter some php code to the file that includes this script.
The php script checks in the url for data and if its true.
<?php
if(isset($_POST['data']) AND $_GET['data'] == 'true'){
//Go to your php file. or include it.
//EXAMPLE
include "/bin/sendredeempoints.php";
//On the sendredeempoints you can do whatever you want with the post.
}
?>
Change your var url to this:
var url = "YOURWEBSITE.com?data=true"; // or the easy one
var url = window.location.href + "?data=true";
I'm facing a problem using the FancyBox plugin. I'm trying to submit a form with Ajax and just print a nice little success message, no validation just yet, trying to get it to work. I can submit with jQuery and display the value of any input within the FancyBox. However when I try to execute Ajax it just closes the FancyBox down. I'm not an expert...
The FancyBox's content is generated using Ajax because it requires data from a database.
Here are the important code parts: (Texts are German...)
The file loaded into the FancyBox using Ajax
<script>
$("#submit").click(function() {
var login = $("#login").val();
$.ajax({
type: "POST",
url: "handleuseredit.php",
cache: false,
data: { login: login },
success: function(data){
if(data=='ok')
{
alert('Richtig.');
}
else
{
alert('Falsche Benutzername/Passwort Kombination.');
}
}
});
});
</script>
<div class="login">
<div class="widget_header">
<h4 class="widget_header_title wwIcon i_16_wysiwyg">Benutzer Bearbeiten</h4>
</div>
<div class="widget_contents lgNoPadding">
<form method="post" id="form-edit">
<p id="errormessagehere"></p>
<div class="line_grid">
<div class="g_3 g_3M"><span class="label">Benutzername</span></div>
<div class="g_9 g_9M">
<input type="text" name="login" id="login" value="<?php echo getusername($_GET['u']) ?>" class="simple_field tooltip" placeholder="Benutzername" autocomplete="off"></div>
<div class="clear"></div>
</div>
<div class="line_grid">
<div class="g_3 g_3M"><span class="label">Passwort</span></div>
<div class="g_9 g_9M">
********
</div>
<div class="clear"></div>
</div>
<div class="line_grid">
<div class="g_6">Abschicken
</div>
<div class="clear"></div>
</div>
</form>
</div>
</div>
Here's how I call the Fancy box
$(document).ready(function() {
$(".fancybox").fancybox({
'scrolling' : 'no',
'padding' : 0,
'titleShow' : false
});
});
handleuseredit.php just echoes "ok" to fullfill the data variable requirement.
You can test something like this with the version 2 of fancybox (http://fancyapps.com/fancybox/):
<script>
$("#submit").click(function() {
var login = $("#login").val();
$.ajax({
type: "POST",
url: "handleuseredit.php",
cache: false,
data: { login: login },
success: function(data){
if(data=='ok')
{
$.fancybox( '<h1>Richtig.</h1>' );
}
else
{
$.fancybox( '<h1>Falsche Benutzername/Passwort Kombination.</h1>' );
}
}
});
});
</script>