Display file upload message success or failure in reactjs - javascript

I am using Ajax call for upload file in server. So I want to show success & failure message as per file upload
$.ajax({
url: "https:my_url",
data: {my data: my_data},
method : "POST",
success: function(result) {
alert(result);
},
error: function(error){
alert("Error in File Upload");
}
});
And using this in react component
<input id="file-input" type="file" className="fileInput" onChange=
{this.myfile} multiple />
So help me out for print message as bootstrap or any good way i.e.
need to be as below
<div class="alert alert-success">
<strong>Success!</strong> You should <a href="#" class="alert-
link">File uploaded </a>.
</div>

Have a CSS class invisible like this
.invisible{
display:none;
}
And then have a state variable uploaded with initial value anything say uploading
this.state = {uploaded:'uploading'}
Then create the two alert messages
<div className=`alert alert-success ${this.state.uploading === 'success'?'':'invisible'}`>
<strong>Success!</strong> You should <a href="#" class="alert-
link">File uploaded </a>.
<div className=`alert alert-danger ${this.state.uploading === 'failure'?'':'invisible'}`>
<strong>Failure!</strong> Failed <a href="#" class="alert-
link">File uploaded </a>.
</div>
What is happening here is that the success message only gets displayed when this.state.uploading is equal to 'success' and the failure message when it is equal to 'failure'.
And then in the ajax call
$.ajax({
url: "https:my_url",
data: {my data: my_data},
method : "POST",
success: (result) => {
this.setState({uploading:'success'})
},
error: (error) => {
this.setState({uploading:'failure'})
}
});
The ajax call sets the this.state.uploading to success or failure depending on the result of the ajax call and the appropriate message is displayed.
For ES5 style
var _this = this
$.ajax({
url: "https:my_url",
data: {my data: my_data},
method : "POST",
success: function (result) {
_this.setState({uploading:'success'})
},
error: function (error) {
_this.setState({uploading:'failure'})
}
});

Related

Error Using Ajax when I load from a differente file with Django

Im using JaxaScript(Jquery with Ajax) and my HTML Page all in the same file, but when I tried to code my JS and HTML in different files, I get an error when trying to ajax with Django.
JS:
$(document).on('click', '#add-button', function (e) {
e.preventDefault();
value = $(this).data("forloopcounter");
value = value - 1
let variation_id = document.getElementsByClassName("select-variations")[value].attributes[2].nodeValue
console.log(variation_id)
$.ajax({
type: "POST",
url: '{% url "cart:add" %}',
data: {
variationid: variation_id,
productquantity: 1,
csrfmiddlewaretoken: "{{csrf_token}}",
action: 'post'
},
success: function (json) {
document.getElementById("cart-quantity").innerHTML = json.quantity
},
error: function (xhr, errmsg, err) {
console.log(xhr)
}
});
})
Note: I have a guess it's because of this url: '{% url "cart:add" %}', but I don't know how to fix.
Note: when I ajax with all in the same page it works.
Note it's not an importation error, when i execute console.log it
works
Error I get in the web:
`jquery.min.js:4 POST http://127.0.0.1:8000/%7B%%20url%20%22cart:add%22%20%%7D 404 (Not Found)
HTML:
{% for variation in product.variation_set.all%}
{%if forloop.first%}
<!--pra fazer ajax passando id da variação selecionado(não aparece pra usuário)-->
<small id="select-variations1" class="small select-variations"
value="{{variation.id}}"></small>
{%endif%}
{%endfor%}`

POST variable error

