jquery: Removing class transferred from JSON response - javascript

I created a function in laravel that raises some pictures together and returns their names, so I can view them immediately on the page without having to refresh the browser. I want to allow deleting a photo, but it does not give that return values ​​through JSON are not in the DOM. What am I doing wrong?
HTML:
<form action="" enctype="multipart/form-data" id="data">
<input type="file" name="image[]" multiple>
<button type="submit">send</button>
</form>
<hr>
<div class="returns_img"> </div>
<script type="text/javascript">
$("form#data").submit(function(event){
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: "upimage",
type: "POST",
data: formData,
async: false,
success: function(msg){
$(".returns_img").append(msg);
},
cache: false,
contentType: false,
processData: false
});
});
$("#dell_msg").click(function(){
$(".up_side").removeClass(".list_img");
});
Routes.php:
Route::post('upimage', function(){
foreach (Input::file("image") as $image) {
$imagename = time(). $image->getClientOriginalName();
$upload = $image->move(public_path() . "/img/",$imagename);
if ($upload) {
$uploaddata [] = $imagename;
}
echo "<div class='list_img'><img src='/img/". $imagename. "'><button id='dell_msg'>X</button> </div>";
}

Related

How to pass an array of "FormData" via ajax and access in Laravel controller

# I just want to know how to send this array the controller by requete ajax
var dataPanier=[];
function addarray(objser)
{
dataPanier.push(objser);
}
$('.target').click(function() {
var btn_name=$(this).attr("name");
switch(btn_name) {
case 'FormPVC':
var dataformPVC = new FormData(),
form_data = $('#'+btn_name).serializeArray();
$.each(form_data, function (key, input) {
dataformPVC.append(input.name, input.value);
});
dataformPVC.append('Fichier', $('#File_PVC')[0].files[0]);
/* function addarray push dataform in array*/
addarray(dataformPVC);
break;
.
.
.
more . . .
I am attempting to send multiple forms data as an array by ajax to a Larave controller.
$.ajax({
type: 'POST',
url: 'lsitedevis',
data: array ,
success: function(data) {
toastr.success('Successfully added Post!', 'Success Alert', {timeOut: 5000});
}
});
$("#btnTest").click(function(){
var formData = $('#frm1, #frm2').serialize();
console.log(formData);
$.ajax({
method: 'POST',
url: 'lsitedevis',
data: formData ,
success: function(data) {
toastr.success('Successfully added Post!', 'Success Alert', {timeOut: 5000});
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="frm1">
<input name="n1" type="text"/>
<input name="n2" type="hidden" value="test2"/>
<input name="n3" type="hidden" value="test3"/>
</form>
<form id="frm2">
<input name="n1" type="text" />
<input name="n2" type="hidden" value="test2"/>
<input name="n3" type="hidden" value="test3"/>
</form>
<input type="button" id="btnTest" value="send"/>
As your already using jQuery for the AJAX request, you could use the serialize() function. This supports multiple form elements, so it is possible to do:
var formData = $('#form1, #form2').serialize();
$.ajax({
type: 'POST',
url: 'lsitedevis',
data: formData ,
success: function(data) {
toastr.success('Successfully added Post!', 'Success Alert', {timeOut: 5000});
}
});
You might want to ask yourself why you have multiple forms but submitting them all as a single request. If it's for visual purposes, it might be easier to have a single form and separate the contents using other markup elements such as a <fieldset> or <div>.

How to find the data-type based on the button clicked using javascript?

I have a PHP function that creates dynamic created division. Each of these divisions have a different data-type and a button. How do I retrieve the data-type of a division when the user clicks on the submit button using Javascript?
PHP CODE:
function html_submit_docs($docname,$datasubmit){
$html .= '<section class="docs">';
$html .=
'<div class="card_doc">
<div class="custome-file" data-type="'.$datasubmit.'">
<div id="label">
Upload Your Document
</div>
<input type="file" />
<button id="upload" value="Upload" />
</div>
</div>';
$html .= '</section>';
return $html;
}
JAVASCRIPT CODE:
$(document).on('click', '#upload', function() {
console.log('button activattion');
var form_data = new FormData();
var doctype = $(this).closest('div').find('data-type').attr('data-type');
console.log(doctype);
jQuery.ajax({
type: 'POST',
url: ajaxobject.ajaxurl,
cache: false,
contentType: false,
processData: false,
data: {
action: 'upload_submit_docs',
testuser: ajaxobject.student_id,
doctype: doctype,
form_data: form_data
},
dataType: 'json',
success: function(response) {
console.log(response);
},
error: function(err) {
console.log('err', err)}
});
})
Since you are using jQuery you can use data():
var doctype = $(this).closest('div').data('type');

Auto submit Form via ajax on selecting image

I have this form to change profile pic of user. I am trying to change the pic on clicking current pic and select from user filesystem
Form:
<form id="changeProfilePicForm" action="<?=base_url()?>user/change_profile_pic" method="post" accept-charset="utf-8" enctype="multipart/form-data">
<div data-content="Click To update" class="image" id="profile-image">
<input id="profile-image-upload" class="hidden" name="image" type="file" accept="image/x-png, image/gif, image/jpeg">
<?if(strlen($user['image'])){?>
<img src="<?=base_url().'uploads/profile/'.$user['image']?>" class="img-circle" alt="user profile pic" height="125px" width="125px">
<?}else{?>
<img src="<?=base_url()?>includes/img/avtar.png" class="img-circle" alt="user profile pic" height="125px" width="125px">
<?}?>
<input type="submit" class="hidden">
</div>
</form>
Javascript:
$("#changeProfilePicForm").on('submit',(function(e){
e.preventDefault();
var $form = $( this );
$.ajax({
url: $form.attr( 'action' ),
type: "POST",
data: new FormData($form),
contentType: false,
cache: false,
processData:false,
success: function(data){
console.log(data);
},
error: function(data){
console.log(data);
}
});
}));
document.getElementById('profile-image').onclick = function() {
document.getElementById('profile-image-upload').click();
};
document.getElementById('profile-image-upload').onchange = function(){
document.getElementById('changeProfilePicForm').submit();
};
PHP controller:
public function change_profile_pic()
{
$user_id = $this->session->user_id;
$image = $this->uploadimage();
if(strlen($image)){
$user_data['image'] = $image;
$updated = $this->user_model->update_user($user_id, $user_data);
$data['response'] = 1;
$data['image'] = $image;
// redirect(base_url()."user");
echo json_encode($data);
}else{
$data['response'] = 0;
$data['message'] = "error";
echo json_encode($data);
}
//redirect(base_url()."user");
}
Problem I am facing is, the form is not submitted via ajax. It is directory submitted as simple form. I can't figure out whats wrong with the code since image is being upload on simple form submission. Is there any problem with event binding or i am missing something here ?
When you call
document.getElementById('changeProfilePicForm').submit();
the submit event is not fired. Try
$('#changeProfilePicForm').trigger('submit');
Edit. Get rid of the form in html:
<input type="file" id="image">
js:
function handleUpload(event) {
var file = this.files[0];
if (!file) return;
var formData = new FormData();
formData.append('file', file);
return $.ajax({
type: 'POST',
url: '/images',
data: formData,
processData: false,
contentType: false,
//...
});
}
$('#image').on('change', handleUpload);
I believe FormData expects a native form element $form[0], not jQuery form element $form.
$("#changeProfilePicForm").submit(function (e) {
e.preventDefault();
var $form = $(this);
$.ajax({
url: $form.attr('action'),
type: "POST",
data: new FormData($form[0]),
contentType: false,
cache: false,
processData: false,
success: function (data) {
console.log(data);
},
error: function(data){
console.log(data);
}
});
}));

Sending data to php file AJAX

So I have a target. It's to have a live area where you type in a username and every time you let a key go onkeyup() in the input area, I want it to send that data to a php file where that file will return what you just typed in and display it out where I want it. This isn't going as I like though :P. Please help, and thanks in advance.
JavaScript/jQuery/Ajax Code
function changeUsername() {
var user = $("#user").val();
$.ajax({
type: "GET",
url: "php/return.php",
data: user,
cache: false,
success: function(data){
$("#username-display").text(data);
}
});
}
HTML Code
<div class="container" title="Press enter to submit">
<label>What is your name: </label><input type="text" name="user" required="" maxlength="200" id="user" onkeyup="changeUsername();" /> <br />
You typed: <strong id="username-display"></strong>
<strong id="msg"></strong>
</div>
PHP Code
<?php
$username_vuln = $_GET["user"];
$username = htmlspecialchars($username_vuln);
echo $username;
?>
Please let me know if you need more info to help me solve this...
hey you can use following code
HTML CODE
<script type="text/javascript">
function changeUsername() {
// var user = $("#user").val();
$.ajax({
type: "GET",
url: "s.php",
data: {'user':$("#user").val()},
success: function(data){
$("#username-display").text(data);
}
});
}
</script>
<div class="container" title="Press enter to submit">
<label>What is your name: </label><input type="text" name="user" required="" maxlength="200" id="user" onkeyup="changeUsername();" /> <br />
You typed: <strong id="username-display"></strong>
<strong id="msg"></strong>
</div>
PHP CODE
<?php
$username_vuln = $_GET["user"];
$username = htmlspecialchars($username_vuln);
echo $_GET["user"];
?>
You need to correct your AJAX code also change type from GET to POST in php code so, final code will be like -
function changeUsername() {
var user = $("#user").val();
$.ajax({
url: "data.php",
data: {'user': user},
type : 'post',
success: function (data) {
$("#username-display").text(data);
}
});
}
PHP CODE :-
$username_vuln = $_POST["user"];
$username = htmlspecialchars($username_vuln);
echo json_encode($username);
Change Get to Post.
function changeUsername() {
var user = $("#user").val();
$.ajax({
type: "POST",
url: "php/return.php",
data: {'user': user},
cache: false,
success: function(data){
alert(data);
$("#username-display").text(data);
}
});
}
Php code first try to get response.
$username_vuln = $_POST["user"];
$username = htmlspecialchars($username_vuln);
echo $username; exit;
Try:
echo( json_encode( $username ) );
exit( 1 );

Adding email into MySQL database with PHP, JQuery, Ajax

My code so far
main.js file:
$('#addButton').on('click', function() {
var email = $('#userInput').val();
$.ajax({
type: "post",
url: 'validation.php',
success: function(html) {
alert(html);
}
});
});
index.html file:
<form method="post">
<input type="text" name="email" placeholder="Your Email" id="userInput"><br>
<button type="submit" name="submit" id="addButton">Add User</button>
</form>
<!-- jQuery first, then Bootstrap JS. -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/js/bootstrap.min.js" integrity="sha384-vZ2WRJMwsjRMW/8U7i6PWi6AlO1L79snBrmgiDpgIWJ82z8eA5lenwvxbMV1PAh7" crossorigin="anonymous"></script>
<script src="main.js"></script>
validation.php file:
<?php
if (array_key_exists("submit", $_POST)) {
$link = mysqli_connect("localhost", "my_username", "my_password", "my_db");
if (mysqli_connect_error()) {
die("Error Connecting To Database");
}
if (validateEmail($_POST['email'])) {
$query = "INSERT INTO `users` (`email`) VALUES ('".mysqli_real_escape_string($link, $_POST['email'])."')";
if (mysqli_query($link, $query)) {
$success = "Email: ".$_POST['email']." added";
} else {
echo "Error in query";
}
}
}
?>
Here is my validate email function:
function validateEmail($email) {
if (!preg_match('/^([a-z0-9\+\_\-\.]+)#([a-z0-9\+\_\-\.]{2,})(\.[a-z]{2,4})$/i', $email)) {
echo "Invalid Email";
return false;
} else {
$domain = array('umich.edu');
list(, $user_domain) = explode('#', $email, 2);
return in_array($user_domain, $domain);
}
}
Am I performing my Ajax request incorrectly because it never adds the email to the database?
Try something this :
$.ajax({
type: 'POST',
// make sure you respect the same origin policy with this url:
url: 'validation.php',
data: {
'email': email
},
success: function(html){
}
});
There is a lot of way to do that, but I think this is the best way and the easiest way for you to make it work base on your current code.
First thing, You don't need to use type="submit" button when using AJAX.
HTML should be,
<form id='emailform'>
<input type="text" name="email" placeholder="Your Email" id="userInput"><br>
<button type="button" name="submit" id="addButton">Add User</button>
</form>
Your JS should be something like this, use jQuery's .serialize() function to your form:
$('#addButton').on('click', function() {
var email = $('#userInput').val();
$.ajax({
type: "post",
url: 'validation.php',
data: $('#emailform').serialize(),
dataType: "html",
success: function(html) {
alert(html);
}
});
});
Try this ;)
$('#addButton').on('click', function(event){
/* prevent default behavior of form submission. */
event.preventDefault();
var email = $('#userInput').val();
$.ajax({
type: "post",
data: {
email: email,
submit: 1
},
url: "validation.php",
success: function(html){
alert(html);
}
});
});
You need to send email and submit because you wrapped all code in if (array_key_exists("submit", $_POST)) { means you are checking if the submit field submitted or not.
You can use below function also in your main.js.
Please remember that whenever you run any post request and if you want to send some data to server you need to mention that variable or json one of the parameter.
$(document).ready(function(){
$("button").click(function(){
$.post("demo_test_post.asp", {email: "hello#hello.com"},
function(data, status){
alert("Data sent!");
});
});
});
Or you can use the below code also for better understanding
$.ajax({
type: 'POST',
// make sure you respect the same origin policy with this url:
url: 'validation.php',
data: {
email: email
},
contentType:'application/json',
success: function(html){
}
});

Categories

Resources