AJAX not sending data - javascript

I am using the following code to get data from an input field and send it to PHP by POST but its not working
<script type="text/javascript">
$(document).ready(function () {
$("#id_1").change(function () {
var rat1 = $(this).val();
$.ajax({
url: "upload.php",
type: "post",
data: rat1,
success: function (response) {
// you will get response from your php page (what you echo or print)
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
});
</script>
this is the input form
<input type="number" name="your_awesome_parameter" id="id_1" class="rating" data-clearable="remove"
data-icon-lib="fa" data-active-icon="fa-heart" data-inactive-icon="fa-heart-o"
data-clearable-icon="fa-trash-o"/>

You need to provide a name for the parameter. It should be:
data: { param_name: rat1 }
Then in upload.php you access it with $_POST['param_name']

Just in case, did you imported Jquery into your project?
I tested your code and I with the minor change that Barmar specified and it is working for me.
Try to use this code in your php file and see if you get any response in the developer tools console.
$data = $_POST["param_name"];
echo json_encode([$data]);

Try in this way men
function realizaProceso(valorCaja1, valorCaja2){
var parametros = {
"valorCaja1" : valorCaja1,
"valorCaja2" : valorCaja2
};
$.ajax({
data: parametros,
url: 'ejemplo_ajax_proceso.php',
type: 'post',
beforeSend: function () {
$("#resultado").html("Procesando, espere por favor...");
},
success: function (response) {
$("#resultado").html(response);
}
});
}

change on input type number is not working in older versions of browsers, I think not sure. But try this below solution as you are using input type number.
$("#id_1").on("mouseup keyup",function () {
//your logic here
});
and passing data as already mentioned by others:
data: { param_name: rat1 }

Related

Ajax select list

I want to retrive the result of this kind of data list with CakePHP 3
<?= $this->Form->select('notif_message',
[ 'oui' => 'oui', 'non' => 'non'], array('id' => 'notifmess')); ?>
<?= $this->Form->hidden('notifmessage', ['value' => $notif_message]) ;?>
The goal is when a user chosse a value, an Ajax call to this controller be done
public function notifmessage() // mise à jour des paramètres de notifications 0 = non, 1 = oui
{
if ($this->request->is('ajax')) {
$notifmessage = $this->request->data('notifmessage');
if($notifmessage == 'oui')
{
$new_notif_message = 'non';
}
else
{
$new_notif_message = 'oui';
}
$query = $this->Settings->query()
->update()
->set(['notif_message' => $new_notif_message])
->where(['user_id' => $this->Auth->user('username') ])
->execute();
$this->response->body($new_notif_message);
return $this->response;
}
}
And i would like to do this call in Ajax without reloading , i have this script
<script type="text/javascript">
$(document).ready(function() {
$('.notif_message').change(function(){
$.ajax({
type: 'POST',
url: '/settings-notif_message',
data: 'select.notif_message' + val,
success: function(data) {
alert('ok');
},
error: function(data) {
alert('fail');
}
});
});
});
</script>
he doesn't work, nothing happend but i don't know why, i don't have any message in log, i can't debug without indication what doesn't not work
Thanks
In yout javascript you should use $('#notifmess').change(… or $('[notif_message]').change(… instead of $('.notif_message').change(….
In CakePHP the first argument of the select method will be used as the name attribute of the select tag.
Update:
In your controller you are retrieving the value of $_POST['notifmessage'], which is the name of the hidden input field.
To get the user's choice you either should use $this->request->data('notif_message'); in the controller, or setting up the ajax request to send the data with notifmessage like so:
$('[name="notif_message"]').change(function(){
$.ajax({
type: 'POST',
url: '/settings-notif_message',
data: {'notifmessage' : this.value},
success: function(data) {
// To change selected value to the one got from the server
$('#notifmess').val(data);
alert('ok');
},
error: function(data) {
alert('fail');
}
});
});
(Where in this case this is referring to <select> tag.)
i'm close to success: my ajax call is working, database update is working , i juste need to put the 'selected' to the other , i'm trying with this jquery code
<script type="text/javascript">
$(document).ready(function() {
$('#notifmess').change(function(){
var id = $('#notifmess').val();
$.ajax({
type: 'POST',
url: '/instatux/settings-notif_message',
data: {'id' : id},
success: function(data){
$('#notifmess option[value="'+data.id+'"]').prop('selected', true);
},
error: function(data)
{
alert('fail');
}
});
});
});

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.

How to post webform with file to webmethod using Jquery/Ajax?

Is this even possible? I have a webform with certain textboxes etc and a file upload element. I am trying to send the data to webmethod using .ajax() method.
It seems to me that it is not possible to send file content to the webmethod in this manner. I am not even able to hit the webmethod.
script type="text/javascript">
var btn;
var span;
$(document).ready(function (e) {
$('#btnsave').on('click', function (event) {
Submit();
event.preventDefault();
});
})
function Submit() {
$.ajax({
type: "POST",
url: "SupplierMst.aspx/RegisterSupplier",
data: "{'file' : " + btoa(document.getElementById("myFile").value) + ",'biddername':" + document.getElementById("txtsuppliername").value + "}",
async: true,
contentType: "application/json; charset=utf-8",
success: function (data, status) {
console.log("CallWM");
alert(data.d);
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
}
});
}
</script>
HTML:
<input id="txtsuppliername" type="text" /><br />
<input type="file" id="myFile">
Code behind :
[WebMethod]
public static string RegisterSupplier(string file, string biddername)
{
// break point not hit
return "a";
}
I have been trying to find solution to this for hours now. Nobody seems to be able help me out on this. Is this even possible using this approch. If not how do I do it? Somebody suggested that I should try to submit entire form instead of passing individual values.
This can be done without any library, by using the JavaScript FileReader API. With it, modern browsers can read the content of the file using JavaScript once it has been selected by the user, and then you could proceed as you were doing (encoding it as a string, and sending it over to the server).
The code would be like this (using the one above as a reference):
// NEW CODE
// set up the FileReader and the variable that will hold the file's content
var reader = new FileReader();
var fileContent = "";
// when the file is passed to the FileReader, store its content in a variable
reader.onload = function(e) {
fileContent = reader.result;
// for testing purposes, show content of the file on console
console.log("The file content is: " + fileContent);
}
// Read the content of the file each time that the user selects one
document.getElementById("myFile").addEventListener("change", function(e) {
var selectedFile = document.getElementById('myFile').files[0];
reader.readAsText(selectedFile);
})
// END NEW CODE
var btn;
var span;
$(document).ready(function (e) {
$('#btnsave').on('click', function (event) {
Submit();
event.preventDefault();
});
})
function Submit() {
$.ajax({
type: "POST",
url: "SupplierMst.aspx/RegisterSupplier",
// changed this line too!
data: {
'file': btoa(fileContent),
'biddername': document.getElementById("txtsuppliername").value
},
async: true,
contentType: "application/json; charset=utf-8",
success: function (data, status) {
console.log("CallWM");
alert(data.d);
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="txtsuppliername" type="text" /><br />
<input type="file" id="myFile">
You can run the code above, select a file (use a plain text file for testing so it's readable), and check the console to see its content. Then the rest of the code would be the same (I made a slight change to fix the parameters in the AJAX call).
Notice that sending the file like this has limits: if you use the GET method, you'll have a shorter parameter size limit, and with POST it will depend on the server settings... but I guess that you had those limits even for a file.
First of all go to App_Start>>RouteConfig.cs>>settings.AutoRedirectMode = RedirectMode.Off; and then Just Replace your function by my code it will definitely work for you,
Good Luck..
function Submit() {
$.ajax({
type: "POST",
url: "UploadImage.aspx/RegisterSupplier",
data: "{'file' : " + JSON.stringify(document.getElementById("myFile").value) + ",'biddername':" + JSON.stringify(document.getElementById("txtsuppliername").value) + "}",
async: true,
contentType: "application/json; charset=utf-8",
success: function (data, status) {
console.log("CallWM");
alert(data.d);
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
}
});

Uncaught SyntaxError: Unexpected token }

I have the following script, which returns me the following error in my console:
Uncaught SyntaxError: Unexpected token }..
The } in between ** is the one causing the problem according to my console. But that's the bracket which closes the 'success' of the AJAX request.. And also if i remove the statement pointed out with the -> the error seems to disappear. Does someone see what is wrong about this?
Note: I don't have those ** in my code, that's just for pointing out the error.
$(document).ready(function() {
$('#edit_patient_info').click(function () {
//Get the data from all the fields
$.ajax({
url: "patient_info_controller.php",
type: "POST",
data: data,
success: function (msg) {
if (msg==1) {
getPersoonlijkGegevens(user_id);
unLockFirstPage();
alert("Gegevens zijn gewijzigd!");
$("#searchbox").val(voornaam.val());
searchPatient();
-> $('#selectable li:first').addClass('ui-selected');​
}
**}**
});
});
});
You had a hidden character after $('#selectable li:first').addClass('ui-selected');
That invalidated your code. Usually, these can be seen when you copy your code to notepad (Or notepad++).
In notepad++, it displayed .addClass('ui-selected');?
Also, you had a extra }.
Try this:
$(document).ready(function() {
$('#edit_patient_info').click(function () {
//Get the data from all the fields
$.ajax({
url: "patient_info_controller.php",
type: "POST",
data: data,
success: function (msg) {
if (msg==1) {
getPersoonlijkGegevens(user_id);
unLockFirstPage();
alert("Gegevens zijn gewijzigd!");
$("#searchbox").val(voornaam.val());
searchPatient();
$('#selectable li:first').addClass('ui-selected');
}
}
});
});
});
From what I can tell it's actually the } two lines down from the one you've marked that's causing the issues; it doesn't match up with any of the opening { characters.
You had an extra }
$(document).ready(function() {
$('#edit_patient_info').click(function() {
//Get the data from all the fields
$.ajax({
url: "patient_info_controller.php",
type: "POST",
data: data,
success: function(msg) {
if (msg == 1) {
getPersoonlijkGegevens(user_id);
unLockFirstPage();
alert("Gegevens zijn gewijzigd!");
$("#searchbox").val(voornaam.val());
}
}
});
});
});​

How to Use $.ajax? when I use Its not hitting my controller Action

Can any body help me out.
I have this code
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
function GOTO() {
var datastring = "id=2";
$.ajax({
type: "POST",
url: "/Home/Index",
dataType: "json",
data: datastring,
success: function (json) { Complete(json.result); },
error: function (request, status, error) {
//alert("an error occurred: " + error);
alert("Error saving data. Please contact support.");
}
});
}
function Complete(result) {
if (result == "success") {
alert("Success");
}
else {
alert("Failed");
}
}
</script>
<input type="button" value="submit" onclick="JavaScript:GOTO()" />
</asp:Content>
and My Controller Code is this
[HttpPost]
public System.Web.Mvc.JsonResult Index(string datastring)
{
return Json(new { foo = "bar", baz = "Blech" });
}
But it never hits my controller at all, is that Something I am doing wrong in my View?
thanks
Try passing the data like this:
$.ajax({
type: "POST",
url: "/Home/Index",
dataType: "json",
data: { datastring: 'foo bar' },
success: function (json) { Complete(json.result); },
error: function (request, status, error) {
alert("Error saving data. Please contact support.");
}
});
function Complete(result) {
if (result == "success") {
altert("Success");
// ^ beware!
You have a syntax error in your code.
Moreover, you don't need to specify the JavaScript: protocol in the onclick attribute, you're merely defining a label at that place. Even better, don't assign event listeners in HTML attributes at all, but use unobtrusive JavaScript, including a fallback for the rare case when JavaScript is unavailable.
Update: if you get the "$.ajax is undefined" error, you probably didn't include jQuery in your page. Add
<script type="text/javascript" src="path/to/jquery-X.X.X.js"></script>
To your page above the script element that uses $.ajax (or any other jQuery function).
it could be down to what data you are passing in. Your method expects a parameter called datastring but you are passing in 'id=2'.

Categories