jquery Ajax URl issue - php

I have looked around quite a bit and it seems absolute urls is the way to go here. I have no problem in chrome but firefox and IE IE still wants to redirect fully to the wrong page.
my states:
<script type="text/javascript">
$(function() {
$('#page_submit').click(function () {
event.preventDefault();
$('.standard span').hide();
var pw = $("input#pw").val();
if (pw == "") {
$("span#pw_err").show();
$("input#pw").focus();
return false;
}
var pw2 = $("input#pw2").val();
if (pw2 == "") {
$("span#pw2_err").show();
$("input#pw2").focus();
return false;
}
if (pw != pw2) {
$("span#match_err").show();
$("input#pw2").focus();
return false;
}
var data = 'pw=' + pw + '&pw2=' + pw2;
$('.standard input').attr('disabled','true');
$('.loading').show();
$.ajax({
url: "/members/includes/change.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
//hide the form
$('#pw_form').fadeOut('slow');
//display results
$('#pw_form_result').fadeIn('slow');
$("#pw_form_result").html(html);
}
});
return false;
});
});
</script>
the structure of the file I am trying to access is:
www.site.com/members/includes/change.php
Not sure what the cause is really. I know the jquery initiator is working because i can summon alert calls to and from the function itself.
edit
after commenting out
event.preventDefault();
it seems to function right? everything I had read before said this was a necessary piece however.

