I've issues in my code, I need send an image with ajax, but when I'd in my code, doesn't work.
I'll need use forms for validated my servlets.
<script type="text/javascript">
function UploadFile() {
fileData = document.getElementById("filePicker").files[0];
var data = new FormData();
var url = 'localhost';
console.log(url);
alert(url);
$.ajax({
url: url,
type: 'POST',
data: fileData,
cache: false,
crossDomain: true,
dataType: 'json',
processData: false,
contentType: false,
success: function (data) {
alert('successful..');
},
error: function (data) {
alert('Ocorreu um erro!');
}
});
alert("Finalizou");
}
</script>
<body>
<form>
<input type="file" id="filePicker" value="" />
<button id="btnUpload" onclick="UploadFile()">Upload</button>
</form>
</body>
If I'd remove the form like that.
<body>
<input type="file" id="filePicker" value="" />
<button id="btnUpload" onclick="UploadFile()">Upload</button>
</body>
It's works.
A button element will be of type submit as default, so it will submit the form and reload the page.
You have to prevent that, something like this
<form>
<input type="file" id="filePicker" value="" />
<button id="btnUpload" onclick="UploadFile(); return false;">Upload</button>
</form>
but as you're using jQuery, you should remove the inline javascript and use proper event handlers
$(function() {
$('#btnUpload').closest('form').on('submit', function(e) {
e.preventDefault();
UploadFile();
});
});
Related
Previously I have some code like this to send a message to the user
<button class="notif btn btn-success"
href="https://api.telegram.org/bot{{ config('app.token') }}/sendMessage?chat_id={{ $rp->report_idsender }}&text=Halo%20{{ $rp->sender_name }}%20permintaan%20anda%20dengan%20id%20{{ $rp->id }}%20sudah%20di%20close%20">Notif</button>
and I am using jquery & js to get URL from href and execute HTTPS post request it works perfectly for me
<script type="text/javascript">
$(".notif").unbind().click(function() {
var url = $(this).attr("href");
console.log(url);
var exe = $.post(url, function() {
alert('Success');
})
});
</script>
But now I want to send a photo to a group on Telegram with reply id and the codes looks like this:
<form method="POST"
action="https://api.telegram.org/bot{{ config('app.token') }}/sendPhoto" enctype="multipart/form-data">
<input type="text" name="chat_id" value="{{ config('app.idgroup') }}" hidden />
<input type="text" name="reply_to_message_id" value="{{ $rp->msg_id }}" hidden />
<input type="text" name="allow_sending_without_reply" value="true" hidden />
<br />
<label for="caption"> Caption</label>
<input type="text" name="caption" placeholder="caption" />
<br />
<input type="file" name="photo" />
<br />
<input type="submit" value="sendPhoto" />
</form>
The problem with this code is that after I submit the form it's opening a page that contains the JSON response whereas I just want to alert it as I did in the previous code.
json response tab picture
The question is, how can I send a photo with the form with telegram bot using js/jquery with reply id in the URL ??
Your code is working fine, but redirecting to page as set in action, you can use following code to prevent default submit button behavior and ajax to stay on the same page and display success message.
<script type="text/javascript">
$(document).on("submit", "form", function (event) {
event.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: $(this).attr("method"),
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status) {
alert('Success');
},
error: function (xhr, desc, err) {
alert('Error');
}
});
});
</script>
Add this code on head section of your page.
I need to pass a single value from my form to my php in the same page. It´s probably not an option to create another .php file and take the code there since there´s a lot going on.
This is the part of the code I need to fix, currently it only works when the code is on another file, since the $_POST is not messing around with other parts of the code. Specifically I need to manage to pass the 'client' or the 'empre' from the form alone to the php.
HTML
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js">
</script>
<script type="text/javascript" >
$(function() {
if($(".cliente").click(function() {
var name = $("#client").val();
var dataString = 'client='+ name;
}))else if($(".empresa").click(function() {
var name = $("#empre").val();
var dataString = 'empre='+ name;
}));
$.ajax({
type: "POST",
data: dataString});
});
</script>
</head>
<body>
<form>
<input name="client" type="text"><br>
<input class="cliente" type="submit" value="Buscar cliente"/><br>
<input name="empre" type="text"><br>
<input class="empresa" type="submit" value="Buscar empresa"/><br>
</form>
//PHP HERE
//HTML AGAIN
</body>
</html>
PHP (same page, just separating for readability)
if(isset($_POST['empre'])){
//DB QUERY
}
elseif(isset($_POST['client'])){
//DB QUERY
}
You can combine and send it in same AJAX call as below, and in PHP you can do:
$parameters = json_decode($_POST['params']);
$parameters would have all the variables sent in that AJAX call.
I would recommend, not to use same page for your AJAX. You should keep it in separate file. That would make code much cleaner, lighter, readable and easy-to-tweak.
$(function() {
$(".cliente, .empresa").click(function(e) {
e.preventDefault();
var paramsToSend = {};
if ($(this).hasClass('client'))
paramsToSend['client'] = $('form[name="client"]').serialize();
else
paramsToSend['empre'] = $('form[name="client"]').serialize()
$.ajax({
url: 'index.php' //assuming this is index.php (same page)
type: "POST",
data: {
params: JSON.stringify(paramsToSend)
},
success: function(data) {},
failure: function(error) {}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="client">
<input name="client" type="text" value="some value"><br>
<input class="cliente" type="submit" value="Buscar cliente" />
</form>
<form name="empre">
<input name="empre" type="text" value="some value"><br>
<input class="empresa" type="submit" value="Buscar empresa" />
</form>
//PHP HERE //HTML AGAIN
Why not use separate forms to process the data? (Your PHP logic mentioned will work with this proposed solution)
$(function() {
$(".cliente").click(function(e) {
e.preventDefault();
alert('Going to post data for client, check the console log now');
$.ajax({
url: $('form[name="client"]').attr('action'),
type: "POST",
data: $('form[name="client"]').serialize(),
success: function(data){
console.log(data);
},
failure: function(error){}
});
});
$(".empresa").click(function(e) {
e.preventDefault();
alert('Going to post data for empre, check the console log now');
$.ajax({
url: $('form[name="empre"]').attr('action'),
type: "POST",
data: $('form[name="empre"]').serialize(),
success: function(data){
console.log(data);
},
failure: function(error){}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form name="client" action="https://someurl.com/fileto.php">
<input name="client" type="text" value="some value"><br>
<input class="cliente" type="submit" value="Buscar cliente"/>
</form>
<form name="empre" action="https://someurl.com/fileto.php">
<input name="empre" type="text" value="some value"><br>
<input class="empresa" type="submit" value="Buscar empresa"/>
</form>
Current code:
index.html
<script type="text/javascript">
$('#username').blur(function(){
$.ajax({
type: "POST",
url: "search.php",
data: {text:$(this).val()}
});
});
</script>
<form id="search" action="search.php" method="post">
<input type="text" id="username" name="username" size="30" placeholder="username ..." />
<input type="submit" id="submit-button" name="sa" value="search" />
</form>
search.php
<?php
echo $_POST['username'];
?>
If I press the submit button it works well but I want to send the value from the field once I focuse out of the field, without pressing the submit button.
You can try focusout.
$('#usernamecopy').focusout(function(){
$.ajax({
type: "POST",
url: "search.php",
data: {username :$('#username').val()}
});
});
In php file you can use:
$user= $_REQUEST['username'];
Not tested but I think if you change data: {text:$(this).val()} to data: {text:$("#usernamecopy").val()}; it will work because when you put this inside the data; the this refers to the data instead of #usernamecopy . By the way, I hope you are not mistaking #usernamecopy with #username
**Use following code in JavaScript :**
<script type="text/javascript">
$('#username').blur(function(){
var value = $("#username").val();
$.ajax({
type: "POST",
url: "search.php",
data: "username="+value,
success: function(data){
}
});
});
</script>
ok so i know this ajax works, but i cant seem to understand why it's not submitting here.
<script type="text/javascript">
$(function(){
$('input[type=submit]').click(function(){
$.ajax({
type: "POST",
url: "postitem.php",
data: $("#myform").serialize(),
beforeSend: function(){
$('#result').html('<img src="loading.gif" />');
},
success: function(data){
$('#result').html(data);
}
});
});
});
submit form
<form action="" method="post" onsubmit="return false;" id="myform">
submit button
<input type="hidden" value="Post" name="submit" />
<button type="submit" title="Done" style="height:33px; width:50px">
<img src="../../css/images/plus_25.png" />
</button>
i'm pretty something is wrong with the button, but i want to keep the way the button is because alot of my other forms use this same button, thanks if you can explain to me why click this submit button does nothing.
You are selecting an <input> instead of a <button>. I had success by changing your jQuery selector from this:
$('input[type=submit]')
to this:
$('button[type=submit]')
http://jsfiddle.net/H3Bcc/
Not all browsers interpret a click attached to a submit button as submitting the form so you are effectively just negating the click of that button.
Preventing a form submission should preferably be captured by attaching the submit handler to the <form> when you have a <input type="submit"> or <button type="submit> so this is the best way to assure success:
jQuery
$(function(){
$('#myform').on('submit', function(e){
// prevent native form submission here
e.preventDefault();
// now do whatever you want here
$.ajax({
type: $(this).attr('method'), // <-- get method of form
url: $(this).attr('action'), // <-- get action of form
data: $(this).serialize(), // <-- serialize all fields into a string that is ready to be posted to your PHP file
beforeSend: function(){
$('#result').html('<img src="loading.gif" />');
},
success: function(data){
$('#result').html(data);
}
});
});
});
HTML
<form action="postitem.php" method="POST" id="myform">
<input type="hidden" value="Post" name="submit" />
<button type="submit" title="Done" style="height:33px; width:50px">
<img src="../../css/images/plus_25.png" />
</button>
</form>
try this :
<script type="text/javascript">
$(function(){
$('input[type=submit]').click(function(e){
e.preventDefault(); // prevent the browser's default action of submitting
$.ajax({
type: "POST",
url: "postitem.php",
data: $("#myform").serialize(),
beforeSend: function(){
$('#result').html('<img src="loading.gif" />');
},
success: function(data){
$('#result').html(data);
}
});
});
});
i need to serialize form input to send an Ajax call using jQuery to php script and each time i tried to print out the values of the form it gives empty array .
HTML Form
<form class="form-horizontal" id="generateCompression" method="post">
<fieldset>
<div class="control-group"><label class="control-label">Checkboxes</label>
<div class="controls">
<input type="checkbox" name="names[]" value="Jan-2011"> Jan-2013</label>
<input type="checkbox" name="names[]" value="Jan-2012"> Jan-2013</label>
<input type="checkbox" name="names[]" value="Jan-2013"> Jan-2013</label>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">Generate</button>
<button type="reset" class="btn">Cancel</button>
</div>
</fieldset>
</form>
Javascript
$(document).ready(function(){
$("#result").hide();
$("#generateCompression").submit(function(){
$.ajax({
url: "compare-action.php",
type: "POST",
data: $("#generateCompression").serialize(),
async: true,
beforeSend : function (){
$("#loading").show();
$("#reportFilecreate").fadeOut();
},
success: function(response) {
$("#loading").hide();
$("#error").show();
$("#error").html(response);
}
});
return false;
});
});
this is the PHP file
<?php
$inputs = $_POST;
print_r($inputs);
?>
Checkboxes do not send anything to the server if at least one checkbox is not checked.
Your script needs to check for the existence of your form field, if the formfield doesnt exist then you know nothing has been checked.
To test simply add a text box to your form and then run your script again.
Try this.
Send serialized data in one variable like
$.ajax({
url: "compare-action.php",
type: "POST",
traditional: true,
data: {
"test_data" : $("#generateCompression").serialize()
},
async: true,
beforeSend : function (){
$("#loading").show();
$("#reportFilecreate").fadeOut();
},
success: function(response) {
$("#loading").hide();
$("#error").show();
$("#error").html(response);
}
});
And in the compare-action.php file
print_r($_POST("test_data"));