Ajax POST with function - javascript

I was using this code for get function and It works perfectly. Im getting data with this function.
function getdata(getdatafrom, resultclass){
$.get(getdatafrom, function(data) {
$(resultclass).html(data);
});
}
But I need this for post method. Im getting inputs with this get method I have to post it. It has to look like this.
function postdata(postdatafrom, inputnamesvaluelist){
$.post(postdatafrom, function(data) {
$(resultclass).html(data);
});
}
I will enter input names on this code like :
onclick="postdata(post.php,input1-input2-input3)"
And it ll post this inputs.. How can I do this?

If you would do this using inline-event you should add single quotes :
onclick="postdata('post.php', '#input1-#input2-#input3')"
Then your js should be :
function postdata(postdatafrom, inputnamesvaluelist){
var inputs_ids = inputnamesvaluelist.split('-');//split string passed into array of ids
var parameters={};
//construct obejct of {name: value,..} that you could pass it in post request
$.each(inputs_ids, function(index, input_id){
var input_name = $(input_id).attr("name");
var input_value = $(input_id).val();
parameters[input_name]=input_value;
})
//post parameters to given "postdatafrom"
$.post(postdatafrom, parameters, function(data) {
//Your code here
});
}
Hope this helps.

Related

jQuery error in client post response - POST HTTP/1.1" 400