This line
$('#page_submit').click(function () {
should be
$('#page_submit').click(function (event) {
so this code
event.preventDefault();
can take effect.
And the 'return false;' is unneccesarry.

Related

Ajax infinite scroll down pagination . image not showing while using async in ajax call

I am using ajax to load data when user scroll further down the page . i am using async = false; which will stop the calls to the ajax function unless the already running call is completed. Yes , its not recommended to use async. but to prevent data disorder i have to use it.
Here is my ajax function
<script type="text/javascript">
var page = 1;
var busy = false;
var lastScrollTop = 0;
$(window).scroll(function(event){
var st = $(this).scrollTop();
if (st > lastScrollTop)
{
if( $(window).scrollTop() + $(window).height() > $(document).height()-550 && busy == false)
{
loadMoreData(page);
page++;
}
}
lastScrollTop = st;
});
function loadMoreData(page){
$.ajax(
{
type: "POST",
url: '<?php echo base_url('sura/load_verse/'.$sura_id.'/')?>'+page,
async: false,
cache: false,
beforeSend: function()
{
$('#loader_message').show();
}
})
.done(function(data)
{
if(data == ""){
$('.ajax-load').html("No More Data Found");
return;
}
$('.ajax-load').hide();
$("#post-data").append(data);
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
});
busy = false;
$('#loader_message').hide();
}
</script>
but the async call does not let the browser to show my loading image $('#loader_message').show(); while the call is fetching the data.
can somebody help me in showing the image while using the async call .Or is there an alternative for async which will stop multiple request at the same time.
Thanks
I believe the solution is to show the loader before starting the ajax call. beforeSend doesn't work because the DOM is not modified until after $.ajax() is done and showing the loader qualifies as modifying the DOM.
Below is my suggested solution. I changed your code a bit to use what I feel are "best practices" for javascript. One thing I always avoid is using PHP code inside the javascript. What you do with base_url() will become a problem if you move your javascript to an external file. That is why I usually define a var baseURL as shown below.
I also cache any JQuery object that needs to be created more than once which is why the vars thisWindow and loader were added.
It also appears that once you set busy = true it is never changed back to false. That is remedied by adding an .always call which runs busy=false. The loader is also hidden in .always so that you can be certain it will removed even if there is an ajax .fail.
I think that with busy being properly managed you can use async: true,. I strongly recommend you give that a try.
Here's my answer
<script>
var page = 1;
var busy = false;
var baseURL = window.location.protocol + "//" + window.location.hostname;
var lastScrollTop = 0;
var thisWindow = $(window);
var loader = $('.ajax-load');
thisWindow.scroll(function (event) {
var st = $(this).scrollTop();
if (st > lastScrollTop)
{
//check busy first, if busy=true you avoid making calls
//do scrollTop() and height()
if (busy == false && thisWindow.scrollTop() + thisWindow.height() > $(document).height() - 550)
{
loadMoreData(page);
page++;
}
}
lastScrollTop = st;
});
function loadMoreData(page) {
busy = true;
loader.show();
$.ajax(
{
type: "POST",
url: baseURL + "/sura/load_verse/$sura_id/" + page,
async: false,
cache: false,
})
.done(function (data)
{
if (data == "") {
loader.html("No More Data Found");
return;
}
$("#post-data").append(data);
})
.fail(function (jqXHR, ajaxOptions, thrownError)
{
})
.always(function () {
busy = false;
loader.hide();
});
}
</script>

Ajax POST to Cakephp Controller always give array() result

i really struggle to get the POST value in the controller .i am really new to this..Please someone share me some light..being in the dark for long hours now.
i had a checkboxes and need to pass all the ids that had been checked to the controller and use that ids to update my database.i don't know what did i did wrong, tried everything and some examples too like here:
sending data via ajax in Cakephp
found some question about same problem too , but not much helping me( or maybe too dumb to understand) . i keep getting array();
please help me..with my codes or any link i can refer to .here my codes:
my view script :
<script type="text/javascript">
$(document).ready(function(){
$('.checkall:button').toggle(function(){
$('input:checkbox').attr('checked','checked');
$('#button').click( function (event) {
var memoData = [];
$.each($("input[name='memo']:checked"), function(){
memoData.push($(this).val());
});
var value = memoData.join(", ")
//alert("value are: " + value);
//start
$.ajax({
type:"POST",
traditional:true;
data:{value_to_send:data_to_send},
url:"../My/deleteAll/",
success : function(data) {
alert(value);// will alert "ok"
},
error : function() {
alert("false submission fail");
}
});
//end
} ); //end of button click
},function(){//uncheck
$('input:checkbox').removeAttr('checked');
});
});
my controller :
public function deleteAll(){
if( $this->request->is('POST') ) {
// echo $_POST['value_to_send'];
//echo $value = $this->request->data('value_to_send');
//or
debug($this->request->data);exit;
}
}
and result of this debug is:
\app\Controller\MyController.php (line 73)
array()
Please help me.Thank you so much
How about this:
Jquery:
$(document).ready(function() {
$('.checkall:button').toggle(function() {
$('input:checkbox').attr('checked','checked');
$('#button').click(function(event) {
var memoData = [];
$.each($("input[name='memo']:checked"), function(){
memoData.push($(this).val());
});
//start
$.ajax({
type: 'POST',
url: '../My/deleteAll/',
data: {value_to_send: memoData},
success : function(data) {
alert(data);// will alert "ok"
},
error : function() {
alert("false submission fail");
}
});//end ajax
}); //end of button click
},function(){//uncheck
$('input:checkbox').removeAttr('checked');
});
});
In controller:
public function deleteAll()
{
$this->autoRender = false;
if($this->request->is('Ajax')) { //<!-- Ajax Detection
$elements = explode(",", $_POST['value_to_send']);
foreach($elements as $element)
{
//find and delete
}
}
}
You need to set the data type as json in ajax call
JQUERY CODE:
$.ajax({
url: "../My/deleteAll/",
type: "POST",
dataType:'json',
data:{value_to_send:data_to_send},
success: function(data){
}
});

Searching not working in ajax once textbox onblur event is called

I have the following code to search through AJAX. Now if I apply onblur event to the textbox (so that searching result disappears) and get back to the textbox again, searching facility is no more working. So the thing is, it might not be able to call onfocus event properly once onblur event is called. Any help would be appreciated.
<script type="text/javascript">
$(document).ready(function () {
$(".searchproductbrand").keyup(function () {
var kw = $(".searchproductbrand").val();
if (kw != '') {
$.ajax({
type: "POST",
url: "livesearch.php",
data: "kw=" + kw,
success: function (option) {
$("#livesearch").html(option);
document.getElementById("livesearch").style.border = "1px solid #A5ACB2";
}
});
} else {
$("#livesearch").html("");
document.getElementById("livesearch").style.border = "0px";
}
return false;
});
});
</script>
<script>
$(document).ready(function () {
$(".searchproductbrand").blur(function () {
document.getElementById("livesearch").style.display = "none";
})
});
</script>
Livesearch is the div where I print my search results.
You should provide your markup, or a jsfiddle but i'm almost sure that everything is working but on the onblur event you set the display rule of the 'livesearch' element to none, but you never set it back to block so you made it invisible and it stayed that way because you need to set it to block or whatever visibible display rule that you want, i created a jsfiddle example based on what you posted, i took the liberty to alter your code and removed the ajax part so you can focus on the real issue, i hope this solves your problem.
http://jsfiddle.net/kFj9u/1
jQuery(document).ready(function(){
var $liveSearch = $('#liveSearch');
$(".searchProductBrand").keyup(function(){
var keyWord = $(this).val();
if(keyWord != ''){
var msg = 'You searched for ' + keyWord;
$liveSearch.css('display','block').html(msg);
}else{
$liveSearch.html('').
css('border','none');
}
}).blur(function(){
$liveSearch.css('display','none');
})
});
Probably your livesearch is still hidden, try this:
<script type="text/javascript">
$(document).ready(function () {
$(".searchproductbrand").keyup(function () {
var kw = $(".searchproductbrand").val();
if (kw != '') {
$.ajax({
type: "POST",
url: "livesearch.php",
data: "kw=" + kw,
success: function (option) {
$("#livesearch").show(); // this is
$("#livesearch").html(option);
document.getElementById("livesearch").style.border = "1px solid #A5ACB2";
}
});
} else {
$("#livesearch").html("");
document.getElementById("livesearch").style.border = "0px";
}
return false;
});
});
</script>
<script>
$(document).ready(function () {
$(".searchproductbrand").blur(function () {
document.getElementById("livesearch").style.display = "none";
})
});
</script>

Form Validation, problems with passing of argument and page redirection

So I'm creating this form validator with PHP and jQuery.
The PHP code will check through the form and then return an array with fields that contain errors. Example: {"email":1,"password":1}
But now I have concerns regarding if no errors were to be found. The problem here is that I've included "return false" in the end of the code to prevent page redirection. I've read that this is bad code practice but not found another way that works as intended.
The second problem is how to pass the o-array into the $('input').each function. Right now it will say that all forms are valid since nothing was passed. If I use $.post instead of $.ajax this scope problem doesn't appear for some reason.
jQuery:
$(function() {
$('#register').submit(function() {
var url = $(this).attr('action');
var data = $(this).serialize();
$.ajax({
type: 'GET',
url: url,
data: data,
success: function(o) {
console.log(o);
$('input').each(function() {
var msgId = o[$(this).attr('name')];
console.log(o[$(this).attr('name')]);
if (msgId > 0) {
$('#listError').css('visibility', 'visible');
$('#listError').append('<li>' + $(this).nextAll('span.msg').eq(msgId - 1).text() + '</li>');
$(this).addClass('invalid');
} else if (msgId != 0) {
$(this).addClass('valid');
}
$('#listError').append('</ul>');
})
}
}, 'json');
return false;
});
});
Fist, why are you submitting a form when you really don't want to?! Use a button instead and make the AJAX request from its click handler.
$('#registerButton').click(function() {
var form = $('#register')
var data = form.serialize();
$.ajax(...);
});
"The second problem is how to pass the o-array into the $('input').each"
What is the problem here? If you have an each() inside a success callback, you can use the data parameter that is passed to the callback (or o in your case) in that each().
Try this
$(function() {
$('#submit_button_id').click(function() {
var url = $(this).attr('action');
var data = $(this).serialize();
var ret = true;
$.ajax({
type: 'GET',
url: url,
async: false,
data: data,
success: function(o) {
console.log(o);
$('input').each(function() {
var msgId = o[$(this).attr('name')];
console.log(o[$(this).attr('name')]);
if (msgId > 0)
ret = false;
$('#listError').css('visibility', 'visible');
$('#listError').append('<li>' + $(this).nextAll('span.msg').eq(msgId - 1).text() + '</li>');
$(this).addClass('invalid');
} else if (msgId != 0) {
$(this).addClass('valid');
}
$('#listError').append('</ul>');
})
}
}, 'json');
if(ret==true){
$('#register').submit();
}
});
});

Submitting form via ajax in jquery

i am having some problems with getting my form to submit. It doesnt seem like anything is being send, is their anything wrong with this code as javascripting isn't my strong point...
$("#send").click(function() {
var complete = true;
$('input#name, input#email, input#subject, textarea#message').each(function() {
if ($(this).val()) {
$(this).css("background","#ffffff").css("color","#5c5c5c");
} else {
$(this).css("background","#d02624").css("color","#ffffff");
complete = false;
}
});
if (complete == true){
var name = $("input#name").val();
var email = $("input#email").val();
var subject = $("input#subject").val();
var message = $("textarea#message").val();
var data = '{"name":"'+name+'","sender":"'+email+'","subject":"'+subject+'","message":"'+message+'"}';
$.ajax({
type:"POST",
url:"contact.php",
data:$.base64.encode(data),
success:function(data){
data = $.parseJSON(data);
if (data.status == "success") {
$.fancybox.close();
}
}
});
}
});
There is also a live version of this in action which can be viewed over at: http://idify.co.uk, thanks :)
You can do it better.
$('form')
.submit(function(event) {
var form = $(this);
$.ajax({
url: '[url here]',
type: 'post',
data: $.base64.encode(form.serialize()), // $.serialize() - it gets all data from your form
dataType: 'json', // function in success callback knows how to parse returned data
success: function(data) {
if (data['status'] == true) {
// your code here
// e.g.
$.fancybox.close();
}
}
});
event.preventDefault();
});
Enjoy! :)
I got an error after submitting:
data is null http://idify.co.uk/javascripts/landing.js Line 25
It looks like the data was sent successfully and there was a response:
{"status":"error","responce":"No token parameter was specified."}
This should help you ensure you've got data in your success callback:
success:function(response) {
if (response) {
var data = $.parseJSON(response);
if (data && data.status == "success") {
$.fancybox.close();
}
} else {
// handle errors
}
}
Haha, thanks guys. I was silly enough not to include the variable that needs to be passed via the php file, got it sorted and it works like a dream, i ended up using the first solution as the form submission one wasnt working for me.

Categories