Using JQuery and AJAX to pass data to a PHP script - javascript

I have an HTML form that Is only composed of a button with a value. I would like to leave it this way. I am using AJAX/JQuery to pass the form data to a PHP script. But, for some reason, the button value is not sent. What could I be doing wrong?
HTML:
<form id="friend-send" method="post" action="">
<button type="submit" class="foll" name="approve-friend" value="4"> Approve </button>
</form>
AJAX/JQUERY:
$(document).ready(function() {
$("#friend-send").submit(function(e) {
var $this = $(this);
var dataString = $this.serialize();
e.preventDefault();
$.ajax({
type: "POST",
url: "relate.php",
data: dataString,
async: false,
success: function() {
$this.hide();
}
});
});
});

JQuery won't serialize a button, use a hidden field instead
<form id="friend-send" method="post" action="">
<input type="hidden" name="approve-friend" value="4" />
<button type="submit" class="foll"> Approve </button>
</form>
Also, You need to serialze the form by id, not the button by id
Instead of this
$("#friend-request-buttons")
It should be this
$("#friend-send")
Lastly, since you are using ajax to post, you can simplfy your form open tag to this...
<form id="friend-send">

<button>
tags are not supported by serialize https://api.jquery.com/serialize/
You would need to use an input of some kind. A hidden one would work.

Don't use serialize, create the input data yourself:
var dataString = {};
var $button = $this.find("[type=submit]");
dataString[$button.attr('name')] = $button.val();
When you provide an object as the data: argument to $.ajax, jQuery will serialize it automatically.

This answer would be if you are set on using the button alone
$(document).ready(function() {
$("#friend-send").submit(function(e) {
var $this = $(this);
var dataString = "?" + $(this).find('button').attr('name') + "=" + $(this).find('button').attr('value');
e.preventDefault();
$.ajax({
type: "POST",
url: "relate.php",
data: dataString,
async: false,
success: function() {
$this.hide();
}
});
});
});

Related

POST method not supported when submitting multiple forms through the same JS code. (405)

I have multiple forms on the same page that are submitted through the same JavaScript code.
<form class="form" id="cancelchallenge" method="POST" action="{{action('ChallengeController#cancelChallenge')}}">
<input type="hidden" name="cancel_challengeid" value="462f2e80-8012-11e9-8b02-65a0a3459d7a">
<button type="button" class="btn-submit-cancelchallenge">cancel challenge</button>
</form>
<form class="form" id="cancelchallenge" method="POST" action="{{action('ChallengeController#cancelChallenge')}}">
<input type="hidden" name="cancel_challengeid" value="9b9ef9d0-8012-11e9-aa0f-95ff09733e52">
<button type="button" class="btn-submit-cancelchallenge">cancel challenge</button>
</form>
There could be any number of forms all of which will have a unique value for each hidden input.
Here is my JavaScript code
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(".btn-submit-cancelchallenge").click(function(e){e.preventDefault();
var $form = $('#cancelchallenge');
var cancel_challengeid = $("input[name=cancel_challengeid]").val();
$.ajax({
type:'POST',
url: $form.attr('action'),
data:{cancel_challengeid:cancel_challengeid},
success:function(data){
if(data.successful) {
toastr.success(data.successful);
}
}
});
});
If I submit any given form using the above code it works but it will always only submit the input value - from the first form - regardless of which form I submit.
Okay So I realise I shouldn't be using the same ID's in multiple forms so I change the form ID from:
id="cancelchallenge" to class="cancelchallenge"
and then update the JS code from:
var $form = $('#cancelchallenge'); to var $form = $(this);
thinking that will allow to submit any given form with the correct input value. However this now results in a 405 error.
"The POST method is not supported for this route. Supported methods: GET, HEAD."
My route looks like this:
Route::post('cancelChallenge', 'ChallengeController#cancelChallenge');
Briefly my controller looks like this:
public function cancelChallenge(Request $request)
{
//Some validation
$challenge = Challenge::where(['id' => $request->cancel_challengeid,
'player1' => Auth::user()->id])->first();
//DB::beginTransaction();
//Update a row in the challenges table
//Insert a row into the transactions table
//Update a row in the users table
//Commit transaction
}
Anyone able to point me in the right direction? Thanks.
$(this) - current element.
el.parent() - parent of element.
el.find() - find selector inside element.
$('.btn-submit-cancelchallenge').click(function(e){
e.preventDefault();
let $form = $(this).parent();
let cancel_challengeid = $form.find('input[name=cancel_challengeid]').val();
$.ajax({
type:'POST',
url: $form.attr('action'),
data: {cancel_challengeid: cancel_challengeid},
success:function(data){
if(data.successful) {
toastr.success(data.successful);
}
}
});
});
Or better:
$('.btn-submit-cancelchallenge').click(function(e){
e.preventDefault();
let form = $(this).parent();
$.ajax({
type:'POST',
url: form.attr('action'),
data: form.serialize(),
success:function(data){
if(data.successful) {
toastr.success(data.successful);
}
}
});
});