I can't figure out what is wrong with my code and I'm not really good with jQuery.
I'm trying to build HTML form will hold cars data. It's based on this form:
HTML source code is here.
Form data is sent on button click on the end back to program.
I upgraded that form with cascading manufacturer (proizvodjac in code) and car models droplist based on this code. But it's not working.
I keep receiving HTTP 400 which would mean that my POST call from client is malformed.
Here is my jQuery functions:
$(function () {
var carsdata = {"alfaromeo":["mito","156","147","giulietta","159","166","146"],"audi":["a3","a4","a6","a5","80","a1","q3","a8","q5"],"bmw":["320","116","x3","316","318","118","530","x1","520","x5","525","330","120","323","serija 1"],"chevrolet":["spark","lacetti","captiva","aveo","cruze"],"citroen":["c4","c4 grand picasso","c3","c5","c4 picasso","xsara","berlingo","c2","xsara picasso","saxo","ds5","c1"],"fiat":["brava","bravo","panda","grande punto","stilo","punto","punto evo","doblo","500","tipo","uno","coupe"],"ford":["c-max","fiesta","focus","mondeo","fusion","ka","escort"],"honda":["civic","accord","cr-v"],"hyundai":["getz","i10","i20","atos","i30","coupe","elantra","accent","santa fe","ix35","tucson"],"kia":["rio","pro_cee'd","sportage","cee'd","pride","sorento"],"mazda":["3","2","323 f","626","6","cx-5","323","premacy","5"],"mercedes":["a-klasa","c-klasa","e-klasa","b-klasa","124"],"mercedes-benz":["e-klasa","clk-klasa","c-klasa","s-klasa","190","a-klasa","b-klasa","c t-model","ml-klasa","w 124","124"],"nissan":["qashqai","x-trail","note","primera","micra","juke","almera"],"opel":["corsa","astra","zafira","meriva","vectra","insignia","mokka","tigra","combo","astra gtc","kadett"],"peugeot":["308","207","206","306","106","307","208","406","508","407","partner","3008","405"],"renault":["thalia","clio","scenic","grand scenic","kangoo","captur","megane grandtour","megane","laguna","5","megane break","twingo","modus","kadjar","megane classic","espace","megane scenic","megane coupe","megane sedan"],"seat":["toledo","leon","ibiza","altea","cordoba"],"skoda":["fabia","octavia","120","superb","felicia","rapid"],"smart":["fortwo"],"toyota":["corolla","yaris","auris","avensis","rav 4","land cruiser"],"vw":["polo","golf v","golf iv","golf vii","passat","golf vi","jetta","passat variant","caddy","sharan","tiguan","golf variant","golf ii","vento","golfplus","golf iii","bora","touran","touareg","up!"]};
var proizvodjac = $('<select id="proizvodjac"></select>');
var model = $('<select id="model"> </select>');
$.each(carsdata, function(item, key) {
proizvodjac.append('<option >' + item + '</option>');
});
$("#containerProizModel").html(proizvodjac);
$("#proizvodjac").on("change", function(e) {
var item;
var selected = $(this).val();
if (selected === "alfaromeo") {
item = carsdata[selected];
} else {
item = carsdata[selected];
}
$(model).html('');
$.each(item, function(item, key) {
model.append('<option >' + key + '</option>');
});
});
$("#containerProizModel").append(model);
$("button#predict").click(function(e){
e.preventDefault();
/*Get for variabes*/
var kilometraza = $("#kilometraza").val(), godina_proizvodnje = $("#godina_proizvodnje").val();
var snaga_motora = $("#snaga_motora").val(), vrsta_goriva = $("#vrsta_goriva").val();
/*create the JSON object*/
var data = {"kilometraza":kilometraza, "godina_proizvodnje":godina_proizvodnje, "proizvodjac":proizvodjac, "model":model, "snaga_motora":snaga_motora, "vrsta_goriva":vrsta_goriva}
/*send the ajax request*/
$.ajax({
method : "POST",
url : window.location.href + 'api',
data : $('form').serialize(),
success : function(result){
var json_result = JSON.parse(result);
var price = json_result['price'];
swal('Predviđena cijena auta je '+price+' kn', '','success')
},
error : function(){
console.log("error")
}
})
})
})
Comments and explanations are in the code.
On server side:
Server is expecting user_input dictionary which is built from variables returned by POST request. Here is how API method looks:
#app.route('/api',methods=['POST'])
def get_delay():
result=request.form
proizvodjac = result['proizvodjac']
model = result['model']
godina_proizvodnje = result['godina_proizvodnje']
snaga_motora = result['snaga_motora']
vrsta_goriva = result['vrsta_goriva']
kilometraza = result['kilometraza']
user_input = {'proizvodjac':proizvodjac,
'model':model,
'godina_proizvodnje':godina_proizvodnje,
'snaga_motora':snaga_motora,
'vrsta_goriva':vrsta_goriva,
'kilometraza':kilometraza
}
print(user_input)
a = input_to_one_hot(result)
price_pred = gbr.predict([a])[0]
price_pred = round(price_pred, 2)
return json.dumps({'price':price_pred});
Error from Google Chrome Developer Console:
which is pointing to:
EDIT 1:
I don' know how to pass proizvodjac and model to onClick function. See what happens on breakpoint:
XHR on Network tab:
HTML form is being filled with data OK only manufacturer and model are not passed to onClick:
EDIT 2:
Getting closer to solution. I've added :
var proizvodjac = $("#proizvodjac").val()
var model = $("#model").val()
as suggested and now all variables are successfully passed!
But I still get error 400 as final ajax POST call is getting stuck somwhere..
EDIT 3:
changed from
data : $('form').serialize()
to
data = data
AJAX method receives everything ok:
Still it doesn't work.
There are two main issues here:
1) you aren't getting the values from two of your fields correctly. You need to add
var proizvodjac = $("#proizvodjac").val()
var model = $("#model").val()
inside the $("button#predict").click(function(e){ function.
2) You're collecting all these values and putting them into your data variable...but then you aren't doing anything with it. Your AJAX request is configured as follows in respect of what data to send:
data : $('form').serialize()
The serialize() function automatically scoops up all the raw data from fields within your <form> tags. In your scenario, if you want to send a custom set of data (rather than just the as-is contents of the form) as per your data object, then you simply need to change this to
data: data
so it sends the information from that object in the POST request instead.

Ajax not working for dynamic key in data parameter

I am trying to make a ajax function like this:
var vm=$.noConflict();
vm(document).ready(function(){
var loadMore=function(e)
{
var idd=vm(this).attr("id");
alert(e.data.recordId); //it return blog_comment_id if I provide static value to data key
var aaa=e.data.recordId;
vm.ajax({
type:"POST",
url:"ajaxHTML.php",
data:({e.data.recordId: idd}),
cache:false,
success:function(res)
{
alert(res);
vm("#"+e.data.divId).html(res);
}
});
}
and calling this ajax function like this, Actually I am trying to make it dynamic where I will provide div id and record id.
vm(function() {
vm(".view_more").click({divId:"fgh",recordId:"blog_comment_id"},loadMore);
});
it is not working If i provide data parameter like this:
data:({e.data.recordId: idd}),
working for
data:({blog_comment_id: idd}),
So how could I make it possible with dynamic key.
Help will be appreciate

Sending a variable back to Express on click?

Let's say I have a list of 10 elements each with a unique id as their name and the user can add to the list whenever.
When I click an element, I want Express to get the id of the element I clicked. If it was just one element with a fixed id I could just use req.body.idname, but there can potentially be 100.
Is there a way to do this?
So far I have:
$( "li" ).click(function() {
var x = $(this).attr('name');
console.log(x);
});
which does get the correct name of the element but that's it.
What I'm trying to do is pass in the id as a parameter for a function like
exports.somePage = function(req, res){
var id = //id from clicked element goes here
//getElement finds the foo with the id
databaseTable.getFoo(id, function (err, foo){
if(err)
console.log("error");
else {
res.render('page', { title: 'Page',
foo : foo
});
}
});
};
You could use AJAX to POST the data.
$("li").click(function()
{
var ajaxData = {};
ajaxData.name = $(this).attr('name');
var request = $.ajax({
type: 'POST',
data: ajaxData,
url: 'http://localhost:3000/handleName'
});
request.success(function(data)
{
console.log("Success.");
for(var i = 0 ; i < data.length ; i++)
{
// Optional to pass some data back.
}
});
request.error(function(request, status, error)
{
console.log(request.responseText);
});
});
Wherea your handleName looks something like this:
app.post("/handleName", function(request, response)
{
response.setHeader('Access-Control-Allow-Origin', 'http://127.0.0.1'); // Sometimes required.
var name= request.body.name;
});
Maybe this isn't 100% copy/paste working for you but using AJAX and fetching the name in the request should work.
This is a two step process. First on express you need the proper routing set:
Server Side
//app = express();
app.get('/api/:paramID1/:paramID2',function(req, res){
//your code req.params.paramID1 or req.params.paramID2
});
On the client side you need a link that invokes the url or ajax like: http://yourdomain/api/1/abc where 1 and abc are param1 and param2 respectively.
So something as simple as: Some Demo on click could send the information you need to the server. Or using a little bit more complex example with JQuery/Ajax:
$.get( "/api/1/abc", function( data ) {
alert( "Load was performed. " + data );
});
Please note that when using rest there are different type of "methods" that can be invoke depending on your needs, such as POST, DELETE, UPDATE or the one just mentioned in the example GET.

Put json result from php script into divs jQuery

I have two divs, each one should have a record name from a json result.
<div class="first"></div>
<div class="second"></div>
My json file is as follows :
[{"Name":"name1","Instruction":"instr"},
{"Name":"name2","Instruction":"instr again"}]
I want to put in the first div's value, the ‘Name‘ value of the first record, same for the second div but with the second record.
I'm using jQuery :
<script>
$(document).ready(function() {
$.post("data/result.php",
function(data) {
//alert("Data: " + data);
$('div.first').append(data.Name); //data.Name returns undefined
}
);
});
</script>
Any help would be appreciated.
as far as you are using post for you ajax call, the data returns as a json string, do this:
$(document).ready(function() {
$.post("data/result.php",
function(data) {
data = JSON.parse(data);
$('div.first').append(data[0].Name);
$('div.second').append(data[1].Name);
}
);
});
As previously mentioned you need to parse the result as json. You could use the built in parser in jquery. Like this:
<script>
$(document).ready(function() {
$.ajax({
url: 'data/result.php',
type: 'POST',
dataType: 'json',
success : function (data) {
$('div.first').append(data[0].Name);
}
});
});
</script>
First of all, you can give a datatype with a request:
$.post('data/result.php',function(data) { },'JSON');
If you are not posting any information, why not just use $.get ? (it's the same syntax btw)
$.post('data/result.php',function(data) {
var $first = $('div.first'),
$second = $('div.second');
$first.text(data[0].Name);
$second.text(data[1].Name);
},'JSON');
Also, if you use .append(..) it will be appended to whatever is already in the div. If that is your intention, use .append(...). However, if you want to replace the content of it, even if it is empty, use .text(...) or .html(...)

simple form validation with jquery serialize() function

$(document).ready(function(){
$('#send').click(function() {
var names = $('#appontment_form').serialize();
//this is how my names variable look like
//doctor=Dr.Fathmath+Shahuda&date=2013-02-27&time=1900+-+1700&phone=
var doc = $(names).filter('doctor');
if(doc !='')
{
$.ajax({
type: "post",
url: "../../includes/jqueryRequireFiles/appointmentSave.php",
data:names,
success: function(data)
{
$('#confir').text('Your Appointment Received..');
}
});
return false;
}
});
});
I have a appontment form. when i click send link it will grab all the values in the textboxs and put it in the names variable through serialize() function. i want to filter the names variable and find out if any of the field is left not filled.. if only if then i will make the ajax part.. but its not working...any help
When you use $.serialize() the variable content looks like ?key=value1&key=value2. If you want to validate the form, just do it without serialize like
var found_errors = false;
if($('#formfield1').val().trim() == "") {
//Handle errors if field is empty
found_errors = true;
}
And if no errors are found, serialize the form and send it.
Consider using jQuery validation plugin.
http://docs.jquery.com/Plugins/Validation

Categories

Resources