Post request on Mootools - ajax

I'm new to MooTools and trying to send Ajax request with form content to the url.
<form method="post" enctype="multipart/form-data" action="<?= $PHP_SELF; ?>" name="fn" id="fn">
<input name="user_name" id="user_name">
<input name="user_mail" id="user_name">
<input name="user_text" id="user_name">
<input type="file" name="attach">
<input id="button" type="button" value="Submit">
</form>
<script type="text/javascript">
$('button').addEvent('click', function(event) {
var req = new Request({
method: 'post',
url: 'url.php',
onSuccess: function(response) {
alert(response);
});
});
</script>
When I click on button, nothing happens. How right transferring data from form?

Your code looks good, you had a } missing but aside from that you just forgot to add a .send();
Like req.send();, and you can actually pass the data as a argument to that method.
Test that and check here about the .send() method.
Suggention to how your code could look like:
<script type="text/javascript">
var req = new Request({
method: 'post',
url: 'url.php',
onSuccess: function(response) {
alert(response);
} // < --- You actually missed this one
});
$('button').addEvent('click', function(event) {
req.send();
});
</script>

Related

Refresh the likes counter without reloading the Ajax page

It was necessary to write a method for salting posts in php and decorate the whole thing with ajax so that the page would not reload. The method was written, likes are put, but for the changes to be visible, you need to reload the page. I suspect I made a mistake in the area of success
This is part of the post, you need to update the button with id = "likebtn {{$ post-> id}}"
html form
<form action="{{route('likePost', ['id' => Auth::user()->id, 'postId' => $post->id])}}" method="POST" id="likepostform{{$post->id}}">
#csrf #method('PATCH')
<button data-id="{{$post->id}}" id="likebtn{{$post->id}}" type="submit" class="likebtn button-delete-post-2">
<img src="{{asset('img/footer/like.png')}}" class="img-fluid" width="25"><small class="text-muted mr-4">{{$post->likepost}}</small>
</button>
<input type="hidden" value="{{Auth::user()->id}}" id="user_id">
</form>
Ajax
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function () {
$("body").on("click",".likebtn",function(e){
e.preventDefault();
var id = $(this).data('id');
var token = $("meta[name='csrf-token']").attr("content");
var user_id = $("#user_id").val();
$.ajax({
url: "id"+user_id+"/"+id+"/like",
type: 'PATCH',
data: {_token: token, id: id, user_id: user_id},
success: function (data){
$("#likebtn"+id).html($(data).find("#likebtn"+id).html());
},
error: function() {
alert('error');
}
});
});
});
</script>

File Data is blank array in server side: Laravel 5.3

I am trying to post File using JQuery. Below is my code.
<script language="javascript">
$(document).ready(function() {
$('#frmUpdateProfile').on("submit", function(event) {
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
var data = {
"FileName" : event.target.FileName.files,
"_token" : "{!! csrf_token() !!}"
};
$.ajax({
url: '{{URL::route("UpdateProfile")}}',
method: "POST",
async: true,
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=utf-8",
success: function (msg) {
SuccessCallback(msg);
},
error: function (jqXHR) {
ErrorCallback(jqXHR);
}
});
});
});
</script>
I tried processData: false,. While debugging in Js, you can check that image is coming in the data. Below is the screenshot.
But when I print the request data in Laravel, it show blank array.
Html form is here
<form method="POST"
action="http://localhost:1234/AS6-Code/public/UpdateProfile"
accept-charset="UTF-8"
enctype="multipart/form-data"
id="frmUpdateProfile">
<input name="_token" type="hidden" value="26KWkWdNqe5iOFE8VRBf1dRnL5xKxwN25jg3tAFW">
<input type="hidden" name="_token" value="26KWkWdNqe5iOFE8VRBf1dRnL5xKxwN25jg3tAFW">
<input multiple="1" name="FileName" type="file">
<input class="btn btn-info" type="submit" value="Update">
</form>
Am I doing something wrong?
Try sending your request with FormData instead:
var data = new FormData($('#frmUpdateProfile')[0]);
Also set contentType to false:
contentType: false
Also Update
event.target.FileName.files
to
event.target.FileName.files[0]
event.target.FileName.files is a FileList object. I believe you need event.target.FileName.files[0] instead.

input(file) and input (text) send with one ajax

