I am trying to append data data from a form to a request so that the complete URL is sent as the request. I know I can do this in PHP but want to know if I can also do it in the javascript
For example the json request is sent to
"http://api.wunderground.com/api/myapi/conditions/q/ZIP.json"
Where ZIP will be replaced by the user submission
$(function() {
$("#getzip").submit(function() {
var zip_data =$(this).serialize();
$.getJSON("get_weather.php",null , function(data); {
Is it possible to pass it in stead of the null? And how would I go about appending it to the request strictly in the javascript?
$.getJSON("get_weather.php",{
whatever: "value",
somemore: "another value"
}.function(){
//
};
then in your PHP:
$whatever=filter_input(INPUT_GET,"whatever",FILTER_SANITIZE_STRING);
$somemore=filter_input(INPUT_GET,"somemore",FILTER_SANITIZE_STRING);
Seems like you would need to append it to the URL string itself:
$.getJSON("http://api.wunderground.com/api/myapi/conditions/q/"
+ zip_data, function(data){ return data });
Related
Here is a script.
It provides some select inputs which allow picking from various types of options. When the submit button is pressed it records the data in mats and pushes the mats array into an array called materialsUsed. Everytime the submit button is clicked a new array is added in materialsUsed.
I want to know how to send the materialsUsed array through a URL to php to extract the data there and insert it into an array created in PHP.
var mats = [name= "", thick= "", size= "", quantity= 0, price= 0];
mats.name = document.getElementById("mat").options[document.getElementById("mat").selectedIndex].value;
mats.thick = document.getElementById("thick").options[document.getElementById("thick").selectedIndex].value;
mats.size = document.getElementById("size").options[document.getElementById("size").selectedIndex].value;
mats.price = parseFloat($('#priceto').val()).toFixed(2);
mats.quantity = parseInt($('#quant').val());
materialsUsed.push(mats);
If you would like to simply load them as GET values into the URL just set them directly in the URL using location.href. Then simply use $__GET (IE: $__GET['mat']) in PHP to grab values.
var baseURL = "http://yourdomain.com";
window.location.href = baseURL + "?mat=" + mats.name + "&thick=" + mats.thick etc...
First you have to properly prepare your mats array and convert materialsUsed array into JSON format. Then you can call an ajax function like below, to send it to the php script.
var jsonString = JSON.stringify(materialsUsed);
$.ajax({
type: "GET",
url: "your_script.php",
data: {data : jsonString},
success: function(){
alert("Successfully sent the data!");
}
});
From the your_script.php file, you can perform this to extract the array.
$data = json_decode(stripslashes($_GET['data']));
Important
When using GET method, the amount of the data (length of url) is
limited. So, if your materialUsed array is too huge, you should use
POST method instead.
I think what you're looking for is making an ajax call to your php script providing your js array as its data.
You should listen for the form submission event in your javascript and launch an AJAX call to your PHP script providing your array. You may send your array via the URL (query string) using a GET or in the request body using a POST (that's an option you specify in your AJAX call). Then you would just retrieve your array in your php script an do whatever you want with it.
I suggest you read more on form submission events and AJAX calls in javaScript.
Quick hint : if you have the possibility to do so, try using jQuery as AJAX is way easier to use with jQuery.
You are trying to use associative array, but it's not possible in Javascript as far as I know.
I'd say the best way to do that is creating a object, parsing to json and sending to php. Does't look that hard.
as we use $_REQUEST in PHP to receive post/get values, I'm looking for a similar function/key to receive values sent through $.ajax.. in java script/j query
example:
<script>
function do_something(){
// here i want the value sent using ajax
return term;
}
$('#input').keyup(function(){
var term=$(this).val();
$.ajax({
url:do_something(),// << is this possible?? or should i try
//url:do_something(term) //<< this???
dataType:'json',
data:{term:term},
results:function(data){
alert(JSON.stringify(data));
}
});
</script>
document.location.search can get GET values of the current URL.
When used like this:
document.location.search.substr(1).split("&");
you can get an array containing all GET keys and values like key=value. Then by simply splitting them on = you get the value.
I'm doing the following jQuery call:
$.getJSON(
"http://localhost:9000/user?name=",
"test",
function(data) {
alert(data.aaData[0]);}
);
but it doesn't work because the data param "test" will be "&test" in the actual call (at least that's what firebug tells me).
I'm a total beginner with JavaScript and jQuery, can anyone tell me how to remove the &-sign in front of the data param?
So that the actual call is http://localhost:9000/user?name=data and not http://localhost:9000/user?name=&data
You could pass the data as an object, like this:
$.getJSON(
"http://localhost:9000/user",
{ name: "test" },
function(data) {
alert(data.aaData[0]);
}
);
The data-object will then be converted to a string and URL-encoded before it is added to the URL. From the jQuery documentation of .getJSON():
If the value of the data parameter is an object (map), it is converted
to a string and url-encoded before it is appended to the URL.
You have to set the get variables to be sent in the correct way:
$.getJSON("http://localhost:9000/user", "name=test", function(data) {
alert(data.aaData[0]);
});
I'm new to JSON/AJAX and
I've some problems with displaying data out of a JSON-object I've got from a server..
The url "http://localhost:8387/rest/resourcestatus.json" represents this object, which I would like to display via HTML/Javascript.. This object stores some monitoring information:
{"groupStatus":[
{"id":"AL Process","time":1332755316976,"level":0,"warningIds":[],"errorIds":[]},
{"id":"AL:instance1","time":1332919465317,"level":0,"warningIds":[],"errorIds":[]},
{"id":"AL:instance2","time":1332919465317,"level":1,"warningIds":["documentarea.locked"],"errorIds":[]},
{"id":"SL","time":1331208543687,"level":0,"warningIds":[],"errorIds":[]}
]}
Since the requested url is different from my domain I can't create a typical XMLHttpRequest.. So I found out that there's an AJAX cross-domain request which can be realised via jQuerys "getJSON()" method.
I want to display the ids and their level in a table.
Any solution to achieve this?
i think you are referring to JSONP. see jQuery.ajax Ex:
var url = 'http://localhost:8387/rest/resourcestatus.json';
$.getJSON(url+'?callback=?', function(data)
{
//data is
/*{
"groupStatus":
[
{"id":"AL Process","time":1332755316976,"level":0,"warningIds":[],"errorIds":[]},
{"id":"AL:instance1","time":1332919465317,"level":0,"warningIds":[],"errorIds":[]},
{"id":"AL:instance2","time":1332919465317,"level":1,"warningIds":["documentarea.locked"],"errorIds":[]},
{"id":"SL","time":1331208543687,"level":0,"warningIds":[],"errorIds":[]}
]
}*/
});
on the server side you will need to wrap the response into a JavaScript function: response = Request["callback"] +"("+ response+")";
the result will look like this:
?({"groupStatus":[{"id":"AL ....})
So the browser will actually load a valid java script code.
The callback function of $.getJSON contains the result of the AJAX call in it's argument.
$.getJSON('http://localhost:8387/rest/resourcestatus.json', function(data) {
$(data.groupStatus).each(function() {
// do something with $(this).id
});
});
I want to encrypt some data in a form using jQuery before it's sent to the server, it can be a MD5 hash. It is a small project, so I don't really need to use SSL.
I have the following JavaScript code where I use $.md5 in the password confirmation info:
$(document).ready(function() {
var dataToSend = {};
dataToSend['action'] = 'signup';
dataToSend['name'] = name.val();
dataToSend['email'] = email.val();
dataToSend['confsenha'] = $.md5(pass2.val());
var options = {
target: '#error',
url: 'insert.php',
beforeSubmit: validate,
data: dataToSend,
success: function(resposta) {
$('#message').html(resposta);
}
};
$('#customForm').ajaxForm(options);
});
The problem is that the data is being duplicated. I tought that overwriting the data being sent by using the var dataToSend would make ajaxForm send only data in that map. But besides sending data from dataToSend, it also sends data from the form, so what I wanted to encrypt using MD5 appears both encrypted and clean. This is an example of what goes in the request:
usuario=user&email=user%40email.com&senha=12345&confsenha=12345&send=&action=signup&name=user&email=user%40email.com&confsenha=d41d8cd98f00b204e9800998ecf8427e
I know I have to define the a function beforeSerialize, but I don't know how to manipulate form data. Can anyone tell me how to do that?
As per the documentation on the plugin site:
data
An object containing extra data that should be submitted
along with the form.
The word along is the crux.
So when you pass data as a part of the options object that data is serialized and is sent along with any data/input elements values that are part of a form.
A better approach would be to hash the password value and assign it to the same field or another hidden field in the beforeSubmit handler(in your case the validate function) and remove the dataToSend object totally.
Something like:
Without any hidden element:
function validate(){
//Other Code
pass2.val($.md5(pass2.val()));
}
With a hidden element in the form:
function validate(){
//Other Code
$("#hdnPass").val($.md5(pass2.val()));
pass2.val("");
}