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
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
openistrue) so it doesn’t lock up the entire page until the response is received. You would be readingxmlHttp.responseTextbefore it was set by the response.You need an
onreadystatechangefunction.See the MDN documentation for XMLHttpRequest which has examples.