Good day, i need past variable in post to other file
}
$.ajax({
url: 'emps.php',
type: 'POST', // GET or POST
data: {"sucursal":$("#suc").val()},
success: function(data) { // data is the response from your php script
// This function is called if your AJAX query was successful
alert(data);
},
error: function() {
// This callback is called if your AJAX query has failed
alert("Errors!");
}
});
}
code variable
<tr>
<td class="col1"><label for="pat">Sucursal:</label></td>
<td class="col2">
<input type="text" name="suc" id="suc" class="medium" readonly="true" style="width: 200px;"size="40" maxlength="200" onChange="javascript:this.value=this.value.toUpperCase();" />
<input type="button" class="btn btn-success btn-sm" id="sbm" name="sbm" value="Buscar" onclick="llenaSucursales()" />
</td>
</tr>
Error image is :
whats its a problem?
I await your help and I started reading and search and can not find the error
You should have a look at the jQuery documentation for $.ajax() to understand what you may use to react on errors in your AJAX call:
$.ajax({
url: 'emps.php',
type: 'POST', // GET or POST
data: {"sucursal":$("#suc").val()},
success: function(data) { // data is the response from your php script
// This function is called if your AJAX query was successful
alert(data);
},
error: function(jqXHR, status, errorThrown) {
// This callback is called if your AJAX query has failed
alert('Got the error ' + errorThrown + ' with status ' +status);
}
});
I would also recommend to open up the Developer Tools (F12 in most browsers) and check the "Network tab" to see the responses of AJAX calls.
Not related to your question:
In the future please take more care when writing your post. Remove unnecessary blank lines, don't post code with errors (just concentrate on the important parts of what you post) - thanks.
The error was that I was missing "/" the address of the file, Thanks, then I leave the code
function empleados(){
if($("#suc").val()=='')
{
alert('Elige una sucursal');
return false;
}
$.ajax({
url: '/emps.php',
type: 'POST', // GET or POST
data: {"suc":$("#suc").val()},
success: function(data) { // data is the response from your php script
// This function is called if your AJAX query was successful
alert(data);
},
error: function() {
// This callback is called if your AJAX query has failed
alert("Errors!");
}
});
}

Show response from ajax error function in django template

