jQuery error in client post response - POST HTTP/1.1" 400 - javascript
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.
Related
Ajax is not sending multiselect data to Django views
I am quite new to Django so bare with me. I have a multiselct list in my webpage and I need to send the selected items to my views in order to make use of them. To do so, I used ajax but when it doesn't seem to work for some reason. This is the script: $("#var_button").click(function(e) { var deleted = []; $.each($("#my-select option:selected"), function(){ deleted.push($(this).val()); }); alert("You have deleted - " + deleted); e.preventDefault(); $.ajax({ type: "post", url: "/description/upload-csv/" , data: { 'deleted' : deleted } }); // End ajax method }); I checked with alert if maybe the variable deleted is empty but it return the selected values so the problem is in my ajax query. This is the part where I retrieve the data in my views.py if request.method == 'POST': del_var = request.POST.getlist("deleted[]") my_class.del_var = del_var I changed the data type to text but it doesn't do anything
I cant help you on the Django side. $.each($('#selector'), (i, e) => { deleted.push($(e).val()); }) but this will add the value to the "deleted" variable.
Ajax POST with function
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.
Ajax-Post data again AFTER success
So I have got a small application that check metrics for domains that are valuable for SEO. I establish a connection with API and process them to get the relevant data. Everything works great there and I do get my data, problem is with Javascript main.js that processes that data. So my main idea is that I have a select input that corresponds to specific API calls, then a textarea where you paste your links. All works great, and I manage to get the response using ajax and build a relevant view corresponding to a specific method selected. When ajax responds with success, I fetch data, parse it and make relevant function calls. When page is built, on top I need to have a small select box that would make user to select different method and would retrieve data for the same links. After success I have built a input that correspond to the same select used on main page. And my question is How can i send data again? So, here is the code $("#parseLink").on("click", function () { var textBox = $("#linkInput").val(); var method = $("#select").val(); var newTextBox = textBox.split("\n"); var methodsList = { "Social Values": "GetValueSocialSpread", "Social Visibility": "SocialGetValueVisibility", "Organic Keyword Count": "GetCountDomainKeyword", "Seo Visibility": "SeoVisibilityWorld" }; var selectedApi = methodsList[method]; var dataToSend = { url: newTextBox, api: selectedApi } $("#container").replaceWith("<div class='containter text-center'><h1>Loading...</h1><i class='fa fa-spinner fa-pulse fa-5x'></i></div>"); function mainFunc() { $.ajax({ type: "POST", url: "../parser.php", data: { data: JSON.stringify(dataToSend) }, success: function (response) { //remove loading $("div.text-center").remove(); $("div.main_holder").append("<div class='container'><div class='row'><div class='pull-right'><button id='export' type='button' class='btn btn-info'>Export</button></div></div></div>"); $("div.main_holder").append("<div class='container'><div class='row'><select class='form-control' id='select'><option>Social Values</option><option>Social Visibility</option><option>Organic Keyword Count</option><option>Seo Visibility</option></select></div></div>"); var result = JSON.parse(response); var jsonObject = result; urlArray = []; $.each(result, function (k, v) { urlArray.push(k); }); if (method === "Social Values") { socialValues(result, urlArray); } else if (method === "Social Visibility") { socialVisibility(result, urlArray); } else if (method === "Organic Keyword Count") { organicKeyWordCount(result, urlArray); } else if (method === "Seo Visibility") { seoVisibility(result, urlArray); } } }); } }); I tried calling ajax function again, not working... it probably has a simple solution(hopefully) I am opened to suggestions! And please tell me if you need more elaborate explanation! Was doing it all night :))
checking instantly php arrays using jquery / ajax
I want to be able to check whether values exist in the php array without having to click the submit button to do those checks using jquery/ajax. when users enter an abbreviation in the text field want to be able to show that the brand exists (either vw or tyta) or not (as they type in the input box) and show the results in the carnamestatus div. I was following a tutorial from youtube, however it queried against a mysql database. I was wondering if this is possible using php arrays instead of mysql? I would be grateful if you could pick any faults in the code. the code is as follows: <?php $car = array() $car["vw"] = array( "name" => "volkswagen"); $car["tyta"] = array( "name => "toyota"); ?> the html code is as follows: <label for="carname">Car Code:</label> <input type="text" onblur="checkcar()" value="" id="carname" /> <div id="carnamestatus"></div> the checkcar() function checkcar(){ var u = _("carname").value; if(u != ""){ _("carname").innerHTML = 'checking ...'; var B = new XMLHttpRequest(); B.open("POST","check.php",true); / B.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); B.onreadystatechange = function() { if(B.readyState==4 && B.status== 200) { _("carnamestatus").innerHTML = B.responseText; } } var v = "carnamecheck="+u; B.send(v); } } </script>
Use Javascript keyboard event and then, send the value of the input into your php function. For example: $("#youInput").keyup( function() { $.ajax( { type: "post", url: "your_url.php", data: {params: $(this).val()}, success: function(data) { console.log(data) } } ); } ); And in you php code, just retrieve the params value, $_POST['params'] Explain When you press the keybord, your retrieve the value of the input ( here, it is $(this).val() where this represents #yourInput ), then you send the value via ajax (Here we use post type) with your url and the different params that you will send to the server side. If you post the value with $_POST['params'] you will get the value entered in the input. And if it's success, the callback function will retrieve the data returned by your server side. Here, we just use, jQuery.ajax but you can find more about ajax here or here. Using library make it easy to work with. Hope it helps you!
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.