Basically I have written an AJAX script using pure javascript and I have a script that basically takes in a HTTP GET REQUEST.
e.g. script.php?id=2
I want to use this id within javascript so it can be sent via AJAX to return data from my database.
How can I access the id value. It should be possible as the value should be present within the headers of the loaded page.
Thanks!
Have a look at the window.location object, the search property has the vales you're interested in.
This function will return an object which has all the variables as keys:
function queryVars() {
var q = window.location.search.slice(1).split(/&/g);
var ret = {};
for (i=0;i<q.length;i++) {
var item = q[i].split(/=/);
ret[item[0]]=item[1];
}
return ret;
}
From your page you could use it like this:
var myquery = queryVars();
window.alert(myquery.id);
This might be just what you're looking for:
http://www.netlobo.com/url_query_string_javascript.html
Related
I'm sending data to a php page for processing through jQuery and ajax and as result I will get
success: function(data){
mydata = data;
}
my data is an url that looks like mydata = https://myurl.com. Now I want to set mydata to a php variable and use it again inside another function in the main page, means: to set $url = mydata;.
How can I do that?
Thanks,
You can do that using Post via a from, GET via a query string
or you can use cookie like in this solution
how to assign javascript variable value to php variable
You can send the mydata variable to PHP by calling an XMLHttpRequest() via AJAX.
For example
var ajax = new XMLHttpRequest(); // Create new request
ajax.open("POST", "mainpage.php"); // Open the file where you want to send it with POST
ajax.send("mydata="+mydata); // Send mydata variable to PHP
Then in PHP you can check for the variable mydata
if(isset($_POST['mydata'])){
// do something
}
PHP scripts execute when you open a file and before everything else.
Ajax calls exectue when the Javascript is completely loaded. (After php).
So you cant do it.
could you give me more detail about what do you want to do?
I am using a codeigniter application that dynamically generates some html elements based on a database query returned from a function in my model.
In one of my views I use XMLHttpRequest to call a php function in one of my controllers which in turn gets data from my model in the form of a string and echos it for the responseText. My javascript code looks like this:
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST", "/controller/my_function", true);
var postStr = "name="+proposalName+"&data="+data;
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttp.send(postStr);
var response = xmlHttp.responseText;
The called function looks like this:
public function my_function(){
$data['name'] = $this->input->post('name');
$data['data'] = $this->input->post('data');
$string = $this->my_model->my_model_function($data);
echo $string;
}
The model returns the string correctly, and even after just echoing a random number or string in the function it still didn't get anything from the response text. No matter what i try to echo in the function there doesn't appear to be anything in the response text. What am i doing wrong here? How can I get the responseText to grab the correct value from my php function?
Edit: fixed a copying issue with postStr variable
var post Str = "name="+proposalName+"&data="+data;
That is a syntax error. The JavaScript falls over when it hits Str. The HTTP request is never sent.
Even if it was sent, you are making an asynchronous request (the third argument to open is true) so it doesn't lock up the entire page until the response is received. You would be reading xmlHttp.responseText before it was set by the response.
You need an onreadystatechange function.
See the MDN documentation for XMLHttpRequest which has examples.
Couple of major issues:
1) Your Javascript is not valid.
var post Str = "name="+proposalName+"&data="+data;
post Str has a space. This code wouldn't run regardless.
2) You really need to read up on how to use the XMLHttpRequest
Read this, it should help:
http://www.jibbering.com/2002/4/httprequest.html
I was able to pull the JSON data and put it into my HTML file as a script in my head. How do I gain access to this data? (put it into usable variables)
external json.php file (populated with mySQL data):
names:
[
{"firstName":"Kevin","lastName":"Guo"},
{"firstName":"Jun Sung","lastName":"Wong"},
{"firstName":"Anton","lastName":"Ansalmar"},
{"firstName":"Linda","lastName":"Wong"},
{"firstName":"George","lastName":"Costanza"}
]
my javascript code that pulls in the external json data:
var elm = document.createElement("script");
elm.setAttribute("type", "text/javascript");
elm.src = "http://totallyExternalURL.php";
elm.id="jsonTest";
console.log(elm);
document.getElementsByTagName('head')[0].appendChild(elm);
The entire json data is put as a script in my head, how can I pull all the firstnames/lastnames for display?
What you're doing is actually known as jsonp. Normally what you'd do is have the script return a script calling a function on your page with the data. You might find it easier to work with jQuery either using jsonp or, if calling a script on your own server, regular `json'.
function callback(data) {
... do something with the returned data
}
var elm = document.createElement("script");
elm.setAttribute("type", "text/javascript");
elm.src = "http://totallyExternalURL.php?callback=callback";
elm.id="jsonTest";
console.log(elm);
document.getElementsByTagName('head')[0].appendChild(elm);
Then have your external script return (note, your script should detect the value of the callback parameter and use that as the name of the function to invoke). The name of the function and the value of the callback parameter need to be the same.
callback( { "names" :
[
{"firstName":"Kevin","lastName":"Guo"},
{"firstName":"Jun Sung","lastName":"Wong"},
{"firstName":"Anton","lastName":"Ansalmar"},
{"firstName":"Linda","lastName":"Wong"},
{"firstName":"George","lastName":"Costanza"}
] });
Or with jQuery
$.getJSON( 'http://totallyExternalURL.php?callback=?', function(data) {
... do something with the data ...
});
Make the js returned as a function that returns the a javascript object that is the array and then you can make a call to that function and assign the return value to a variable.
So wrap the JSON in a function call.
Look up jsonp.
I'm using jQuery to load the result of a PHP script into a variable. The script is passed something that the user typed with a GET request. I want to take just what the script spit out into its <body> tag. Here's what I've tried:
JS:
function loader() {
var typed = $('#i').val(); //get what user typed in
$.get("script.php", {i: typed}, function(loaded) {dataloaded = loaded;});
alert($(dataloaded).find('body'))
}
But it just displays [Objec object]. How can I get a useful value that is just the contents of the body of a loaded page?
I know the PHP works, I just need the JS.
The script echos something like 1!!2 (two numbers separated by two exclamation points).
Thanks!
You are trying to access the dataloaded which might not be assigned due to the asynchronous nature of AJAX calls. The only safe place to access it is inside the success callback. Also you could use the .html() function to get the contents of the body tag:
function loader() {
var typed = $('#i').val(); //get what user typed in
$.get('script.php', { i: typed }, function(loaded) {
alert($(loaded).find('body').html());
});
}
Also note that if the script.php only echoes 1!!2 without a <body> tag it won't work.
Without knowing what console.log prints it is hard to say, but try these
alert($(dataloaded).find('body').html());
Or
alert($(dataloaded).find('body').text());
I changed the page that I'm trying to fetch to XML. I'm using $.find to get each element of interest individually from the XML page, which suits this particular app well.
This problem has disappeared, as there is no longer a head section to ignore, and I'm just grabbing individual XML elements anyway.
Thanks for all your time and help!
Use JSON type. I am not sure about whether your Jquery script correct or not but using JSON with a correct usage would solve problem. ie.:
function loader() {
var typed = $('#i').val(); //get what user typed in
$.get("script.php", {i: typed}, function(loaded) {dataloaded = loaded;},"json");
alert($(dataloaded).find('body'))
}
And POST variable from script.php after encoding JSON. Use Php's json_encode() function. You need to create variable as an array. For example:
<?php
$title = 'Hello World';
$content = 'Get well soon Japan!';
$arr=array('title'=>$title,'content'=>$content);
echo json_encode($arr);
?>
And Jquery would be something like:
function loader() {
var typed = $('#i').val(); //get what user typed in
$.get("script.php", {i: typed}, function(loaded) {var dataloaded = loaded.title+" "+loaded.content;},"json");
$("body").html(dataloaded);
}
You may need to use Jquery's parseJson() functions on some situations. Don't think you will need here.
I want to call a PHP file but want to pass an argument to the PHP file. Not getting the correct approach, I am attempting to write a cookie and read that cookie when the PHP file loads. But this is also not working. I am using following code to write and read cookie. I just want to test the read cookie function of JavaScript here. I know how to read the cookie value in PHP.
<script>
function SetRowInCookie(NewCookieValue)
{
try
{
alert(NewCookieValue);
document.cookie = 'row_id=' + NewCookieValue;
loadCookies();
}
catch(err)
{
alert(err.description);
}
}
function loadCookies() {
var cr = []; if (document.cookie != '') {
var ck = document.cookie.split('; ');
for (var i=ck.length - 1; i>= 0; i--) {
var cv = ck.split('=');
cr[ck[0]]=ck[1];
}
}
alert(cr['row_id']);
}
</script>
I'm not sure what in your code (running on the client's PC) you expect to cause the php script (running on the server) to run. You'll need to invoke the php by making some kind of http request (like get http://yoururl/recheckcookie.php). With at HTTP request, the javascript code on the client to queries the webserver for the output of your recheckcookie.php script. This script can then recheck the cookie, and return some/no output.
Look up XMLHttpRequest or preferably the corresponding JQuery to see how to perform the HTTP request.
Cookies are not the way to transfer variables between client and server. you should append key/variables pairs to your request URL using either a get (querystring) or post method.
jQuery ajax example;
$.get('http://www.myphpserver.com/script.php?row_id=' + NewCookieValue);
I think, you dont need cookies. try it with $.post, where you can define which url will be called, something like:
$.post(url, params, callback_function);
Well I'm not sure what it is you are ultimately trying to achieve but it sounds like using AJAX could be your solution. There is a good tutorial here.
AJAX will basically allow you to call a php script, pass it variables and then use it's output on your webpage.