So i have an AJAX function and I want to search every element with particular class, take its value and add it into the AJAX in the right format. Is that possible?
I have this AJAX function:
function sendOrders(button) {
$.ajax({
url: "external_file.php",
method: "POST",
data: {
/*Here I need to add the data*/
GameID: "'.$_SESSION['GameID'].'",
Round: "'.$round.'",
UserID: "'.$_SESSION['UserID'].'",
}
}).done(function( msg ) {
$("#DEBUG").html(msg);
});
};
and I need to collect data from hidden-type inputs on the page with class="order".
I know that I can acces each element by class with jquery, but I have no idea how to add the properties to my AJAX, when it's already written. Number of those elements is variable and they have non-repeating ids, class is the same. Inputs look like this:
<input class="order" type="hidden" name="some_name" id="some_id" value="some_value">
Can anyone help?
From what I understand, you want to make that ajax call with several different values that you get from the inputs with class order?
Assuming you want to just add the value from those fields, you can do something pretty simple:
First, update your ajax function with an additional input variable,
function sendOrders(button, val) {
$.ajax({
url: "external_file.php",
method: "POST",
data: {
value : val,
GameID: "'.$_SESSION['GameID'].'",
Round: "'.$round.'",
UserID: "'.$_SESSION['UserID'].'",
}
}).done(function( msg ) {
$("#DEBUG").html(msg);
});
};
Then, to get data from all of your 'order' class inputs, you can use Jquery's 'each' function. For example, if you want the value from each of those inputs, you can use your new sendOrder function in the each function:
$('.order').each(function(){
sendOrder(buttonId, $(this).val())
});
Not quite sure how you are using 'button' in your ajax function, but I assume it's associated with your save or submit button, so buttonId would be whatever the id is of that button. This will iterate over all inputs with class order and make the ajax call with those values.
If you're using the button as a submit you can probably take it out all together from the ajax function, and have something like this:
function sendOrders(val) {
$.ajax({
url: "external_file.php",
method: "POST",
data: {
value : val,
GameID: "'.$_SESSION['GameID'].'",
Round: "'.$round.'",
UserID: "'.$_SESSION['UserID'].'",
}
}).done(function( msg ) {
$("#DEBUG").html(msg);
});
};
$('#buttonId').click(function(){
$('.order').each(function(){
sendOrder(buttonId, $(this).val())
});
});
Create the data object, loop over all the inputs, and add the values to the object.
function sendOrders(button) {
var data = {
GameID: "'.$_SESSION['GameID'].'",
Round: "'.$round.'",
UserID: "'.$_SESSION['UserID'].'",
};
$(button).closest("form").find("input[type=hidden]").each(function() {
data[this.name] = this.value;
});
$.ajax({
url: "external_file.php",
method: "POST",
data: data
}).done(function( msg ) {
$("#DEBUG").html(msg);
});
};
Related
I am desperately trying to submit multiple POST variables via AJAX, but just cant get manage to get the formatting right... Problem is that I have both a hardcoded / written action=problem_lookup variable and a dynamic field input as $(this).val and just cant manage to get both into one data string...
this works well:
data: 'problem=' + $(this).val(),
This does not:
data: { action: 'problem_lookup' , problem: $("problem").val() },
data: { action: 'problem_lookup' , problem: $(this).val() },
data: { action: problem_lookup, problem: $(this).val() },
I tried numerous formats from other threads and looked at the official jquery manual, but cant seem to get this figured out. Any help is appreciated.
EDIT:
full script below, tried the solutions posted so far but no success. $("problem") is a <select> field (with Select2 running) hence shouldnt cause me so much frustration, especially since the original approach with data: 'problem=' + $(this).val(), works fine.
$(function () {
$('#problem').change(function () { // on change in field "problem"
var data = {
action: 'problem_lookup',
problem: $("problem").val()
}
$.ajax({ // launch AJAX connection
type: 'POST', // via protocol POST
url: 'ajax.php',
//data: 'problem=' + $(this).val(), // send $_POST string
//data:"{'action':'"+action+"','problem':'"+$(this).val()+"'}",
//data:"{'action':'problem_lookup','problem':'"+$(this).val()+"'}",
//data: { action: 'problem_lookup' , problem: $("problem").val() },
//data : data_string,
data: $.param(data),
dataType: 'json', // encode with JSON
success: function (data)
{
// do something
},
});
});
});
An issue is in the
$("problem")
Jquery call.
If.problem is a css class try with
$(".problem")
if problem is a css id try with
$("#problem")
For posting arrays of object you can build data as an object containing arrays, changing a little bit your structure. Something like this
Var obj={};
obj.postData=[];
obj.postData.push(/*your first object here*/);
...
obj.postData.push(/*your n-th object here*/);
$.ajax({
.....
data:obj;
......
});
Try the FormData() FormData.
var data = new FormData();
data.append('action', value);
...
You need to specify your data variable first like this:
var data = {
action: 'problem_lookup',
problem: $("problem").val()
}
In AJAX serialize your data using $.param,
data: $.param(data),
Note: Twice check if $("problem").val() is correct. If problem is a class, you need to specify like this $(".problem").val() or if it is ID, $("#problem").val()
I have a form and a jQuery function which is triggered if user changes a html select field. The function collects all of the information what it needs and posts to a php script with an ajax post.
I want to extend this function with a new feature: if the selected value equals to a predefined value I want to display a dialog with two buttons. The user needs to click one of these buttons and if he does the new information will attached to the post.
An easy example:
The select has 3 options:
- Lemon
- Banana
- Apple
If the user selects lemon or banana, the scripts sends the info to the server without further actions. But if he selects apple, I need an extra dialog, because I want to ask if he needs a red or a green one. And it needs to be attached to the information which I want to send to the server.
Could you help me guys how should I do it?
I have only the first part:
$('select.myList').change( function()
{
var e = $(this)
var val = $(this).val();
var id = $(this).attr('data-id')
var url = 'index.php?process'
$.ajax({
type: "POST",
url: url,
data: { id: id, val: val },
success: function(data){
var o = $.parseJSON(data);
if( o.error )
{
console.log('error:' + o.message);
} else
{
console.log('success:' + o.message);
}
return false;
}
})
return false
})
First, I would say you should be extremely careful with your variable names. You should NEVER use e as a variable if it can be avoided. I would also change id and val.
In any case you should be able to use the beforeSend property in ajax: http://api.jquery.com/jquery.ajax/, so assuming that 'apple' would be the val of the element:
$.ajax({
type: "POST",
url: url,
data: { id: id, val: val },
beforeSend: function() {
if (val === 'Apple') {
//do stuff
}
},
// rest of ajax call
}
I have an HTML able, which I bind by using the following Action in MVC controller:
public ActionResult BindTable(int ? page)
{
int pageSize = 4;
int pageNumber = 0;
List<Users> _users = query.ToList();
return View(_users.ToPagedList(pageNumber, pageSize));
}
Below the table I have the following HTML:
<textarea class="form-control" style="resize:none;" rows="9" placeholder="Enter value here..." id="txtValue"></textarea>
<br />
<button style="float:right; width:100px;" type="button" onclick="CallFunction()" class="btn btn-primary">Update specific record</button>
The Javascript function responsible for calling the action is as following:
function CallFunction() {
if ($('#txtValue').val() !== '') {
$.ajax({
url: '/User/UpdateUser',
type: 'POST',
data: { txt: $('#txtValue').val() },
success: function (data) {
$('#txtValue').val('');
alert('User updated!');
},
error: function (error) {
alert('Error: ' + error);
}
});
}
And here is the Action responsible for updating the user:
public ActionResult UpdateUser(string txtValue)
{
var obj = db.Odsutnost.Find(Convert.ToInt32(1));
if(obj!=null)
{
obj.Text= txtValue;
obj.Changed = true;
db.SaveChanges();
return RedirectToAction("BindTable");
}
return RedirectToAction("BindTable");
}
Everything works fine. But the table doesn't updates once the changes have been made ( it doesn't binds ?? )...
Can someone help me with this ???
P.S. It binds if I refresh the website.. But I want it to bind without refreshing the website...
I created a BIND function with Javascript, but it still doesn't binds:
function Bind() {
$(document).ready(function () {
var serviceURL = '/User/BindTable';
$.ajax({
type: "GET",
url: serviceURL,
contentType: "application/json; charset=utf-8",
});
});
}
You're not actually updating the page after receiving the AJAX response. This is your success function:
function (data) {
$('#txtValue').val('');
alert('User updated!');
}
So you empty an input and show an alert, but nowhere do you modify the table in any way.
Given that the ActionResult being returned is a redirect, JavaScript is likely to quietly ignore that. If you return data, you can write JavaScript to update the HTML with the new data. Or if you return a partial view (or even a page from which you can select specific content) then you can replace the table with the updated content from the server.
But basically you have to do something to update the content on the page.
In response to your edit:
You create a function:
function Bind() {
//...
}
But you don't call it anywhere. Maybe you mean to call it in the success callback?:
function (data) {
$('#txtValue').val('');
Bind();
alert('User updated!');
}
Additionally, however, that function doesn't actually do anything. For starters, all it does is set a document ready handler:
$(document).ready(function () {
//...
});
But the document is already loaded. That ready event isn't going to fire again. So perhaps you meant to just run the code immediately instead of at that event?:
function Bind() {
var serviceURL = '/User/BindTable';
$.ajax({
type: "GET",
url: serviceURL,
contentType: "application/json; charset=utf-8",
});
}
But even then, you're still back to the original problem... You don't do anything with the response. This AJAX call doesn't even have a success callback, so nothing happens when it finishes. I guess you meant to add one?:
function Bind() {
var serviceURL = '/User/BindTable';
$.ajax({
type: "GET",
url: serviceURL,
contentType: "application/json; charset=utf-8",
success: function (data) {
// do something with the response here
}
});
}
What you do with the response is up to you. For example, if the response is a completely new HTML table then you can replace the existing one with the new one:
$('#someParentElement').html(data);
Though since you're not passing any data or doing anything more than a simple GET request, you might as well simplify the whole thing to just a call to .load(). Something like this:
$('#someParentElement').load('/User/BindTable');
(Basically just use this inside of your first success callback, so you don't need that whole Bind() function at all.)
That encapsulates the entire GET request of the second AJAX call you're making, as well as replaces the target element with the response from that request. (With the added benefit that if the request contains more markup than you want to use in that element, you can add jQuery selectors directly to the call to .load() to filter down to just what you want.)
I am trying to grab user input from a dynamic form using jquery serialize. My form looks like this
<form id="lookUpForm">
<input name="q" id="websterInput" />
<button onclick="webster(); return false;">Search</button>
</form>
I want to take the input, and attach it to the end of websters dictionary URL to search for a word.
http://www.merriam-webster.com/dictionary/ + (user input)
When you run an alert to see what the value of 'q' is, you get
q=input
so for example if I put 'cats'
the alert would say q=cats.
I want the the string to just be what the user entered. However, you need to give the input a name to use seralize. So how can I take the user input, and strip out the 'q=' part.
EDIT
as requested here is the function I'm calling. Note. I HAVE to use serialize(); This isnt an option.
function webster() {
var stringHolder = $("#lookUpForm").serialize();
alert(stringHolder);
$.ajax({
type: 'GET',
crossDomain: 'true',
url: "http://www.merriam-webster.com/" + stringHolder,
success: function (data) {
console.log(data);
console.log("http://www.merriam-webster.com/" + stringHolder);
},
error: function () {
alert("Failed to get dictionary data");
console.log("http://www.merriam-webster.com/dictionary/" + stringHolder);
}
});
};
You can just access it using val method of jQuery
function webster() {
var stringHolder = $("#lookUpForm").serialize();
alert(stringHolder);
$.ajax({
// (...) removed some code for brevity
error: function () {
alert("Failed to get dictionary data");
console.log("http://www.merriam-webster.com/dictionary/" +
$('#websterInput').val()); // I suppose you want the user-input here
}
});
};
You could use serializeArray().
And then do something like this and put your string together like you want to
var array = $("#lookUpForm").serializeArray();
$(array ).each(function(){
alert(this.value);
});
I'm trying to check if a user exists in my database and then change the values of my input fields to match that user's information. I have the following code but it doesn't seem to work.
<button onclick="checkAvailability()">Check Availability</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function checkAvailability()
{
$(function()
{
$.ajax(
{
type: 'POST',
url: 'test.php',
data: "name=" + $("#name").val(),
dataType: 'json',
success: function(row)
{
$('#name').val(row[0]);
$('#address1').val(row[1]);
$('#phone1').val(row[2]);
alert('success');
}
});
});
}
</script>
The alert goes off but none of the values are changed. I checked the response using Firebug and the response is a JSON object with the user's information. I'm not sure where the error is. Thank you for any input.
If you have a json object you must use: $("#name").val(row.name);
In case you are getting a json then it might look like this
var json = [{"name": "sample"},{"phone":"sample"},{"address":"sample"}];
When you are doing row[0].
what you get is an object["name":"sample"]
So you must make the following change
success: function(row)
{
$('#name').val(row.name);
$('#address1').val(row.address);
$('#phone1').val(row.phone);
alert('success');
}
Also make sure you have input types with id's name, address1 and phone1