Ajax send parameters through url - ajax

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){
..//
}
});

Related

AJAX response returns current page

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

Magento add to wishlist via ajax is not working with secure url (SSL installed)

I am using magento add to wishlist via ajax
it's working fine but after install SSL on server and make secure magento checkout pages from admin.
It give me not any response from ajax (302 Found).
But if i open this url in new tab then it's working fine.
When i use https in request url then it gives me the following html response "Reload the page to get source for: REQUEST URL" and without https there is no response to display.
here below the code which i used for :-
function additemtowishlist(wId,pId)
{
var wishlisturl = 'wishlist/index/ajaxadd/product/'+pId;
var wishlistparam = '/?wishlist_id='+wId;
var url = '<?php echo Mage::getUrl("",array('_secure'=>false))?>'+wishlisturl+wishlistparam;
new Ajax.Request(url, {
dataType: "json",
onSuccess: function(response){
if (typeof(response.responseText) == 'string') eval('data = ' + response.responseText);
if (typeof data.product_id != 'undefined') {
var htmltoshow = '<div class="messages successmessage"><div class="success-msg"><span>'+data.message+'</div></div>';
jQuery("#wishlistresulthome-"+data.product_id).html(htmltoshow);
jQuery("#customwishlist-"+data.product_id).css('visibility','hidden');
}
else {
alert(Translator.translate('Error happened while creating wishlist. Please try again later'));
}
}
});
}
Thanks in advance.
Hello Simranjeet you may try this :-
function additemtowishlist(wId,pId)
{
var wishlisturl = 'wishlist/index/ajaxadd/product/'+pId;
var wishlistparam = '/?wishlist_id='+wId;
var url = '<?php echo Mage::getUrl("",array('_secure'=>false))?>wishlist/index/ajaxadd/product/';
new Ajax.Request(url, {
method: 'post',
parameters: {'wishlist_id':wId,'product_id':pId },
onSuccess: function(response){
if (typeof(response.responseText) == 'string') eval('data = ' + response.responseText);
if (typeof data.product_id != 'undefined') {
var htmltoshow = '<div class="messages successmessage"><div class="success-msg"><span>'+data.message+'</div></div>';
jQuery("#wishlistresulthome-"+data.product_id).html(htmltoshow);
jQuery("#customwishlist-"+data.product_id).css('visibility','hidden');
}
else {
alert(Translator.translate('Error happened while creating wishlist. Please try again later'));
}
}
});
}
I discovered that ajaxToCart has ssl functionality built into it, but if the theme developer was lazy they may have neglected to include the code that tells ajaxToCart that ssl is enabled. I found it in the following code from ajax_cart_super.js.
function ajaxToCart(url,data,mine) {
var using_ssl = $jq('.using_ssl').attr('value');
if(using_ssl==1) {
url = url.replace("http://", "https://");
}
..
..
}
As you can see, ajaxToCart will replace the http with https, but only if there is an element with the class using_ssl and value=1. The developer who made my theme didn't include that element, so when the ajax request points to an unsecure page that should be secure, the ajax response won't work in jquery.
So for me, the quick fix was to just add this element onto my pages. I know this site will always have ssl enabled so I simply hard coded it into my template as shown below.
<input type="hidden" class="using_ssl" value="1" />
Once that was there, the javascript picked up the value and did the replacement. So now it works fine for me by just adding that into the template. If you are a theme developer and you want users to be able to switch this on and off, you may want to check against the settings in the admin. Although you may be on an insecure page, it will tell you if ssl is enabled in the backend, which would require this fix to be added.
I haven't tested the following but I think it would look something like this...
if(Mage::app()->getStore()->isCurrentlySecure()){
echo '<input type="hidden" class="using_ssl" value="1" />';
}
BTW, after years of appreciating stackoverflow solutions, I am making my first post here. Thanks to all contributors, the help is great and I'll try to pay it back now. :)
Try update your javascript url variable, by setting _secure to true value.
please try with below with your wishlist url just change instead of my custom action
Mage::getUrl('',array('_secure'=>true))
I think that gets you the base secure url, I believe.
Mage::getUrl('customer/account/login',array('_secure'=>true))
Will get you to the login page. In other words,
Mage::getUrl('module/controller/action',array('_secure'=>true))

My ajax request isn't working