html
<body>
<form method="post" action="" id="dataForm" enctype="multipart/form-data">
<input type="text" id="textSelector"/>
<input type="file" id="fileSelector"/>
<button name="sub-comfirm" class="btn-selection-content" type="submit" id="sub-comfirm">Send</button>
</form>
</body>
js/ajax
var fileVar = null;// global var to store file info
$(document).ready(function(){
$('#dataForm').on('submit', function(e) {
e.preventDefault();
SendData();
});
$('#fileSelector').on('change',function(ev){
fileVar = null;
fileVar = new FormData();
$.each(ev.target.files, function(key, value)
{
fileVar.append(key, value);
});
});
});
function SendData(){
var formData = new FormData($("#dataForm")[0]);
// should i add the filerVar like this ?
// formData.append("Image", fileVar);
$.ajax({
type: "POST",
url: "checkinput.php",//you need to add this '?files part' to URL
data: formData,// use fileVar here now
cache: false,
processData: false,
// contentType: false,
success:function(data)
{
console.log(data);
console.log("success");
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log("failure");
}
});
}
php
print_r($_POST);
print_r($_FILES);
my intention is to send input(file) and input(text) in one ajax , i can get the input file value if i add ajax data with fileVar , but i cant get my input text value i have no idea why , can anyone tell me what i did wrong ?
var formData = new FormData($("#dataForm")[0]) is the way to get both to one ajax but i cant get any input text value.
anyone can teach me how to make this work ?
I think you need to specify input name attributes:
<body>
<form method="post" action="" id="dataForm" enctype="multipart/form-data">
<input type="text" id="textSelector" name="textSelector"/>
<input type="file" id="fileSelector" name="fileSelector"/>
<button name="sub-comfirm" class="btn-selection-content" type="submit" id="sub-comfirm">Send</button>
</form>
</body>
Hope that helps.

AJAX POST Form using return false still refreshes

I can't seem to see the issue here, this AJAX request should be pulling results from sx.php and displaying within the success, although it keeps submitting to itself???
s.php
<script type="text/javascript">
$(document).ready(function(){
$(".button").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "sx.php",
data: $(this).closest("form").serialize(),
cache: false,
success: function(data){
$('#status').html(data);
}
});
return false;
});
});
</script>
<form>
<input type="hidden" name="mid" value="<?php echo htmlspecialchars($result['id']); ?>" />
<h5><?php echo htmlspecialchars($result['title']); ?></h5>
<input type="submit" class="button" value="Go" />
</form>
Im going crazy here...!
Don't trigger the click of the button, but call the from submit event:
$('form').submit(function(){
return false
})

Sending AJAX request before submitting the form

Problem: I'm trying to send ajax reguest, and then submit the form.
Aproaches:
1. I solved the problem by putting
success: function() {
document.myform.submit();
}
But i think it's not the most elegant solution. Can you explain me why it works only if i put document.myform.submit(); in success? Is there any other way to solve this problem?
<div class="buttons">
<div class="right">
<form name="myform" onsubmit="javascript: startAjax(); return false;" action="https://example.com/payment.php" method="get">
<input type="hidden" name="merchantId" value="<?php echo $merchantIdKZM; ?>">
<input type="submit" value="<?php echo $button_confirm; ?>" id="button-confirm2" class="button" name="PayKZM" />
</form>
</div>
</div>
<script type="text/javascript">
function startAjax() {
console.log("dafaaaa");
$.ajax({
type: 'get',
url: 'index.php?route=payment/bank_transfer/confirm',
async: 'false',
success: function() {
// location = '<?php echo $continue; ?>';
}
});
} // Calls ajaxComplete() when finished
function ajaxComplete()
{
console.log("dafa");
document.myform.submit();
}
</script>
success's function is called upon the get request receiving a valid response as #harsh pointed out. Thus it will occur after the get request. I believe something similar to the following would do as you request though I haven't tested it:
<script type="text/javascript">
$(function () {
$("#form").on('submit', function () {
var $form = $(this);
$.ajax({
type: 'GET',
url: 'index.php?route=payment/bank_transfer/confirm',
data: $form.serialize(),
async: 'false',
success: function () {
$.ajax({
type: 'GET',
url: 'https://example.com/payment.php',
data: $form.serialize(),
});
}
});
});
});
</script>

Resources