Building a URL in AJAX via an HTML input - javascript

How may I take the input from a textbox in HTML, using autocomplete, in order to feed that data into my url parameter via ajax? My goal is to output the data into HTML. The type of data that I am querying is an XML API.
This is my html:
<input id="data_from_autocomplete">
<button type="submit>Submit</button>
This is my jQuery:
$.ajax({
type: "GET",
url: "http://www.something" + data_from_autocomplete + ".com",
dataType: "xml",
success: parse
});

Use
var param = $("#data_from_autocomplete").val();
var url = "http://www.something" + encodeURIComponent(param) + ".com";
//call your ajax
[update]
If you need to pass the value of the search field as parameter, just pass it in the data parameter of the ajax call:
var city = $("#data_from_autocomplete").val();
var state = "wa";
$.ajax({
url : "https://www.zillow.com/webservice/GetRegionChildren.htm",
data : {
"zws-id": /*your zws-id goes here*/,
state : state,
city: city
},
success: function(response) {
//process your response here
}
});

Related

Pass variable string from javascript to php using ajax

How to pass a variable value from html page using javascript to php?
i created this code in my index.php
$amount = $_GET['pricenumb'];
echo $amount;
and this is my javascript code to call on click of button and send the data to the PHP file.
<script type="text/javascript">
$(".cell").on("click", "input:checkbox", function () {
var thiss = $(this);
var total = $("#price");
var target = $("label[for='" + thiss.attr("id") + "']");
var item_value = +(target.html().replace(/[^0-9\.]/g, "") || 0);
var cur_total = +(total.html().replace("$", "") || 0);
if (thiss.prop("checked") === true) {
cur_total += item_value;
} else {
cur_total -= item_value;
};
total.text("$" + cur_total);
});
</script>
<script type="text/javascript">
$("#pay_btn").on("click", function () {
var price = $("#price").text();
var pricenumb = price.replace(/[^0-9\.]/g, "");
$.ajax({
type: "POST",
url: "forumdisplay.php?fid=2",
data: "price=" + price + "pricenumb="+ pricenumb,
cache:false,
success: function(){
}
});
});
</script>
and this is the checkbox,
<div class="cell">
<div class="form-check"><label for="check-a" class="form-check-label"><input id="check-a" class="form-check-input" type="checkbox">$166<span class="form-check-sign"></span></label>
<div class="mask visible-on-sidebar-regular">Buy Product</div>
</div>
</div>
the work code is, when I check the checkbox, it will update the div content, and I want when I click on pay button, get the div value via javascript and send the value to my index.php
You are using POST in your ajax and GET in php, chage your ajax to GET. Also, In your ajax change
type: "POST",
url: "forumdisplay.php?fid=2",
data: "price=" + price + "pricenumb="+ pricenumb,
to
type: "GET",
url: "forumdisplay.php",
data: {
price: price,
pricenumb: pricenumb,
fid: 2
}
That's not how you pass data in ajax. The correct format is to use curly braces and define props name and then value
data:{propName1: value1,propsName2: value2,propsName3: "Some string value"}
Which can be used in the file like this in case of POST request.
$_POST['propName1'] which will give value1 variable data as a result
$_POST['propName3'] which will give output as Some string value string
The value can be in quotes if it's a string or not in quotes if it's a variable. So you need to redefine your ajax data props to
$.ajax({
type: "POST",
url: "forumdisplay.php?fid=2",
data: {price: price ,pricenumb: pricenumb},
cache:false,
success: function(response){
// Things to do on success
},
error: function(error){
// Error handling in case of error
}
});
These values you passed can be used in the file forumdisplay.php with $_POST['price'] and $_POST['pricenumb']. The name inside the $_POST is the propsName inside data props in ajax function.

jQuery AJAX GET Request not calling properly

I'm calling a GET request from a jQuery AJAX function, but the GET request doesn't seem to be calling properly. After running the script, the address bar only shows "index.php?", instead of the expected "index.php?searchterm=searchterm".
index.php
$(function(){
$("form").submit(function(){
var searchterm = document.getElementByID("searchterm").value;
$.ajax({
method: "GET",
url: "search.php",
data: searchterm
})
.done(function(res) {
document.getElementById("item1").innerHTML = res;
});
});
});
If it's any relevance, here is search.php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$searchterm= isset($_GET['searchterm']) ? $_GET["searchterm"] : '';
exec("C:\Users\Callum\AppData\Local\Programs\Python\Python35-32\python.exe search.py $searchterm", $output, $result);
echo $result[0];}
?>
Correct data in ajax call as :
.......
$.ajax({
method: "GET",
url: "search.php",
data : { searchterm : searchterm } // Change here
})
.......
According to docs ,data in ajax call is data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. Object must be Key/Value pairs.
Reference
You should open the firebug console and see if you ajax request is visible there. If it is visible you can click on it and you will see what data it is passing to the requested url search.php
Also You didn't pass the data correctly using ajax. And if you are using ajax then browser address bar will not be updated as the page is not getting reloaded.
$(function(){
$("form").submit(function(){
var searchterm = document.getElementsByID("searchterm").value;
$.ajax({
method: "GET",
url: "search.php",
data: { searchterm : searchterm }//This is how to pass data correctly
})
.done(function(res) {
document.getElementById("item1").innerHTML = res;
});
});
});
the data property of the ajax function is an object so it should look like this:
data: { searchterm: searchterm }