I have an <ul id="keuze_lijst"> , an input field with id #sykje and an button with class .search .
Now when i press the button i would like to clear the UL and repopulate it with data, for this i currently got this .js file.
$(document).ready(function() {
$(".search").click(function(){
var searchValue = $("#sykje").val();
$("#keuze_lijst").empty();
$.ajax({
url: 'http://www.autive.nl/frysk/simulator/sim.php?action=getSongs&search='+searchValue,
data: "",
dataType: 'json',
success: function(rows) {
for(var i in rows){
var row = rows[i];
var id = row[1];
var titel = row[2];
var artiest = row[9];
$("#keuze_lijst").append("<li class='mag_droppen'>"+
"<div class='song_left'>"+
"<div class='titel'>"+titel+"</div>"+
"<div class='artiest'>"+artiest+"</div>"+
"</div><!-- .song_left -->"+
"</li>");
}
}
});
});
});
When i remove the ajax command and put something like $("#keuze_lijst").html("hello"); it works fine. But the ajax command isn't working. Though the var searchValue does his work. (ajax uses the correct url). And when i enter that url the page echoes an fine json with multiple rows.
But in my page the ajax script isn't adding the <li>.
What am i doing wrong?
edit: added an jsfiddle -> http://jsfiddle.net/TVvKb/1/
.html() totally replaces the HTML. So at the end, your "#keuze_list will contain </li>.
Just execute one html() command after you build your html into a string var or something.
From a quick glance, I can say that the problem might be with your use of the html() function. This actually replaces the entire html content.
You might want to try using append() or prepend().
Possible Problems:
You are running into a Same Origin Problem. Per default you can only make Ajax-Requests to your own domain. If you need to make cross-domain calls use JSONP or CORS.
Use the html() only once, and hand over your complete string, otherwise you will override your previous html all the time.
You are not landing in the success handler due to an error (e.g. invalid JSON).
Not sure, but I think if you insert a string in the .append() and other jQuery methods, it parses to (valid) HTML first. That means that unclosed tags are closed, making your HTML invalid.
$('<div />'); // parses to <div></div>
So, I assume that your DOM ends up like this this:
$('ul').append('<li>').append('foo').append('</li>'); // <ul><li></li>foo</li></ul>
Please, just format your string first. You don't want jQuery to parse every input.
var str = '<li>';
str += 'foo';
str += '</li>';
$('ul').html(str);
For cross-domain AJAX requests (without JSONP):
proxy.php
header('Content-Type: application/json');
if(empty($_GET['search'])) exit;
$url = 'http://www.autive.nl/frysk/simulator/sim.php?action=getSongs&search=' . $_GET['search'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_exec($ch);
curl_close($ch);
Javascript
$.getJSON({
url: 'proxy.php&search='+searchValue,
success: callback
});

How can I return an id value from a div already populated through ajax

I am having some difficulty passing a correct id function back to AJAX.
I'm creating a product bulletin generator that lets items to be added by their SKU code (which works fine). My problem is that when a bulletin is clicked on, a preview of that bulletin is loaded into a div and shows all products associated with that bulletin.
From inside those results, I am trying to add the ability to delete a product from the bulletin. The problem is that the value being passed back to AJAX belongs to the first product only. It won't send the value belonging to the particular item if it is any other item than the first one.
This is the code (belonging to main.php) that gets loaded via AJAX into a div and is looped with each product associated with a selected bulletin
echo "<form name='myDelForm'>
$news_gen_id<br>
<input type='hidden' id='delccode' value='".$news_gen_id."'>
<input type='hidden' id='deledit' value='".$edit."'>
<input type='button' onclick='ajaxDelCcode()' value='Delete' /><br></form>
</td>";
The AJAX code (on index.php, where the div that calls in main.php is also located) is this
function ajaxDelCcode(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new
ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById("ajaxMain2");
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var deledit = document.getElementById("deledit").value;
var delccode = document.getElementById("delccode").value;
var queryString = "?delccode=" + delccode + "&deledit=" + deledit;
ajaxRequest.open("GET", "main.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
Currently, using those two pieces of code, I can successfully delete only the first product. The delccode variables do not seem to change when the products are looped (although when I echo the variables during the loop, it is definitely changing to the appropriate value...it's just not passing it correctly back to AJAX.)
I tried taking the AJAX code, putting it inside the main.php product loop, and change the function name during each loop (so ajaxDelCcode$news_gen_id() for example) and also to the button itself so that it is calling the AJAX specific to it. And it works if you are visiting main.php directly...but not from index.php after main.php has been called into the div.
I can't figure out how to pass the correct looped value from main.php within the div, back to the AJAX code on index.php
Can anyone help me with this?
Thanks,
Dustin
Instead of storing the id in the input, just pass it as an argument to the function:
function ajaxDelCcode(delccode) { ...
<input type='button' onclick='ajaxDelCcode(\"".$news_gen_id."\")' value='Delete' />
Also, I'd swap the quotes if I were you. Or better yet, instead of using echo, break the PHP code and just write HTML:
<? ... ?><input type="button" onclick="ajaxDelCcode('<?= $news_gen_id ?>')" value="Delete" /><? ... ?>
What does the code you use to delete look like? Is it in the same php file as the form you posted above? If so, is the form getting submitted to itself accidentally? Like perhaps when a user presses enter while on an input type=text control? I understand that you want to do this by ajax but I am suspecting that the form is your problem.
Seconding the jQuery comment.
Here try this
1) add jquery to your document.
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
2) give your inputs name attributes
<input type='hidden' name='delcode' id='delccode' value='".$news_gen_id."'>
<input type='hidden' name='deledit' id='deledit' value='".$edit."'>
3) Use a function something like this instead of all that code above
function ajaxDelCcode() {
$.ajax({
url: "main.php",
type: "GET",
dataType: "text",
data: $("#myDelForm").serialize(),
success: function(rText) {
$("#ajaxMain2").text(rText);
}
});
}

CI + AJAX, Double posting + refreshing of page

So I have a normal form with 1 textarea and two hidden inputs, which I would like to post via AJAX to a CI controller I have that inserts the information into the database.
The problem I'm having is that a) the page action is still called and the output of the controller is displayed and b) because the initial AJAX request is still processed plus the extra loading of the action target the information gets inserted twice.
This is my javascript code:
$(document).ready(function() {
$("#submit-comment").click(function(){
var post_id = <?=$p->id?>;
var user_id = <?=$user->id?>;
var content = $("textarea#content").val();
if(content == '') {
alert('Not filled in content');
return false;
}
$.ajax({
type: "POST",
url: "<?=site_url('controller/comment')?>",
data: "post_id="+post_id+"&user_id="+user_id+"&content="+content,
success: function(msg){
alert(msg);
}
});
});
});
I have tried doing
...click(function(e)... ... e.preventDefault
with no luck.
What am I doing wrong? :P
Thanks
Ps. All the information is processed properly and accessed, it's just the preventing the form which is screwing it up..
Just realised I was using a input type="submit", rather than input type="button".
Doh!

Resources