AJAX response returns current page - ajax

I was searching for a similar issue for a while now, but none of the solutions worked for me (and I couldn't find exactly the same issue).
First of all, the website I'm working on is running on Zend Framework. I suspect that it has something to do with the issue.
I want to make a pretty basic AJAX functionality, but for some reason my response always equals the html of the current page. I don't need any of Zend's functionality, the functions I need to implement could (and I'd prefer them to) work separately from the framework.
For testing purposes I made it as simple as I could and yet I fail to find the error. I have a page "test.php" which only has a link that triggers the ajax call. Here's how this call looks:
$('.quiz-link').click(function(e){
e.preventDefault();
$.ajax({
URL: "/quiz_api.php",
type: "POST",
cache: false,
data: {
'test': 'test'
},
success: function(resp){
console.log(resp);
},
error: function(resp){
console.log("Error: " + reps);
}
});
});
And this quiz_api.php is just:
<?php
echo "This is a test";
?>
When I click on the link I get the entire HTML of the current page. "This is a test" can't be found there. I'm also getting an error: "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/."
I reckon it has to do with the JS files that are included into this HTML response, but I've also tried setting "async: true" and it didn't help.
I would like to avoid using Zend Framework functions for this task, because I'm not well familiar with it and even making a simple controller sounds rather painful. Instead I want to find out what's causing such behavior and see if it can be changed.
PS: I've also tried moving quiz_api.php to another domain, but it didn't change anything.

I know that it might be an older code but it works, simple and very adaptable. Here's what I came up with. Hope it works for you.
//Here is the html
Link Test
<div id="test_div"></div>
function test(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// This is the php file link
var url = "quiz_api.php";
// Attaches the variables to the url ie:var1=1&var2=2 etc...
var vars = '';
hr.open("POST", url, true);
//Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange =
function(){
if(hr.readyState == 4 && hr.status == 200){
var return_data = hr.responseText;
console.log(return_data);
document.getElementById('test_div').innerHTML = return_data;
}else{
document.getElementById('test_div').innerHTML = "XMLHttpRequest failed";
}
}
//Send the data to PHP now... and wait for response to update the login_error div
hr.send(vars); // Actually execute the request
}
you can change the whole page with a document.write instead of changing individual "div"s

Related

Prestashop: How to submit data from adminpanel template to Admin Controller?

I'm trying to make a custom page in the adminpanel of Prestashop where the shopowner can fill in his upcoming events that will appear in a column in the header.tpl page. The templates and controller are working so far, with a structure based on an answer here at Stack Overflow:
How to create a new page in prestashop admin panel?
Now I have made in the content.tpl (with the added custom JavaScript and CSS files) the form with the input fields. The next step is to send it to the controller to save it in the database. But I'm stuck this part. I can't find how I can nicely submit the form to the controller. First I tried it with an Ajax function but I couldn't find the right way. Also without Ajax no success.
$.ajax({
type: 'POST',
headers: { "cache-control": "no-cache" },
url: baseUri + '?rand=' + new Date().getTime(),
async: true,
cache: false,
dataType : "json",
data:{
processEvents: true,
ajax: 'true',
controller: 'AdminEvents',
token: static_token
},
//success: function(jsonData){
//}
});
This is an example of an Ajax function that I tried. My questions:
How does other tpl or js files receive the baseUri, where is that
variable set?
What is the function of the ?rand date and time in that line? A kind
of security token?
What is the url of the controller? Also the url when I use
I guess the processEvents : true and Ajax : true is for security
reasons and to check if the form is submitted by Ajax or not?
Why is it necessary to send the controller name?
Where does the token come from?
Questions about the controller:
Which (Prestashop default functions) can or do need to use? For
example:
if (Tools::isSubmit('name')){
etc.
if (Tools::getValue('create_account')){
etc.
Can I use that functions anywhere or maybe only in an Init function?
A lot of questions, feel free to answer only a part of it, I just need a good push in the right direction, searching and reading in the online documentation and on the internet doesn't brought me the solution and brainwashed me a little.
EDIT:
I made a little progress by myself:
Where does the token come from?
What is the url of the controller? Also the url when I use
With the tools getAdminTokenLite and the controller name I generated the controller url:
$token = '?controller=AdminEvents&token='.Tools::getAdminTokenLite('AdminEvents');
The url to post to is the token plus the domain, admin directory and index.php.
With the tool getValue I get the POST data like in PHP with $_POST["name"].
Tools::getValue('event_name')
So its working but I guess it can be better with other Presta default tools.
I know that it's very late to answer you, but for sure it will help other mates with same problem.
Here is an example about how to implement ajax calls in Prestashop 1.6 on Admin panel using ANY Controller from BackOffice (if you want also, you can use ajax.php controller, but I'm using for this AdminImportController() )
tpl part:
$('#mybtn').click(function(e) {
var data = $('#datalist').val();
// Ajax call with secure token
$.post( "{$current|escape:'html':'UTF-8'}&token= {$token|escape:'html':'UTF-8'}",
{ ajax: true, action: "MyFunction", mydata: data } );
  });
And in admin controller side:
public function ajaxProcessMyFunction()
{
// Get param
$mydata = (int)Tools::getValue('mydata');
$answer = 0;
if( $mydata > 0 ) {
$this->importProfList = Db::getInstance()->executeS(
"SELECT * FROM .... LIMIT 1"
);
...
$answer = $someOperationResult;
}
// Response
die(Tools::jsonEncode(array(
'answer' => htmlspecialchars($answer)
)));
}
Tested and working like a charm.
Regards

Ajax send parameters through url

I'm new with ajax and thought i'd be a fun experiment to put into my project. I've created my own lightbox type feature to send a message on a website I'm creating. When the user clicks "Send Message", that's when the lightbox appears, and at the top I'm trying to get it to say "Send message to User", where User is the name of the user they're sending a message too. My lightbox html elements are actually on a seperate webpage, which is why I'm using ajax. this is what I have so far, and can't seem to figure out what the problem is:
user.php page
<div id = "pageMiddle"> // This div is where all the main content is.
<button onclick = "showMessageBox(UsersName)">Send Message</button>
</div>
Note: The username passes correctly into the javascript function, I have checked that much.
main.js page
function showMessageBox(user){
alert(user); // where i checked if username passes correctly
var ajaxObject = null;
if (window.XMLHttpRequest){
ajaxObject = new XMLHttpRequest();
}else if (window.ActiveXObject){
ajaxObject = new ActiveXObject("Microsoft.XMLHTTP");
}
if (ajaxObject != null){
ajaxObject.open("GET", "message_form.php", true);
ajaxObject.send("u="+user);
}else{
alert("You do not have a compatible browser");
}
ajaxObject.onreadystatechange = function(){
if (ajaxObject.readyState == 4 && ajaxObject.status == 200){
document.getElementById("ajaxResult").innerHTML = ajaxObject.responseText;
// use jquery to fade out the background and fade in the message box
$("#pageMiddle").fadeTo("slow", 0.2);
$("#messageFormFG").fadeIn("slow");
}
};
}
message_form.php page
<div id = "messageFormFG">
<div class = "messageFormTitle">Sending message to <?php echo $_GET['u']; ?></div>
</div>
Note: When accessing this page directly through the URL, giving it a parameter of u and a value, it displays correctly
Use jQuery.ajax();
http://api.jquery.com/jQuery.ajax/
$.ajax({
type: "GET",
url: "message_form.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
freakish way to do it (old school) :)
anyway i think the problem may be that you are loading an entire html page to a div! meaning tags and stuff, a good way to understand what's wrong would be to use a debugger and see what comes in ajaxObject.responseText.
Hope this helps.
Btw convert to jQuery ajax!! saves you loads of time =)
I believe that you need to add a request header prior to sending your data. So you'd have this:
ajaxObject.open("GET", "message_form.php", true);
ajaxObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxObject.send("u="+encodeURIComponent(user));
Instead of what you have.
However, it may be a good idea to allow a library to do this for you. It looks like you already have jQuery loaded, so why not let it handle your AJAX requests instead?
I figured it out after watching some ajax tutorials from bucky :) aka thenewboston. If I'm using the GET method, i just had to add the parameter to the end of the url in the .open function, instead of passing it through the send function (like you would a post method).
if you want to send number of field values using ajax.you can use serilalize function.
Example:
jQuery.ajax({
url: 'filenamehere.php',
type: 'post',
data: $("#formidhere").serialize(),
success: function(data){
..//
}
});

dynamicly fill table using zpt and ajax as update

I'm creating a webproject in pyramid where I'd like to update a table every few secondes. I already decided to use ajax, but I'm stuck on something.
On the client side I'm using the following code:
function update()
{
var variable = 'variable ';
$.ajax({
type: "POST",
url: "/diagnose_voorstel_get_data/${DosierID}",
dataType: "text",
data: variable ,
success: function (msg) {
alert(JSON.stringify(msg));
},
error: function(){
alert(msg + 'error');
}
});
}
Pyramid side:
#view_config(route_name='diagnose_voorstel_get_data', xhr=True, renderer='string')
def diagnose_voorstel_get_data(request):
dosierid = request.matchdict['dosierid']
dosieridsplit = dosierid.split
Diagnoses = DBSession.query(Diagnose).filter(and_(Diagnose.code_arg == str(dosieridsplit[0]), Diagnose.year_registr == str(dosieridsplit[1]), Diagnose.period_registr == str(dosieridsplit[2]), Diagnose.staynum == str(dosieridsplit[3]), Diagnose.order_spec == str(dosieridsplit[4])))
return {'Diagnoses ' : Diagnoses }
Now I want to put this data inside a table with zpt using the tal:repeat statement.
I know how to use put this data in the table when the page loads, but I don't know how to combine this with ajax.
Can anny1 help me with this problem ? thanks in adance.
You can do just about anything with AJAX, what do you mean "there's no possibility"? Things become much cleaner once you clearly see what runs where and in what order - as Martijn Pieters points out, there's no ZPT in the browser and there's no AJAX on the server, so the title of the question does not make much sense.
Some of the options are:
clent sends an AJAX request, server does its server-side stuff, in the AJAX call success handler the client reloads the whole page using something like window.location.search='ts=' + some_timestamp_to_invalidate_cache. The whole page will reload with the new data - although it works almost exactly like a normal form submit, not much sense using AJAX like this at all.
client sends an AJAX request, server returns an HTML fragment rendered with ZPT which client then appends to some element on your page in the AJAX success handler:
function update()
{
var variable = 'variable ';
$.post("/diagnose_voorstel_get_data/${DosierID}")
.done(function (data) {'
$('#mytable tbody').append(data);
});
}
client sends an AJAX request, server returns a JSON object which you then render on the client using one of the client-side templating engines. This probably only make sense if you render your whole application on the client and the server provides all data as JSON.

Codeigniter not detecting form on jQuery send

I'm going a little crazy here as I'm at a real loss for words what is happening. After a lot of digging around, I believe I am doing everything as should be.
Situation
I'm trying to send a user creation form to the server via AJAX and codeIgniter fails to even get past this part
if($this->input->post('blnAjax')) { // do something }
I have successfully incorporated the AJAX side of things in to the client as it fetches content from the server with very little problem. Here are some of the details involved in the call:
Ajax code
The ajax code is part of a much larger framework beyond the scope of this question but in terms of the actual call function, the event has event.preventDefault(); event.stopImmediatePropagation(); to stop it running off. The URL is reachable and the post values have been serialized with request type set to POST
requestpage: function(){
var strURL = params.strBaseURL + params.strRequestURL;
$.ajax({
type: params.strRequestMethod,
url: strURL,
data: params.strRequestParameters,
dataType: 'json',
success: function(json) {
methods.postrequestprocedure(json);
}
});
},
Ajax request
Everything runs smoothly on the client making the XMLHttpRequest with json as expected return. I don't even get to this point when the form has been submitted however. Codeigniter will never think the form has been set if using AJAX
Parameters application/x-www-form-urlencoded
blnAjax 1
user_login_name[] fred
user_login_name[] ted
user_name[] Fred Flintstone
user_name[] Ted bear
usergroup_id[] 16
usergroup_id[] 16
Controller
On the controller, with regard to the action, I have included alall code up to the point of fail. Please note that I have tested the other aspects of the code and they run fine
public function user_add() {
/* Include extra script files needed for form handling */
$this->view['aryScript'][] = 'jquery.validate.min';
$this->view['aryScript'][] = 'jquery.validate.additional-methods';
/* Include extra CSS files */
$this->view['aryCSS'][] = 'form';
/* First check if the user has correct access rights */
if($this->view['intAccessLevel'] < INT_SUPER_USER_ACCESS_LEVEL) {
$aryResponse['notifications'][] = array('strType' => 'permanent',
'strMessage' => 'Denied!');
}
/* Import extra libraries and helpers */
$this->load->library(array('PasswordHash'));
$this->load->model('UserAdminModel');
$this->view['strTitle'] = 'Add User';
$this->view['aryButtons']['user_add_another'] = array(
'strDisplay' => $this->lang->line('user_add_another')
'strURL' => '#',
'strID' => 'user_add_another',
'aryData' => array('action' => 'form-clone')
);
if($this->input->post('blnAjax')) {
echo 'Big sigh of relief';
Thank you kindly for taking the time to read my problem
The answer is never as simple as it seems! My client is using a CodeIgniter mod that rewrites the URI and thus dumping the data passed from the ajax query. It hadn't been a problem when performing gets and "real" POST queries.
So if you are ever using Wiredesignz - Language Identifier beware that it can affect your queries
How I fixed it, I use a custom page controller but the theory is the same:
Be sure that you have $this->config->item('language_abbr'); available to your javascript functions maybe through a constant or echo it directly in to the javascript if on the same page
Modify the URL before sending it with something similar to params.strBaseURL + params.strLanguage + '/' + params.strRequestURL;
You should now find things work just fine. I hope this helps and noone else has to spend a mini eternity to find this out

Cross-Domain Requests with jQuery

For a project I need to get the source code of web page of different other domains.
I have tried following code:
$('#container').load('http://google.com');
$.ajax({
url: 'http://news.bbc.co.uk',
type: 'GET',
success: function(res) {
var headline = $(res.responseText).find('a.tsh').text();
alert(headline);
}
});
Still I am not getting any results but just a blank alert box.
By default all browsers restrict cross-domain requests, you can get around this by using YQL as a proxy. See a guide here: http://ajaxian.com/archives/using-yql-as-a-proxy-for-cross-domain-ajax
For security reasons scripts aren't able to access content from other domains. Mozilla has a long article about HTTP access control, but the bottom line is that without the website themselves adding support for cross-domain requests, you're screwed.
This code is Working Perfectly with the help of JQuery and YQL
$(document).ready(function(){
var container = $('#target');
$('.ajaxtrigger').click(function(){
doAjax($(this).attr('href'));
return false;
});
function doAjax(url){
if(url.match('^http')){
$.getJSON("http://query.yahooapis.com/v1/public/yql?"+
"q=select%20*%20from%20html%20where%20url%3D%22"+
encodeURIComponent("http://www.yahoo.com")+
"%22&format=xml'&callback=?",
function(data){
if(data.results[0]){
var data = filterData(data.results[0]);
container.html(data);
} else {
var errormsg = '<p>Error: could not load the page.</p>';
container.html(errormsg);
}
}
);
} else {
$('#target').load(url);
}
}
function filterData(data){
data = data.replace(/<?\/body[^>]*>/g,'');
data = data.replace(/[\r|\n]+/g,'');
data = data.replace(/<--[\S\s]*?-->/g,'');
data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g,'');
data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g,'');
data = data.replace(/<script.*\/>/,'');
return data;
}
});
The solution for your case is JSON with padding or JSONP.
You will need an HTML element that specified for its src attribute a URL that returns JSON like this:
<script type="text/javascript" src="http://differentDomain.com/RetrieveUser?UserId=1234">
You can search online for a more in-depth explanation, but JSONP is definitely your solution for this.
Do the following steps.
1: Add datatype:jsonp to the script.
2: Add a "callback" parameter to the url
3: Create a javascript function with name same as "callback" param value.
4: The output can be received inside javascript function.
Found one more solution for this :
function getData(url){
if(url.match('^http')){
$.get(url,
function(data){
process(data);
}//end function(data)
);//end get
}
}
This is really a pretty easier way to handle cross-domain requests. As some of the sites like www.imdb.com rejects YQL requests.

Resources