Cannot get $_POST('input') using jQuery .submit()

I was trying to upload a form using jQuery's submit() and success in redirect the page to uploadAll.php, but when I was trying to get the input array using $_POST['inputname'] I can not obtain the value.
I was trying to use serialize() but I get confused in where I should put my PHP page reference.
<form id="regForm" action="uploadAll.php" method="post" enctype="multipart/form-data">
//some inputs and a hidden input here
</form>
document.getElementById("regForm").submit(function() {
var inputValues = $(this).serialize();
$.ajax({
url: "uploadAll.php",
type: "POST",
data: inputValues
}).done(function(data) {
alert(data);
});
});
return false;
Can I just submit without using serialize()? It seems my serialize does not work. Any help is appreciated
trust me, your code is wrong..
try use this code instead:
$("#regForm").on('submit', function(e) {
e.preventDefault();
var inputValues = $(this).serialize();
$.ajax({
url: "uploadAll.php",
type: "POST",
data: inputValues
}).done(function(data) {
alert(data);
});
});

How to send AJAX form without using HTML <form> tag

I want to send data to my PHP using AJAX but without using the HTML <form> tag because in my case if I have the form I have a loop of sending the form and AJAX PHP came into looping so I think I would not use form but how can I apply these if AJAX had a method of POST?
$(document).on('click', '#myButton', function(){
$.ajax({
url: "insert.php",
method: "post",
data:{data},
dataType:"text",
success:function(data){
alert('Successfully')
}
})
})
and my HTML is:
<div class = "myDiv1">
<input type = "text">
<input type = "button" id = "myButton">
</div>
Is there a possible way to do this? I'm just asking. Thank you :)
Javascript
$(document).on('click', '#myButton', function(){
$.ajax({
url: "insert.php",
method: "post",
data:{
text: $('.text-value').val()
},
dataType:"text",
success:function(data){
alert('Successfully')
}
})
})
HTML
<div class = "myDiv1">
<input type = "text" class="text-value">
<input type = "button" id = "myButton">
</div>
You can assign values to data in ajax like
var formData = {
value1 = $(element1).val();
value2 = $(element2).val();
// and so on
}
Pass the formData to ajax

How to send multiple variables through ajax?

