Javascript get form value in URL without jQuery - php

If data is submitted via POST through the classic HTML form method is it possible to access those values using standard Javascript without libraries? How would this be done?
Edit for clarity: The variables have been posted. I am trying to access those values via javascript.

Thinking outside the box: (A hack that should never see the light of day)
For this example the posted variable is "a":
var val=document.URL;
var start;
start = val.search(/a=/);
var end;
end = val.search(/&/);
var thispos = val.substring(start+2,end);
document.URL returns the url of the current site.
val.search returns the position of the first occurrence of the regular expression in
the parameter field.
substring the two and...
thispos now contains the posted variable.
Brutal but functional. Is this too terrible to be an answer?

use:
var myField = document.getElementById('myFieldId');
then myField.value will contain the value.

If you have submitted the page, then you have to get the form data using PHP.
Here is a tutorial that should help: http://www.phpf1.com/tutorial/php-form.html
But if you decide to test jQuery, you can use this:
jQuery('#submit').live('click', function()
{
var form_data = jQuery("#data_form").serialize();
//Save data
jQuery.ajax({
url: siteURL +"/path/to/php/file/jquery.php",
data: {formData : form_data,
success: (function(data) {
//data is whatever you return from jquery.php
//I use json for return data
alert('Data has been saved');
}),
dataType: 'json'
});

After a post, the data is send to the server, javascript cant do anything with that since its client side. What you can do is pre-check with document.getElementById('formid') and use those values in the form. After validating or doing what you want to do, end with form.submit() to really send it to the server.

function getUrlInfo() {
var data = window.location.search.substring(1).split("&");
//returns an array of strings containing the params and their values
// data = [ "param=value","param=value","param=value"]
var params1Array = data[0].substring(0).split("=");
//Splits the first string element at the "=" symbol and
//returns an array with the param and value
//param1Array = ["param","value"]
var param1Value = param1Array[1].replace("+", " ");
//Gets the value from the second element in the param1Array
//Replaces the spaces, if any, in the second element,
//which is the value of the url param
var param2Array = data[1].substring(0).split("=");
//Repeat steps for the second param element,in the url params data array
var param2Value= param2Array[1].replace("+", " ");
return {
param1Value,
param2Value
}
};

The submitted data (either POST or GET) is proccesed on the server side. Javascript runs on the client-side so you can't access the variables from the page receiving the form request.
But you can access them before the post using the input field id (specially to check the input values before sending them).

Related

Passing JavaScript array using AJAX

I'm very new to ajax and I'm trying to pass an array that I have created in javascript called markers over to a PHP page when the user clicks the submit button. At the time of submission the array exists and is within scope. The code below is what is trying to do that. When I click the submit button I get sent to the php page and "failed" is printed (part of my code) meaning the array was not passed. I believe the error occurs in the ajax code and I'm not sure where it is coming from, any help is greatly appreciated!
The javascript/ajax stuff:
function submit_tour(){
var input = JSON.stringify(markers);
//var input = $(this).serialize();
var sent = $.ajax({
type: "POST",
data: input,
dataType: 'JSON',
url: "test_portal2.php"
}).done(function() {window.alert("done");})
.fail(function() {window.alert("failed");});
window.alert("" + input);
}
The HTML button that is supposed to send the array:
<form name="toursubmit" action="test_portal2.php" onsubmit="submit_tour()">
<input type="submit" value="Submit">
</form>
The PHP that catches it (in the test_portal.php file):
$ans = json_decode($sent);
echo $ans;
if ($ans != NULL){
echo "works";
echo $ans;
}
else {
echo 'failed';
}
A couple of things to point out.
First, you need to prevent the default POST action within your submit_tour() function, otherwise the synchronous POST will happen.
Second, you need to specify the contentType value in your AJAX call as application/json.
Third, if you are actually POSTing JSON to PHP and using application/json as the ContentType, then you will need to get the JSON data in PHP by accessing the raw input like this:
$json = file_get_contents('php://input');
$obj = json_decode($json);
This is because $_POST is only auto-generated for form-encoded content types.
When you send
var input = JSON.stringify(markers);
And markers has no value
<input type="hidden" id="markers" name="markers"> // No value anywhere
Then it will surely be Null :)
Also do you populate your $sent variable from a value in $_POST ? don't see that happening
You don't need this in a form tag. The code is submitting the form and not running the JS.
Remove the form tag, or put this: submit_tour(); in onsubmit on the form instead, and return false.

calling php and javascript functions with one button

This is what I'm trying to achieve, but my Googling hasn't helped:
I have a button that adds a new row to a table dynamically. I also add a select component to a cell with the same action all in javascript. I'd like for that select component to populate with values from a sql select statement. Of course I don't want to define the connection to the DB in the JavaScript. So I was wondering if there was a way I could call a PHP function to retrieve the values then store it in variable within JavaScript.
PS I understand that PHP is server side as opposed to JS. But surely this is possible.
here's a simple implementation of such a thing using jQuery's ajax and php.
html
<select data-source-url="/category/list"></select>
javascript using jQuery
$("select[data-source-url]").each(function(){
var url = $(this).attr("data-source-url");
var el = $(this);
$.get(url, function(data){
for (i=0;i<data.length;i++){
el.append("<option>" + data[i] + "</option>");
}
},"json");
});
category/list endpoint (a php script)
$list = array();
$list[0] = "category 1";
$list[1] = "category 2";
$list[2] = "category 3";
$list[3] = "category 4";
$list[4] = "category 5";
echo json_encode($list);
a little explanation: what happens is a request being made via the JavaScript client to a php script, which returns an array of values in JSON (which is basically a javascript data-structure), those values are added to the select box dynamically.
Please note that on initial load of the page, the select box will be empty.
yes ofcourse you can. for storing s php variable in a js ariable you can do like this.
before storing it into js variable store the required value in your php variable
var value = '<?php echo $value;?>';
Javascript cannot connect directly to a database.
You want AJAX. A basic flow for this functionality looks like this.
Create a PHP script that connects to the database and gets the options for your select element (let's call it options.php). This script should fetch the options from the database and output them as a JSON array.
In your javascript, you would create an ajax request to options.php. With the JSON data returned from that script, you would loop over each element and create and append a corresponding option element to the dom inside of your select element.
Also consider using jQuery. It greatly simplifies ajax and provides a cross-browser solution.
Option 1
Pass a php array with all possible values to the client side using something like this on the client side:
var opt_values = [<?php echo $php_values; ?>]; //javascript array
or
var opt_values = <?php echo json_encode($php_values); ?>; //json object
Option 2
Another way is making an ajax request. Write a php function that return a JSON object and then you can manipulate the result using jQuery ajax method:
PHP function:
$json = array();
$result = mysqli_query ($connection, $query);
while($row = mysqli_fetch_array ($result))
{
$bus = array(
'id' => $row['id'],
'text' => $row['name']
);
array_push($json, $bus);
}
return = json_encode($json)
Jquery
$('#button-id').click(function(){
//adds a new row to a table dynamically
$.ajax({
type: "get",
dataType: "json",
url: "/get_values.php",
success: function (response) {
var $el = $("#myselect"); //get the select
$el.empty(); // remove old options
//Append the new values
$.each(response, function(key, value) {
$el.append($("<option></option>")
.attr("value", value.id).text(value.text));
});
}
});
});
Just thought i'd put it out there since w3schools is my friend and i kinda follow what they're saying in this post.
W3Schools PHP & AJAX communication

Jquery set PHP $_GET array

Greetings Stackoverflow
How do I set the php $_GET[] array from Jquery? I have a string looking simmilar to this: $sample_string = "Hi there, this text contains space and the character: &";. I also have a variable containing the name of the destination: $saveAs = "SomeVariable";. In PHP it would look following: $_GET["$SomeVariable"] = $sample_string;.
How do I do this in Jquery?
Thanks in advance, Rasmus
If you're using jQuery, you'll have to set up an AJAX request on the client side that sends a GET request to the server. You can then pull the data you supplied in the request from the $_GET[] array on the server side.
$(function() {
var data = {
sample_string: "hi",
saveAs: "something"
};
$.get('/path/to/script.php', data, function(response) {
alert(response); // should alert "some response"
});
});
And in script.php:
<?php
$sample = $_GET['sample_string']; // == "hi"
$saveAs = $_GET['saveAs']; // == "something"
// do work
echo "some response";
?>
Can't tell if you're looking to grab a GET param from javascript or set a GET param from jQuery. If it's the former, I like to use this code (stolen a while back from I can't remember where):
var urlParams = {};
(function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
Then you can call
var cake = urlParams['cake'];
To get the $_GET param specified by http://someurl.com?cake=delicious
If you want to send a $_GET parameter, you can use either jQuery's $.get() or $.ajax() functions. The $.get function is more straightforward and there's documentation on it here http://api.jquery.com/jQuery.get/
For $.ajax you would do something like this:
var trickystring = "Hi there, this text contains space and the character: &";
$.ajax({
url:'path/to/your/php/script.php',
data: {
'getParam1':trickystring,
'getParam2':'pie!'
},
type:'GET'
});
Now in PHP you should be able to get these by:
$trickystring = $_GET['getParam1'];
$pie = $_GET['getParam2'];
Hope these examples GET what you're looking for. (Get it?)
if $sample_string is what you want in jquery, you can do
var sample_str = '<?php echo $sample_string; ?>'; and then use the js variable sample_str wherever you want.
Now, if you want to do set $_GET in jquery, an ajax function would be way to go.
$.ajax({
url:'path/to/your/php_script.php',
data: {
'param1': 'pqr',
'param2': 'abc'
},
type:'GET'
});
Do you mean that would look like $_GET[$saveAs] = $sample_string y think.
$_GET is a variable for sending information from a page to another by URL. Its nosense to do it in jQuery that is not server side. If you want to dynamically set the $_GET variable to send it to another page you must include it in the URL like:
/index.php?'+javascriptVariable_name+'='+javascriptVariable_value+';
$_GET is just a URL parameter. So you can access get like /index.php?id=1:
echo $_GET['id'];
Look at this article, it shows all the ways to load stuff with ajax:
http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/

How to unserialize a serialized array sent to the server using GET method with a jQuery Ajax call?

I'm trying to deserialize an array from an URL I've sent from a JQuery Ajax call to a PHP script in the server.
What I have done
I've been sending variables with values to the server successfully with jQuery Ajax this way:
// A simple text from an HTML element:
var price = $("#price option:selected").val();
// Yet another simple text:
var term1 = $('#term1').val();
Then I prepare the data to be sent via Ajax this way:
var data = 'price=' + price + '&term1=' + term1;
//if I alert it, I get this: price=priceString&term1=termString
And send it with jQuery Ajax like this:
$.ajax({
url: "script.php",
type: "GET",
data: data,
cache: false,
dataType:'html',
success: function (html) {
// Do something successful
}
});
Then I get it in the server this way:
$price = (isset($_GET['price'])) ? $_GET['price'] : null;
$term1 = (isset($_GET['term1'])) ? $_GET['term1'] : null;
And I'm able to use my variables easily as I need. However, I need to do this with an array.
Main question
Reading a lot, I've managed to learn the professional way to send an array to the server: serialize it! I've learnt this way to do it with jQuery:
var array_selected = [];
// This is used to get all options in a listbox, no problems here:
$('#SelectIt option:not(:selected), #SelectIt option:selected').each(function() {
array_selected.push({ name: $(this).val(), value: $(this).html().substring($(this).html().indexOf(' '))});
});
var array_serialized = jQuery.param(array_selected);
// If I alert this I get my array serialized successfully with in the form of number=string:
//Ex. 123=stringOne&321=StringTwo
This seems to be right. I add this to the data as before:
var data = 'price=' + price + '&' + array_selected + '&term1=' + term1;
//if I alert it, I get this: price=priceString&term1=termString&123=stringOne&321=StringTwo
How do I reconstruct (unserialize) my array in the server? I've tried the same as before:
$array_serialized = (isset($_GET['array_serialized'])) ? $_GET['array_serialized'] : null;
with no success! Any ideas why? How can I get my serialized array passed this way in the server as another array which PHP can handle so I can use it?
Or am I complicating my life myself needlessly? All I want is to send an array to the server.
If you name a variable with [] in the end of it, it will create an array out of the values passed with that name.
For example, http://www.example.com/?data[]=hello&data[]=world&data[]=test, will result in the array $_GET["data"] == array('hello', 'world', 'test'); created in PHP.
In the same way, you can create an associative array in PHP: http://www.example.com/?data[first]=foo&data[second]=bar will result in $_GET["data"] == array("first" => "foo", "second" => "bar");
BTW, you might be interested in using jQuery's .serialize() or .serializeArray(), if those fit your client side serializing needs.
I'm not too knowledgeable with PHP, but I think you may have overlooked something pretty simple, <?--php unserialize($string) ?>.

How to pick up JSON in PHP from Jeditable Script

I want to create a jeditable text area that posts the values entered in to a database and then returns the new value to the div that replaces the textarea. I found this on Stackoverflow that handles returning the new value to the div.
$(document).ready(function() {
$('.edit_area').editable(submitEdit, {
indicator : "Saving...",
tooltip : "Click to edit...",
type : "textarea",
submit : "OK",
cancel : "Cancel",
name : "Editable.FieldName",
id : "elementid",
});
function submitEdit(value, settings)
{
var edits = new Object();
var origvalue = this.revert;
var textbox = this;
var result = value;
edits[settings.name] = [value];
var returned = $.ajax({
url: "http://jimmymorris.co.uk/xmas/record_xmas_msg.php",
type: "POST",
data : edits,
dataType : "json",
complete : function (xhr, textStatus)
{
var response = $.secureEvalJSON(xhr.responseText);
if (response.Message != "")
{
alert(Message);
}
}
});
return(result);
}
});
My problems is I don't know what my POST vars are called so I can insert in to my db. Does it even return POST var to php or does it send php json and how do I know what that is called?
Please help, Cheers in advance.
What it sends to the server depends on what you supply to the "post" mamber of the $.ajax options paremeter.
If you pass a query string parementer data : "name=foo&surname=bar" The PHP script would recieve it in the $_POST variable and could be accessed by means of $_POST['name'] $_POST['surname']
However if you passed an object to the data parameter it would be changed to a query string i.e
data : {name : 'foo', surname : 'bar'},
JQuery.ajax would change it into a query string like the example above then It would be sent to the server, and the PHP script would also access it same as mentioned above.
P.S I highly recommend using some type of encoding when sending data to the server, encodeURIComponent(variable) and accordingly decode it in PHP by using urldecode.
You have the id posted which you can retrieve in the PHP page as $_POST['id']. The text is posted as value which you can retrieve in the PHP page as $_POST['value']. You can of course change the default names.

Categories