unset a variable passed through post in ajax

I have ajax code in my javascript file as follows:
// Default settings for Ajax requests
$.ajaxSetup({
type: 'POST',
url: path + '/relay.php'+ '?curr=' + currency + "&ver=" + Math.random(),
success: function(response) {
// Refresh the cart display after a successful Ajax request
container.html(response);
$('#jcart-buttons').remove();
},
.......
The above will post as (in firebug):
POST http://www.myshop.com/cart/relay.php?curr=EUR&ver=0.5750630930208085
I have a remove function as follows:
function remove(link) {
// Get the query string of the link that was clicked
var queryString = link.attr('href');
queryString = queryString.split('=');
// The id of the item to remove
var removeId = queryString[1];
// Remove the item and refresh cart display
$.ajax({
type: 'GET',
data: {
"jcartRemove": removeId,
"jcartIsCheckout": isCheckout
}
});
}
The remove will display as follows(firebug)
GET http://www.myshop.com/cart/relay.php?curr=EUR&ver=0.5750630&jcartRemove=5
I need to remove the curr variable too...
How can i do it in my remove link code above ???
CHANGE AJAX METHOD BECAUSE YOU ARE SENDING PARAMETERS FROM URL (this is get method to send parameters)
$.ajaxSetup({
type: 'GET',
url: path + '/relay.php'+ '?curr=' + currency + "&ver=" + Math.random(),
success: function(response) {
// Refresh the cart display after a successful Ajax request
container.html(response);
$('#jcart-buttons').remove();
},
$.ajax({
type: 'POST',
data: {
"jcartRemove": removeId,
"jcartIsCheckout": isCheckout
}
});
HERE ARE THE LINKS:
LINK AJAX
LINK POST
LINK GET
1.You need to change the $.ajaxSetup method, the url used in this method i.e
url: path + '/relay.php'+ '?curr=' + currency + "&ver=" + Math.random()
contains curr and ver parameters but you don't need curr variable in Remove Function So you need to remove curr varible from this url and add curr variable only in particular ajax calls where it will be required.
2.Like by default your url should be
url: path + '/relay.php?ver=' + Math.random()
and add curr varible in your subsequent ajax calls using data parameter.
3.Now, when you call remove function default query string will not contain curr parameter.
function remove(link) {
// Get the query string of the link that was clicked
var queryString = link.attr('href');
queryString = queryString.split('=');
// The id of the item to remove
var removeId = queryString[1];
// Remove the item and refresh cart display
$.ajax({
type: 'GET',
data: {
"jcartRemove": removeId,
"jcartIsCheckout": isCheckout
}
});
}
GET http://www.myshop.com/cart/relay.php?ver=0.5750630&jcartRemove=5&jcartIsCheckout=true
in case isCheckout=true
GET http://www.myshop.com/cart/relay.php?ver=0.5750630&jcartRemove=5&jcartIsCheckout=false
in case isCheckout=false
In case you have any queries, do post.

How to use Ajax call correctly to send form data to Webserver?

I am trying to implement a form containing a list of cities, using a JSON array and an autocomplete function.
My ajax call is successful and gives the expected success alert, but I'm still not getting the JSON array data.
The problem is that my suggest_json_application function is failing at the 'if form.has_key('term')' statement and giving the message "form has no key".
How can I pass the form data to the function properly through the ajax call, with the key term?
HTML form
</head>
<body>
<form>
<fieldset><legend>Cities</legend>
<input type='text' name='term' id='term'>
</form>
JQuery
$('document').ready(function() {
var term = $('#term').val();
$.ajax({
url: "/suggestjson",
type: "POST",
dataType: "json",
data: JSON.stringify({'term': term}),
success: function (data) {
alert('success');
console.log( data );
}
});
});
Webserver
cities = ['New York', 'London', 'Los Angeles',
'Paris', 'San Francisco', 'Adelaide']
if environ['PATH_INFO'] == "/suggestjson":
return suggest_json_application(environ, start_response)
def suggest_json_application(environ, start_response):
//Return JSON array of completions for a city name
form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ)
if form.has_key('term'):
print "form has key"
q = form.getvalue("term", "")
matches = [c for c in cities if c.lower().startswith(q.lower())]
else:
print "form has no key"
matches = []
return json.dumps(matches)
Currently you are sending whole html element to server. Invoke val() function to get the value of element,
Also use id selector for easy access to element,
like this:
var term = $('#term').val();
please try to change "data" option to a object in the ajax call as follow
$('document').ready(function() {
var term = $('input[name=city]');
$.ajax({
url: "/suggestjson",
type: "GET",
dataType: "json",
data: {'term': term},
success: function (data) {
alert('success');
console.log( data );
}
});
});
Use val() :- see details here
var term = $('#term').val();
and also data parameter in ajax it should be
data : {term: term}

Replace javascript onmouseover with jQuery only

I have a page that displays a dynamic amount of "orders" and I have a button to "view" and another button to "print". To display the specific OrderNumber I'm using a javascript function triggered by onmouseover and a jQuery ajax function to change the button text, make a database entry, and then view or print another page. The problem is the order is viewed or printed MULTIPLE times from onmouseover. How can use only jQuery and call the specfic OrderNumber? Here is the code I'm using now:
This code is repeated for each order:
<div class="console_orders_details">
<input type="button" value="View"
id="vieworder'.$row[orderid].'" onmouseover="vieworder('.$row[orderid].');">
</div>
Here is the function to view the order:
function vieworder(id){
$(function(){
$('#vieworder' + id).click(function(){
var orderid = id;
var dataString = 'orderid='+ orderid; //string passed to url
$.ajax
({
url: "includes/ajax/console-view.php", //url of php script
dataType: 'html', //json is return type from php script
data: dataString, //dataString is the string passed to the url
success: function(result)
{
window.open("print.php?view=1&orderid="+id+"");
$('#vieworder' + orderid + ':input[type="button"]').attr("value", "Viewed!").fadeIn(400);
}
});
})
});
}
I'm assuming I need to eliminate the "vieworder" function and use a pure jQuery function. However, I don't know how to send over the order "id", which is why I used javascript.
You can target all elements with an ID that starts with vieworder, and then store the row ID as a data attribute :
<div class="console_orders_details">
<input type="button" value="View" id="vieworder'.$row[orderid].'" data-id="'.$row[orderid].'">
</div>
JS
$(function(){
$('[id^="vieworder"]').on('click', function(){
var orderid = $(this).data('id'),
btn = $('input[type="button"]', this);
$.ajax({
url: "includes/ajax/console-view.php",
dataType: 'html',
data: {orderid : orderid}
}).done(function(result) {
window.open("print.php?view=1&orderid="+orderid+"");
btn.val("Viewed!").fadeIn(400);
});
});
});
Your onmouseover event is probably being fired many times, resulting in your problem. This might help to stop unwanted extra calls, by ignoring them unless the previous one has completed.
var activeRequests = {}; // global
function vieworder(id){
if (activeRequests[id]) { return; }
activeRequests[id] = true;
$(function(){
$('#vieworder' + id).click(function(){
var orderid = id;
var dataString = 'orderid='+ orderid; //string passed to url
$.ajax
({
url: "includes/ajax/console-view.php", //url of php script
dataType: 'html', //json is return type from php script
data: dataString, //dataString is the string passed to the url
success: function(result) {
delete activeRequests[id];
window.open("print.php?view=1&orderid="+id+"");
$('#vieworder' + orderid + ':input[type="button"]').attr("value", "Viewed!").fadeIn(400);
}
});
})
});
}
First, don't have a dynamic id that you have to parse, and don't have an event handler in your html:
<div class="console_orders_details">
<input type="button" value="View" class="vieworder" data-id="$row[orderid]">
</div>
Next, create an event handler for just what you want to do. .one() will set an event handler to fire only once:
$(document).ready(function (){
$(".console_orders_details").one("mouseover", ".vieworder" function(){
var dataString = "orderid=" + $(this).data("id");
$.ajax({
url: "includes/ajax/console-view.php", //url of php script
dataType: 'html', //json is return type from php script
data: dataString, //dataString is the string passed to the url
success: function(result) {
window.open("print.php?view=1&" + dataString);
$(this).val("Viewed!");
}
});
});
});
If you want this to work onclick, then just change the mouseover to click. Also, fadeIn doesn't work on values. Here is a fiddle that has the basics: http://jsfiddle.net/iGanja/EnK2M/1/

Categories