The code below sends the id of item to more.php to load more content. It works fine. Now to add some more features I need to send one more id to more.php through the same code.
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','.show_more',function(){
var ID = $(this).attr('id');
$('.show_more').hide();
$('.loding').show();
$.ajax({
type:'POST',
url:'more.php',
data:'id='+ID,
success:function(html){
$('#show_more_main'+ID).remove();
$('.display').append(html);
}
});
});
});
</script>
Suppose second id is var catid = '<?php echo $cat ?>'; how to send this catid through the same ajax code. data : {id : id, catid : catid} is something I should do but can't get how to deal in current situation when my data carries data:'id='+ID,.
your should look like. specify your data as an object:
<script type="text/javascript">
$(document).ready(function () {
$(document).on('click', '.show_more', function () {
var ID = $(this).attr('id');
$('.show_more').hide();
$('.loding').show();
$.ajax({
type: 'POST',
url: 'more.php',
data: { id:ID, userid: userid },
success: function (html) {
$('#show_more_main' + ID).remove();
$('.display').append(html);
}
});
});
});
To retrieve multiple input's I suggest combining them in a Form:
first embed your inputs in an form with a submit button, you should also not use the same name twice because it won't work now, create unique names
<form action="GET" id="myForm">
<input id="string" type="text" name="string" />
<input id="string2" type="text" name="string" />
<input type="submit" value="Go" />
</form>
and write code to submit the ajax way
$('#myForm').submit(function(event) {
// Stop form from submitting normally
event.preventDefault();
var $form = $(this);
$.ajax({
type: "GET",
url: "retrieve.php",
data: $form.serialize(), //make it JSON
success: function() {
console.log("it worked");
}
});
});

Submitting forms using jquery $.ajax - oly the first submits

I've got a problem with submitting AJAX forms - using this tutorial.
My forms are in div#upform and when I'm trying to submit any of them via $.ajax it submits only the first one, here's the code:
$(function() {
$(".button").click(function() {
var txt = $(".tekst#test").val();
var dataString = 'tekst='+ tekscior;
$.ajax({
type: "POST",
url: "upload/base",
data: dataString,
success: function() {
$('#upform').html("<div id='message'></div>");
$('#message').html("<h2>described!</h2>")
.append("<p>thanks!</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='http://artivia-dev2/i/check.png' />");
});
}
});
return false;
});
});
AND Here are my forms:
<!-- ONLY THIS ONE IS SUBMITTED, EVEN WHEN I'M SUBMITTING THE SECOND ONE! -->
<div class="slidingDiv">
<div id="upform">
<form name="contact" action="">
<input type="text" value="TESTFORM" class="tekst" id="test">
<input type="submit" name="submit" class="button" id="submit" value="Send" />
<form>
</div>
<div class="slidingDiv">
<div id="upform">
<form name="contact" action="">
<input type="text" value="TESTFORM" class="tekst" id="test">
<input type="submit" name="submit" class="button" id="submit" value="Send" />
<form>
</div>
##UPDATE
Problem, when I submit one form - it's great - but when after this one submit I want to submit the second - the data is submitted correctly, but the success messages are refreshed in both forms, that's the fix, which I've triend to use, but it doesn't work:
$.ajax({
type: "POST",
url: "upload/base",
data: dataString,
success: function() {
upform.html("<div class='message'></div>");
var mess = $(this).closest('.message');
mess.html("<h2>Described</h2>")
.append("<p>Thanks!</p>")
.hide()
.fadeIn(1500, function() {
mess.append("<img id='checkmark' src='http://ar-dev2/i/check.png' />");
});
}
});
First, you should not use same id to multiple element. Instead of that you may use class or name or data attribute.
$(".button").click(function() {
var upform = $(this).closest('.upform'); // keep reference of upform
var txt = $(this).prev(".tekst").val(); // this will retrieve the value of input
// nearest to the button
var dataString = 'tekst='+ tekscior;
......
$.ajax({
type: "POST",
url: "upload/base",
data: dataString,
success: function() {
upform.html();
.....
}
});
});
Problem with var txt = $(".tekst#test"); selector:
It has been started searching from top and when it found a match it stop journey and return the value and you always get the value of first one. If you use
var txt = $(".tekst"); without id, you will face the same problem.
IDs are singular. You can not have the same id on the page more than once!
If you want to repeat identifiers, use name.
You should be using different ids for both the forms. Both your forms have the same id upform

Categories