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.
Related
I have a form and an array containing some data. I am trying to post both these objects to my php script. The code I am using to post the form and array is shown below:
var json_data = JSON.stringify(data_vendor); //array to be posted
$.ajax({
url: '/crm/inventory/add_purchase_order.php',
type: 'POST',
data: {data_vendor:json_data,form_data:$("#purchase_orderform").serialize()},
dataType: 'json',
In the PHP script I am able to decode the array using the following :
$vendor_codes = json_decode($_POST["data_vendor"],true);
The form contains several fields/inputs one of which is called "order_quantity" . I am trying to retrieve this value using:
$order_quantity = $_POST["order_quantity"];
The data read shows up as NULL.
(i) Is the method used correct for posting multiple objects/strings correct?
(ii) Is the method used to retrieve the form inputs correct?
Usually when you use serialize() that is all you send because it is a urlencoded string. Then the form control names are available as keys in $_POST
But you currently only have 2 keys available to $_POST ... $_POST["data_vendor"] and $_POST["form_data"]
$_POST["form_data"] is a urlencoded string which you did with serialize() so it also needs to be decoded now manually
Try
$formData = urldecode($_POST["form_data"]);
$order_quantity = $formData ['order_quantity'];
To validate this just do a dump of $_POST["form_data"] and you will see that it is a string...not array
I have stored the returned data from a mysql query into a session variable. I can extract what I want from using $_SESSION['info'][][].
I would like to be able to retrieve values from the array dynamically. The user will select numbers from drop downs (2 of them). One of the numbers needs to passed to the first element of the array and obviously, the second goes to the second element. And then, the result is echoed to the screen.
I need to do this all client side. So like this:
Get result of keypress a
Store it as $a
Get the result of keypress b
Store it as $b
Pass the results of to echo $_SESSION['info'][$a][$b]
I can get one key stroke and pass it to a variable and even possible the second with my limited knowledge but pass them to the session variable and printing the result escapes me at the moment.
enter code here$(document).ready(function() {
$("#pcc").keyup(function() {
var dInput = $(this).val();
$n1=dInput;
//$(".dDimension:contains('" + dInput + "')").css("display","block");
});
});
$(document).ready(function() {
$("#pcp").keyup(function() {
var dInput = $(this).val();
$n2=dInput
//$(".dDimension:contains('" + dInput + "')").css("display","block");
});
});
I know I could probably nest that but one hurdle at a time. I know that saves the keystrokes. I have tested it by passing the values to alerts.
Progess at last. I am using this code to pass the variables from the input fields:
$(document).ready(function(){
$("#pcp").keyup(function(){
var value = $("#pcp").val();
n1= value;
});
$("#pcp").keyup(function(){
var value = $("#pcc").val();
n2= value;
matrix('n1','n2');
});
});
And I know its getting passed to matrix() because Im dumping the variables to console from within matrix like so:
function matrix(){
// getting values from key presses
//console.log(n1, n2);
$.ajax({
url: "matrix.php",
method: 'GET',
dataType: 'json',
data: { a: n1, b: n2 },
success: function(data) {
var response = data.response;
}
$_SESSION['arrayOfMatrix'][$a][$b]= response;
});
I also know that the variables have been passed because I was getting variable undefined errors in console and now I dont. So 2 positive things.
However, thats as far as seem to be able to go. I dont seem to be getting anything back. I have tried putting console.log inside of matrix.php but I dont get anything in that either so Im guessing its just not firing and sending data to matrix.php. Is there any other testing I can do to see where its failing? I feel that Im close to nailing it.
};
What you need is AJAX. You need to create a PHP script that will take two values for $a and $b through a GET or POST request. You can then use jQuery's $.ajax to asynchronously invoke that script and get the result.
So for a start you need a PHP script (let's call it for the sake of this example: example.php).
In example.php you can do something like this:
<?php
session_start();
$a = $_GET['var_a'];
$b = $_GET['var_b'];
//do some checking of the two above variables here
$response = array(
'response' => $_SESSION['info'][$a][$b];
);
echo json_encode($response);
You can substitude $_POST with $_GET if you prefer using a POST request instead.
The next step involves quite a bit of JavaScript so, when you have both $n1 and $n2 populated you can send a POST request using $.ajax:
$.ajax({
url: <path-to-example.php>,
method: 'get',
dataType: 'json'
data: { var_a: $n1, var_b: $n2 }
}).done(function(data){
var response = data.response;
//$_SESSION['info'][$a][$b] is now in response
});
Again you can substitute 'get' with 'post' in case of a POST request
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.
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 });
I'm trying to get the data returned from a page which is returning JSON to put itself into an array. This code works, however I can't put the variable (which should be the content) into the jQuery.parseJSON command. It works fine however when I use a ' ... ' string.
$.get( "server/php/index.php", function( data ) {
var data = jQuery.parseJSON(data);
});
If there is any other methods of doing this? What I'm trying to do is get the info from this page where it then puts itself into hidden input fields on a form.
Thanks in advance.
Don't pass the data into another variable called data. Call it something else and if you want to use it outside of your AJAX call then make sure you declare the variable elsewhere in your code so you can pass the data to it and use it.
var dataStorage;
$.get( "server/php/index.php", function( data ) {
dataStorage = jQuery.parseJSON(data);
});
Try removing the "var". Don't initialize data another time.
$.get( "server/php/index.php", function( data ) {
data = jQuery.parseJSON(data);
});