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
Related
cuIzgaraKay is a javascript code I want to use it in sql command as cuIzgaraKay.id(it gets the value correctly I checked it). However, I could not it. I googled it but I can't find what I search . How can i do it ? sorry for asking syntax error but I can't find it maybe ı have logical error
if(cuIzgaraKay){
<?php
include_once('../phps/kutuphane/inc.php');
$result = mysql_query("select id from bolge_db where parent_id="?>+ cuIzgaraKay.id + <?);
As far as I can tell, you're trying to execute an SQL query from the PHP page, using data from the Javascript code you're generating.
The Javascript is only evaluated on the client side of your page. That means that the server-side cannot know anything about the Javascript code.
What you need to do, is to generate the ID, and communicate it to the PHP backend, for example with a HTTP POST/GET request or something.
EDIT:
If you're new to Javascript, I'd suggest you look into the native JS object XMLHttpRequest. You use it like this:
/*
params:
url: relative URL on host, e.g. '/users/morten/data'
method: GET, POST, PUT, DELETE, HEAD or OPTIONS
data: data to send with request, e.g. POST form-data
ok_cb: function to call on success
fail_db: function to call on failure
*/
function http_req(url, method, data, ok_cb, fail_cb) {
var client = new XMLHttpRequest();
client.onreadystatechange = function () {
if(client.readyState == this.DONE) {
if(client.status == 200 || client.status == 302 || client.status == 304)
ok_cb(...);
else
fail_cb(...);
}
};
client.open(method, url, true);
client.send(data);
}
Or you can use jQuery or a ton of other frameworks to do the same thing.
EDIT:
what is method in there how can i write there and how can i get data from php – user1702486
The method is whatever HTTP request method you want to use. See the wikipedia page for more info: http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods
This code will POST to /page.php sending a data-string along.
If the request returns a successful code, the ok-callback will be called.
// handle HTTP OK
var ok = function(meth, res, url) {
console.log("OK: got " + res);
}
// handle all else
var fail = function(meth, res, url) {
console.log("UTTER UTTER FAILURE!\n" + res);
}
// make a HTTP POST to server/page.php sending the data along
// you can serialize the data and use XML or JSON or whatever instead
http_req("/page.php", "POST", "username=usr&password=passw&userid=12345", ok, fail);
On the PHP page, you will need to handle the POST by checking the data and returning an answer if appropriate. Something like this:
<?php
if (empty($_POST))
{
print_r($_POST);
...
// do something with the data and print something back
}
?>
If you've posted "data1=1234&data2=5678&str=hello%20mum" the $_POST array will look like this:
(
[data1] => 1234
[data2] => 5678
[str] => "hello%20mum"
)
You can't, javascript is client side and php is server side. So the php code gets executed before the javascript.
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
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.
Users of my website will, ideally, be sending a few hundred posts to a db server over the course of about an hour (basically its an online-experiment). The experiment is implemented in js, so I'm trying to use an XMLHttpRequest object to post the data the script collects.
The thing I'm uncertain about is how to use the POST parameter. I want to set about 8 different key/value pairs to the $_POST variable so it can be accessible to a .php page for processing before sent to the db server. I'm not interested in retrieving any information from the server itself, only sending it (which is why, and I'm not sure whether it's the correct approach, I'm setting the readyState conditional to '1'/open).
Here's the script I'm working with at the moment:
function postData(dataList) {
var xmlhttp = new XMLHttpRequest();
var processingUrl = "process_exercise_data.php";
var POSTBody = "";
POSTBody+="block_type="+encodeURIComponent(dataList[0]);
POSTBody+="&block_number="+encodeURIComponent(dataList[1]);
POSTBody+="&trial_type="+encodeURIComponent(dataList[2]);
POSTBody+="&trial_number="+encodeURIComponent(dataList[3]);
POSTBody+="&input_value="+encodeURIComponent(dataList[4]);
POSTBody+="&output_value="+encodeURIComponent(dataList[5]);
POSTBody+="&prediction_value="+encodeURIComponent(dataList[6]);
POSTBody+="&error="+encodeURIComponent(dataList[7]);
xmlhttp.open("POST",processingUrl,true);
if (xmlhttp.readyState==4) {
xmlhttp.send(POSTBody);
}
}
The main goal is to send the key/value pairs to the .php page using POST while remaining on the current page(simple AJAX request, if I'm not mistaken). Any comments or suggestions are very appreciated!
Remember, all I'm trying to accomplish is having the user, when he/she acts in a certain way under a certain condition (outside of the scope of this function), to call this function and POST this data to the server. A server response text isn't needed.
EDIT:
Now my question is this: Will I still be able to access the $_POST array in at the processing php page? Here's an example:
$block_type = $_POST['block.type'];
You don't want to set request headers. What you want is to send request body along. And the body should be like
'block_type='+encodeURIComponent(dataList[0])+'&block_number='+encodeURIComponent(dataList[1])
etc. Guess you got the idea. Body is what you pass to the send() method of XMLHTTPRequest object.
Consider using jQuery, it will make your task so much easier. Using the jQuery.post method you only have to provide the data hash, you don't have to worry about serialization, correct escaping or readyState.
You must call send before readyState will change.
Replace
xmlhttp.open("POST",processingUrl,true);
if (xmlhttp.readyState=4) {
xmlhttp.send(POSTBody);
}
with
xmlhttp.open("POST", processingUrl, false);
xmlhttp.send(POSTBody);
If you want to handle a response, add define xmlhttp.onreadystatechange:
xmlhttp.open("POST", processingUrl, false);
xmlhttp.onreadystatechange = function () {
if (this.readyState === 4) {
// handle response
}
};
xmlhttp.send(POSTBody);
Edit: I would also like to mention that = is not the JavaScript equality operator, it's the assignment operator. Use === for equality checking and == for type-converting equality checking.
I have a set of links dynamically generated in a table. Each of the rows has a unique "id" property on it's tag. The goal is to get XMLHTTPRequest to tell the page 'deletepost.php' which record to remove from an outside database.
It changes a hidden input value to the value of the row (a number), and then submits that form
<script type="text/javascript">
var http = false ;
// instance the request object!!!!
if(navigator.appName == "Microsoft Internet Explorer") {
http = new ActiveXObject("Microsoft.XMLHTTP");
} else {
http = new XMLHttpRequest();
}
/////////////////////////////////////////////////
function rdel(num) {
document.getElementById("pid_to_del").value = num;
//this element is a hidden <input> tag. this line changes the value.
http.open("POST", "deletepost.php", true); //this _SHOULD_ post the form
http.onreadystatechange = function() {
if(http.readyState == 4) {
$("tr#r" + num).fadeOut("slow"); // jquery fadeout animation
alert(http.responseText); // this alerts whatever deletepost.php says
}
}
http.send(null);
}
</script>
This function rdel() is called by one of the links, which looks like this:
delete
This is what deletepost.php looks like:
<?php
print_r($_POST);
?>
The page that makes the request alerts:
Array
(
)
An empty array. :( Why?!
Two things here, the first is that you actually have to put your post string (very similar to a query string) into the
http.send(null);
call. So you would do:
http.send('field1=value1')
Secondly, in order for to actually notify the server that there are values being posted, you must set the content type for your request using:
http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
Hope that helps
EDIT:
I see now that you are trying to use this request to sent a serialized copy of an html form to the server asynchronously. Javascript does not contain the functionality to do this, but certain libraries and plugins (such as JQuery and AjaxForm) do.
For your example, however, you should be able to accomplish this using:
http.send('pid_to_del=' + pid);
The quickest fix would be:
where you open the XMLHttpRequest object:
http.open("POST", "deletepost.php", true)
change the url to be "deletepost.php?number="+num
then in you php page change the POST to a GET.
$number = $_GET['number']
POST allows you to send large amounts of parameters/options around but unless your numbers are going to be more than 140 characters long, this will make no difference. There appears to be a common mis-conception that POST is more secure than GET, simply because it seems more obvious how to get a browser to manipulate the post variable. However, it is a very very small stretch to do the same thing with POST variables so security should not depend on POSTing rather than GETting. There's nothing wrong with using POST except that you don't seem to be able to get it to work easily. I would never do this directly in javascript. I would always use something like jquery. You could replace the whole script with the following and it would work in most browsers:
function rdel(num) {
$.post("/webroot/deletepost.php", {number: num},
function(dat){
$("tr#r" + num).fadeOut("slow"); // jquery fadeout animation
alert(dat.responseText); // this alerts whatever deletepost.php
});
}
by the way, in your selector $('tr#r'+num), the tr is unnecessary since the id's on a page are unique so the result will be the same as $('#r'+num) but would take longer to calculate the selector. Reference by id is the fastest, the former finds all tr tags and then finds the id within that collection, rather than using the 'native' getElementById function by just using id in the selector. In short, don't make jquery do anything you don't need it to do ;)