I have created some ajax that uploads an image and loads it into the page.
It creates an images with an X button on the top corner, I am trying to get it so when this button is clicked I then run another peice of php code with will delete the correct image and reload the images.
I cant get my ajax code to pick up the php code and I am not sure why.
Any pointed would be very helpful.
I have found out that dymanically created elemets will not be picked up so had to change my ajax code to
$("body").on("click", "#deleteform button", function(e){
so I am hitting this point but but it sill is not picking up my php code and I dont know why.
Any pointers would be very helpful
AJAX JS:
$(document).ready(function(){
$("#uploadForm").on('submit',function(e) {
e.preventDefault();
$.ajax({
url: "include_advert/advert_new_gun_add_image.inc.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#targetLayer").html(data);
},
error: function()
{
}
});
});
});
$(document).ready(function(){
$('button.deleteimage').on('click', function(){
var image_id = parseInt($(this).parent().attr('id').replace('deleteform', ''));
console.log(image_id); // You can comment out this. Used for debugging.
e.preventDefault();
$.ajax({
url: "include_advert/advert_new_gun_delete_image.php",
type: "POST",
data: {image_id: image_id},
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#targetLayer"+image_id).html(data); // targetLayer is dynamic and is different for each record
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
});
});
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="include_advert/advert_js/advert_gun_load_save_images.js"></script>
<div class="bgColor">
<form id="uploadForm" action="include_advert/advert_new_gun_add_image.inc.php" method="post" class="login-form" enctype="multipart/form-data">
<div id="targetLayer" class=col> </div>
<div id="uploadFormLayer">
<input name="file" type="file" class="inputFile" /><br/>
<div class="text-center">
<input type="submit" name="submit" value="UPLOAD" class="btn btn-common log-btn">
</div>
</form>
advert_new_gun_add_image.inc.php:
<?php
$imagecount = 0;
echo ('<div class=row sm>');
foreach ($getadvertimages as $getadvertimages_row) {
echo ( '<div class="image-area" >
<form id="deleteform'.$getadvertimages_row['image_id'].'" method = "POST" action ="include_advert/advert_new_gun_delete_image.php" >
<img src="'. $getadvertimages_row['image_src'] . '" alt="Preview">
<button onclick = "" name="deleteimage" id="deleteimage" value="'. $getadvertimages_row['image_id'] . '" class="remove-image" style="display: inline;" >X</button>
</form>
</div>');
}
echo ('</div>');
advert_new_gun_delete_image.php:
<?php
if (isset($_POST['deleteimage']) ){
echo('hello');
}?>
I am expecting when I click the button on the image it will run the advert_new_gun_delete_image.php file without reloading the complete page
The Above Answer was almost there but I had to change the $('button.delete-button').on('click', function(){ to $("body").on("click", "#deleteimage", function(e){
And I also removed:contentType: false, cache: false,processData:false,
Thanks Ghulam for the push in the right direction
$(document).ready(function(){
$("body").on("click", "#deleteimage", function(e){
var image_id = parseInt($(this).parent().attr('id').replace('deleteform', ''));
console.log(image_id); // You can comment out this. Used for debugging.
e.preventDefault();
$.ajax({
url: "include_advert/advert_new_gun_delete_image.php",
type: "POST",
data: {image_id: image_id },
success: function(data)
{
$('#imageareadiv').hide();
$("#targetLayer").html(data); // targetLayer is dynamic and is different for each record
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
});
});
$(document).ready(function(){
$('button.delete-button').on('click', function(){
var image_id = parseInt($(this).parent().attr('id').replace('deleteform', ''));
console.log(image_id); // You can comment out this. Used for debugging.
e.preventDefault();
$.ajax({
url: "include_advert/advert_new_gun_delete_image.php",
type: "POST",
data: {image_id: image_id},
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#targetLayer"+image_id).html(data); // targetLayer is dynamic and is different for each record
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
});
});
include 'advert_new_gun_save_image_script.inc.php';
include 'advert_new_dropdown_populate/advert_new_gun_image_populate.php';
$imagecount = 0;
echo ('<div class=row sm>');
foreach ($getadvertimages as $getadvertimages_row) {
echo ( '<div class="image-area" >
<form id="deleteform'.$getadvertimages_row['image_id'].'" method = "POST" action ="include_advert/advert_new_gun_delete_image.php" >
<img src="'. $getadvertimages_row['image_src'] . '" alt="Preview">
<button type="button" name="deleteimage" value="" class="remove-image delete-button" style="display: inline;" >X</button>
</form>
</div>');
}
echo ('</div>');
Similarly you can make "targetLayer" dynamic with image_id value just like I did with form's attribute id deleteform.
$(document).delegate('#deleteform button', 'click', function (e) {
instead of
$("body").on("click", "#deleteform button", function(e){
Related
I'm newby with jquery and have a problem with dealing multiple multipart forms on same page. I'm trying to add some data to mysql via php also uploading mp3 files at same time. Each form uses samename+PHPID. There is no problem with first form but im not getting file data when i use other forms. Can anyone help me?
JS:
$(".msc_send_button").click(function(e) { // changed
var a = this.id; // Button id
var form = $('#'+a).parents('form').attr('id'); // Get buttons parent form id
e.preventDefault();
var formData = new FormData($('#'+form)[0]); // Form Data
$.ajax({
url: '/formposts',
type: 'POST',
cache: false,
contentType: false,
processData: false,
data: formData,
beforeSend: function(){
// change submit button value text
$('#'+a).html('Sending...');
},
success: function(data) {
if(data) {
// Message
$('#info').html(data);
//Button Reset
$('#'+a).html('Send');
}
},
error: function(e){
alert(e);
}
});
return false;
});
PHP Form:
<form name="music-form" id="music-form<?php echo $cont['id']; ?>" enctype="multipart/form-data" novalidate>
<input type="text" name="songno" id="songno" value="<?php echo $cont['song_no']; ?>">
<input type="file" id="mp3" name="mp3" class="inputfile" accept="audio/*" multiple>
<button type="submit" class="msc_send_button" id="msc_send_button<?php echo $cont['id']; ?>">Send</button>
</form>
I think you should change your jquery selector. I didn't see your html codes but you may have created nested forms. Maybe you can use closest('from') instead of parents('form')
$(".msc_send_button").click(function(e) { // changed
var buttonEl = $(this);
var form = buttonEl.closest('form');
e.preventDefault();
var formData = new FormData(form[0]); // Form Data
$.ajax({
url: '/formposts',
type: 'POST',
cache: false,
contentType: false,
processData: false,
data: formData,
beforeSend: function(){
// change submit button value text
buttonEl.html('Sending...');
},
success: function(data) {
if(data) {
// Message
$('#info').html(data);
//Button Reset
buttonEl.html('Send');
}
},
error: function(e){
alert(e);
}
});
return false;
});
Multiple file upload is not working if all files are not the same extension !! If I chose two png files , it works . But choosing two different file extensions (png,pdf) got empty array in $_FILES !
index.php
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js" > </script>
</head>
<body>
<form>
<input name="file[]" type="file" multiple/>
<input type="button" value="Upload" />
</form>
<progress></progress>
<script>
$(':button').on('click', function() {
$.ajax({
// Your server script to process the upload
url: 'upload.php',
type: 'POST',
// Form data
data: new FormData($('form')[0]),
// Tell jQuery not to process data or worry about content-type
// You *must* include these options!
cache: false,
contentType: false,
processData: false,
// Custom XMLHttpRequest
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
// For handling the progress of the upload
myXhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
$('progress').attr({
value: e.loaded,
max: e.total,
});
}
} , false);
}
return myXhr;
},
});
});
</script>
</body>
</html>
upload.php
<?php var_dump($_FILES); ?>
Result image
Hope to help you.
demo.php
<?php
if(isset($_FILES)&&!empty($_FILES)){
for($i=0;$i<count($_FILES);$i++){
echo "File ".($i+1)." is ".$_FILES["file-".$i]['name']."\n";
}
die;
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
// Updated part
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
// Full Ajax request
$(".update").click(function(e) {
// Stops the form from reloading
e.preventDefault();
$.ajax({
url: 'demo.php',
type: 'POST',
contentType:false,
processData: false,
data: function(){
var data = new FormData();
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
return data;
}(),
success: function(result) {
alert(result);
},
error: function(xhr, result, errorThrown){
alert('Request failed.');
}
});
});
});
</script>
</head>
<body>
<form enctype="multipart/form-data" method="post">
<input id="file" name="file[]" type="file" multiple/>
<input class="update" type="submit" />
</form>
<body>
</html>
I think you can use following code :-
<button id="upload">Upload</button>
<script type="text/javascript">
$(document).ready(function (e) {
$('#upload').on('click', function () {
var form_data = new FormData();
var ins = document.getElementById('multiFiles').files.length;
for (var x = 0; x < ins; x++) {
form_data.append("files[]", document.getElementById('multiFiles').files[x]);
}
$.ajax({
url: 'uploads.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response); // display success response from the PHP script
},
error: function (response) {
$('#msg').html(response); // display error response from the PHP script
}
});
});
});
</script>
I am getting Id value from my AJAX and I am also able to display it. I set the Id value input text in the AJAX and displaying it on HTML like this <input value="4864" id="compare_id" type="hidden"> Now I have to pass that value to PHP to get the result from database.
Is there any idea how to do it?
AJAX
$(document).ready(function() {
arr = [];
$("[type=checkbox]").click(function() {
$.ajax({
type: "POST",
url: "includes/compare_process.php", //
data: 'users=' + arr,
dataType: 'json',
success: function(msg) {
$("#pics_name,#pics_Id").empty();
$.each(msg, function() {
$("#pics_Id").append("<input type=hidden value=" + this.Id + " id=compare_id name=compare_id>");
//alert(msg.id);
});
},
error: function() {
alert("failure");
}
});
});
});
//tried AJAX
$(document).ready(function(){
$('#search-button').click(function(){
$.ajax( {
type: "GET",
url: 'includes/compare_process.php?key=compare_details',
data: $('#search-form').serialize(),
success: function(response) {
//$('#response').html(response);
alert(response);
}
} );
});
});
PHP
<div class="bg-popup" style="display: none;" id="open_compare_popup">
//popup code here
<?php
$val2=htmlentities($_GET['compare_id']);
echo $val2;
$sql = "SELECT * FROM `request` WHERE Id IN($val2)";
?>
//end popup code here
This output I am getting from AJAX
<form action="#" method="get" id="search-form">
<span id="pics_Id">
<input value="4869" id="compare_id" name="compare_id" type="hidden">//output
<input value="4884" id="compare_id" name="compare_id" type="hidden">//output
<input value="5010" id="compare_id" name="compare_id" type="hidden">//output
</span>
<button class="action action--button action--compare" type="button" id="search-button" name="search-button"><span class="action__text">Compare</span></button>
</form>
I have to pass the input value to PHP after clicking on a button.
I'm trying to submit a single value as following?
HTML:
<form class="form-horizontal" role="form" method="POST" enctype="multipart/form-data" name="frmanalyse" id="frmanalyse">
{{ csrf_field() }}
<label for="marginsource" style="float: left; width:150px; text-align:left;">Margin Source</label>
<input type="file" name="marginsource" id="marginsource" >
<br />
</form>
script:
<script type="text/javascript">
$( "#frmanalyse" ).submit(function(event) {
$.post( "marginanalyser", {username: "medo ampir"}, function( data ) {
alert(data);
});
event.preventDefault();
});
in laravel routes:
Route::post('marginanalyser',function(Request $request){
echo $request->input('username');
$file = $request->file('marginsource');
echo 'File Name: '.$file->getClientOriginalName();
});
nothing shows in the message at all.
Change your JavaScript to use FormData as you aren't submitting the file
$( "#frmanalyse" ).submit(function(event) {
event.preventDefault();
var formData = new FormData();
formData.append('marginsource', $('#marginsource')[0].files[0]);
formData.append('username', "medo ampir");
$.ajax({
url : window.location.origin + "/marginanalyser",
type: "POST",
data : formData,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
processData: false,
contentType: false,
success:function(data, textStatus, jqXHR) {
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown){
//if fails
}
});
});
Been looking at some tutorials, since I'm not quite sure how this works (which is the reason to why I'm here: my script is not working as it should). Anyway, what I'm trying to do is to insert data into my database using a PHP file called shoutboxform.php BUT since I plan to use it as some sort of a chat/shoutbox, I don't want it to reload the page when it submits the form.
jQuery:
$(document).ready(function() {
$(document).on('submit', 'form#shoutboxform', function () {
$.ajax({
type: 'POST',
url: 'shoutboxform.php',
data: form.serialize(),
dataType:'html',
success: function(data) {alert('yes');},
error: function(data) {
alert('no');
}
});
return false;
});
});
PHP:
<?php
require_once("core/global.php");
if(isset($_POST["subsbox"])) {
$sboxmsg = $kunaiDB->real_escape_string($_POST["shtbox_msg"]);
if(!empty($sboxmsg)) {
$addmsg = $kunaiDB->query("INSERT INTO kunai_shoutbox (poster, message, date) VALUES('".$_SESSION['username']."', '".$sboxmsg."'. '".date('Y-m-d H:i:s')."')");
}
}
And HTML:
<form method="post" id="shoutboxform" action="">
<input type="text" class="as-input" style="width: 100%;margin-bottom:-10px;" id="shbox_field" name="shtbox_msg" placeholder="Insert a message here..." maxlength="155">
<input type="submit" name="subsbox" id="shbox_button" value="Post">
</form>
When I submit anything, it just reloads the page and nothing is added to the database.
Prevent the default submit behavior
$(document).on('submit', 'form#shoutboxform', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'shoutboxform.php',
data: $(this).serialize(),
dataType: 'html',
success: function(data) {
alert('yes');
},
error: function(data) {
alert('no');
}
});
return false;
});
Use the following structure:
$('form#shoutboxform').on('submit', function(e) {
e.preventDefault();
// your ajax
}
Or https://api.jquery.com/submit/ :
$("form#shoutboxform").submit(function(e) {
e.preventDefault();
// your ajax
});