A part of the django view which is executed is as follows:
def traxio_advice(request):
.......
.......
elif calculation['statusCode'] == 400:
response = JsonResponse({'message': 'The calculation is not available! Please try another mileage.'}, status=500)
return response
And in django template I have ajax call as follows :
$.ajax({
type: 'POST',
url: '{% url 'traxio_advice' %}',
data: {
firstname: $('input[name=firstname]').val(),
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success: function (data) {
......
},
error: function (data) {
var message = $.parseJSON(data.responseText).message;
$('#calculation-error').removeClass('hidden').html(message)
},
beforeSend: function () {
$('#result-content').html('<div class="loader"></div>');
}
})
The problem is in the error function. I get what I want, thus, the data is correct.
message = "The calculation is not available! Please try another mileage."
But the message isn't showing in the div with the id calculation-error.
Instead I see the loader from the beforeSend function on the screen and in the console I get
POST http://127.0.0.1:8000/master/traxio_advice/ 400 (Bad Request)
What am I missing?
Just for the info, If anyone else would have a similar problem.
Actually the problem was in the beforeSend function and the template .
The div with id #calculation-error (where I wanted to show the error) was inside the div with id #result-content.
But in the beforeSend function I replaced the content of the div with the id #result-content.
Thus in the template like this :
<div id="result-content">
<div class="loader"></div>
</div>
I tried to show error in the div with the id #calculation-error. It couldn't be shown because that div doesn't exist.

Laravel & Ajax - Insert data into table without refreshing

First of all, I have to say that I'm beginner with using Ajax... So help me guys.
I want to insert the data into db without refreshing the page. So far, I have following code...
In blade I have a form with an id:
{!! Form::open(['url' => 'addFavorites', 'id' => 'ajax']) !!}
<img align="right" src="{{ asset('/img/icon_add_fav.png')}}">
<input type="hidden" name = "idUser" id="idUser" value="{{Auth::user()->id}}">
<input type="hidden" name = "idArticle" id="idArticle" value="{{$docinfo['attrs']['sid']}}">
<input type="submit" id="test" value="Ok">
{!! Form::close() !!}
And in controller I have:
public function addFavorites()
{
$idUser = Input::get('idUser');
$idArticle = Input::get('idArticle');
$favorite = new Favorite;
$favorite->idUser = $idUser;
$favorite->idArticle = $idArticle;
$favorite->save();
if ($favorite) {
return response()->json([
'status' => 'success',
'idUser' => $idUser,
'idArticle' => $idArticle]);
} else {
return response()->json([
'status' => 'error']);
}
}
I'm trying with ajax to insert into database:
$('#ajax').submit(function(event){
event.preventDefault();
$.ajax({
type:"post",
url:"{{ url('addFavorites') }}",
dataType="json",
data:$('#ajax').serialize(),
success: function(data){
alert("Data Save: " + data);
}
error: function(data){
alert("Error")
}
});
});
Also in my web.php I have a route for adding favorites. But when I submit the form, it returns me JSON response like this: {"status":"success","idUser":"15","idArticle":"343970"}... It actually inserts into the db, but I want the page not to reload. Just to display alert box.
As #sujivasagam says it's performing a regular post action. Try to replace your javascript with this. I also recognized some syntax error but it is corrected here.
$("#ajax").click(function(event) {
event.preventDefault();
$.ajax({
type: "post",
url: "{{ url('addFavorites') }}",
dataType: "json",
data: $('#ajax').serialize(),
success: function(data){
alert("Data Save: " + data);
},
error: function(data){
alert("Error")
}
});
});
You could just replace <input type="submit"> with <button>instead and you'll probably won't be needing event.preventDefault() which prevents the form from posting.
EDIT
Here's an example of getting and posting just with javascript as asked for in comments.
(function() {
// Loads items into html
var pushItemsToList = function(items) {
var items = [];
$.each(items.data, function(i, item) {
items.push('<li>'+item.title+'</li>');
});
$('#the-ul-id').append(items.join(''));
}
// Fetching items
var fetchItems = function() {
$.ajax({
type: "GET",
url: "/items",
success: function(items) {
pushItemsToList(items);
},
error: function(error) {
alert("Error fetching items: " + error);
}
});
}
// Click event, adding item to favorites
$("#ajax").click(function(event) {
event.preventDefault();
$.ajax({
type: "post",
url: "{{ url('addFavorites') }}",
dataType: "json",
data: $('#ajax').serialize(),
success: function(data){
alert("Data Save: " + data);
},
error: function(data){
alert("Error")
}
});
});
// Load items (or whatever) when DOM's loaded
$(document).ready(function() {
fetchItems();
});
})();
You are using button type "Submit" which usually submit the form. So make that as button and on click of that call the ajax function
Change your button type to type="button" and add onclick action onclick="yourfunction()". and just put ajax inside your funciton.
Replace input type with button and make onClick listener. Make sure you use this input id in onclick listener:
So:
$('#test').on('click', function(event){
event.preventDefault()
... further code
I would also change the id to something clearer.

jQuery Ajax not sending Post data to PHP file

I'm trying to send variables from my JavaScript to a PHP file using AJAX but it's not working. I've looked through all the similar asked questions (there are a bunch) but have yet to find a solution.
This is my first php file (one with the form, sends data to JavaScript):
<option value="imageOne" data-cuteform-image='assets/SketchThumbnails/imageOne.png></option>
<input id="inputURLID" type="text" name="inputURL">
<button type="submit" onclick="handleInputs(document.getElementById('sketch').value, document.getElementById('inputURLID').value); return false;">Submit</button>
JavaScript (where AJAX call is):
var content = {
'sketch': pickedSketch,
'songUrl': enteredURL
};
$.ajax({
type: "POST",
url: "loadSketch.php",
data: content,
success: function (data, text) {
// alert("success");
// console.log(data);
// console.log(text);
window.location.href = "loadSketch.php";
},
error: function (request, status, error) {
alert(request.responseText);
}
});
PHP (loadSketch.php):
if(isset($_POST['songUrl']))
{
$temp = $_POST['songUrl'];
echo $temp;
echo "received AJAX data";
} else {
echo "nothing in post variable";
}
When I get redirected to loadSketch.php (from the successful ajax call), "nothing in post variable" gets echoed out. Any ideas what I'm doing wrong?
Any insight is much appreciated! :)
Nothing is in songURL because when your Ajax function returns it is redirecting to the same page you just posted to. It is creating a new HTTP request to that PHP file with no data sending to it. Remove the comments on the console messages and you'll see the correct echo messages.
$.ajax({
type: "POST",
url: "loadSketch.php",
data: content,
success: function (data, text) {
alert("success");
console.log(data);
},
error: function (request, status, error) {
alert(request.responseText);
}
});
You should not use a submit button because it makes the whole page reload; instead use normal buttons and handle the click events calling your AJAX function.
HTML:
<button onclick="doAjaxFunction(param1, param2);">Calling Ajax Function<button>
JavaScript:
function doAjaxFunction(val1,val2){
$.ajax({
type: "POST",
url: "loadSketch.php",
dataType: "json",
data: {"'value1':'"+ val1+"', 'value2':'"+ val2+"'"},
success: function (data, text) {
// alert("success");
// console.log(data);
// console.log(text);
window.location.href = "loadSketch.php";
},
error: function (request, status, error) {
alert(request.responseText);
}
});
Then just pick your POST parameters in loadSketch.php and use them.
PHP:
$x = $_POST['value1'];
$y = $_POST['value2'];

Categories