error in ajax code - php

I am trying to implement ajax when the button is clicked, but the ajax is not wroking, can anyone tell me what's wrong, many thanks! what I want is that when click the "Move marked to set" button, in the "formstatus" div should display some message I defined in the addtoset.php, but currently it direct to to "#"page instead of remain on the same page
here is my ajax code
$('#movetoset').click(function() {
var fail="";
var hint="";
if ($('#selectsett').val() === 'General') {
fail += "Please chooose a set.\n";
}
for(j=0;j< array_str_idnum.length;j++)
{
if( document.getElementById('check' + array_str_idnum[j]).checked ==false){
hint='1';
}
}
if(hint=="1"){
fail += "Please check all the box.\n";
}
if(fail == ""){
var str = $("#complicated").serialize();
$.ajax({
type: "POST",
url: "addtoset.php",
data: str,
cache: false,
success: function(msg)
{
$("#formstatus").ajaxComplete(function(){
$(this).fadeIn("slow").html(msg)
});
}
});
return true;
}else{
alert(fail);
return false;
}
});
here is my html code
<form id ="complicated" method = 'post' action = '#'>
<div class="fancybuttonwrapper" style="margin-left:480px;"><span class="button"><span>
<input type="submit" class="form_button" id="movetoset" value=" Move Marked to Set"></span></span> </div>
<select name="sets" id ="selectsett">
<option value="General">Select Set</option>
<option value="Ceremony">Ceremony</option>
<option value="Lunch">Lunch</option>
<option value="Garden">Garden</option>
<option value="Longname">This is max length</option>
</select>
</div>
<div id="formstatus"></div>
</form>

your array array_str_idnum is not defined.
Further, you have to return false, else your form gets posted and so no ajax call at all.
Try this script. (always return false when you are in a form, else it gets send)
$('#movetoset').click(function() {
console.log("here")
var fail = "";
var hint = "";
if ($('#selectsett').val() === 'General') {
fail += "Please chooose a set.\n";
}
var str = $("#complicated").serialize();
$.ajax({
type: "POST",
url: "addtoset.php",
data: str,
cache: false,
success: function(msg) {
$("#formstatus").ajaxComplete(function() {
$(this).fadeIn("slow").html(msg)
});
}
});
return false;
});
check out: http://jsfiddle.net/wRNQv/5/ there is a running version.

Add fail handler to Ajax call and see what you get as error
error: function(xhr, textStatus, errorThrown){
}

The problem is you do not prevent the default action from executing. So the request may be started, but the page immediately redirects to different URL (defined in form's action).
Change the following part of the code:
$('#movetoset').click(function() {
var fail="";
into the following:
$('#movetoset').click(function(event) {
event.preventDefault(); // prevent form from submitting
var fail="";
It should help. Please let me know if it did.

Related

pass values from one PHP page to another with ajax

I have tied for hours now to get the values value="oneyearanalysis" and value="oneyearanalysis", of each button when i press them, i tried with ajax. I think i am close but i get no output GetData but i do in my console.log(clikYear);. Hope you can help me
Best regards
Index.php
<div class="container" style="margin-top: 50px;">
<select name="button" id="button">
<option value="">Select...</option>
<option value="oneyearanalysis">1 year analyse</option>
<option value="fiveyearanalysis">5 year analyse</option>
</select>
</div>
$(document).ready(function(){
$("#button").on("change",function() {
var clikYear = $(this).val();
console.log(clikYear);
if (clikYear !== "") {
var getTableCall2 = $.ajax({
url : "GetData.php",
type:"POST",
cache:false,
data:{clikYear:clikYear},
})
}
});
getTableCall2.done(function(data){
console.log(data);
console.log(getTableCall2);
console.log(clikYear);
})
GetData.php
if(isset($_POST['clikYear']))
{
$year= $_POST['clikYear'];
}
$yearOfChoice = $year;
You were quite close to make it work. If you apply the simple recommandations below, you should save yourself that kind of trouble in the future.
First recommandation is to indent your code correctly.
You would have noticed the getTableCall2 variable is declared on select change. But "used" before that when trying to apply the .done() promise handler.
Below, I made no change to you code except the indentation.
The order of execution on document ready is:
Register the change handler (not executed)
Throw an error.
 
$(document).ready(function(){
$("#button").on("change",function() {
var clikYear = $(this).val();
console.log(clikYear);
if (clikYear !== "") {
var getTableCall2 = $.ajax({
url : "GetData.php",
type:"POST",
cache:false,
data:{clikYear:clikYear},
})
}
});
getTableCall2.done(function(data){
console.log(data);
console.log(getTableCall2);
console.log(clikYear);
})
Second recommandation is to use the console where you would have seen this error:
ReferenceError: getTableCall2 is not defined.
Third recommandation is to be a bit more creative with you class and id naming. .button used on a <select> just can lead to confusion. You can use the name you want. Make it meaningful! I'm sure you do not use the word door when you talk about a window in the real life...
So here is something that should work:
$(document).ready(function(){
$("#analysis_term").on("change",function() {
var clikYear = $(this).val();
console.log(clikYear);
if (clikYear !== "") {
var getTableCall2 = $.ajax({
url : "GetData.php",
type:"POST",
cache:false,
data:{clikYear:clikYear},
})
getTableCall2.done(function(data){
console.log(data);
})
}
});
});
And to test it, make sure the GetData.php outputs something in both cases:
$year = "No POST value!";
if(isset($_POST['clikYear'])){
$year= $_POST['clikYear'];
}
echo "The POST value is:" . $year;
The ID for your Select is "button" but you are using Class Selector instead. Try replacing . with # in front of button
HTML
<select id="button">
<option value="">Select...</option>
<option value="oneyearanalysis">1 year analyse</option>
<option value="fiveyearanalysis">5 year analyse</option>
</select>
JQuery
$("#button").on("change", function () {
var clikYear = $(this).val();
console.log(clikYear);
if (clikYear !== "") {
$.ajax({
url: "GetData.php",
type: "POST",
cache: false,
data: { clikYear: clikYear },
})
}
});

Receive Jquery/Ajax Post Request in PHP

I have Jquery/Ajax Code which sends Text Fields Data to PHP Script. But i don't know how i can receive that data and process for Validation.
Here is the Ajax Code:
$("#button").click(function (e) {
var dataa = $("#survay").serialize();
var data = $("#yourName ,#emailAdress , #phoneNumber , #zipCode").serialize();
$.ajax({
type: "POST",
url: 'processRequest.php',
data: dataa,
beforeSend : function(){
$('.eDis').empty().append('<div class="loader"><img src="images/32.gif" /> Loading...</div>').show();
},
success: function (html) {
if(html !='1') {
$('.eDis').empty().append(html).addClass("actEr");
setTimeout(function(){
$('.eDis').removeClass("actEr")}, 5000);
}
if(html == '1') {
$('.eDis').empty().append('<div class="success">Your Message has been sent</div>').addClass("actEr");
window.location ='../thank-you.html';
}
if(html =='0') { $('.eDis').empty().append('Error..').addClass("actEr"); setTimeout(function(){
$('.eDis').removeClass("actEr")}, 3000);
}}
});
});
processRequest.php should be PHP script which will handle all the texts fields data.
If above Text fields data is valid then i want it to Proceed further and redirect the page to thank-you.html
.eDis is CSS class, which i want to use to display valid,Invalid fields information.
It is in HTML.
Based on your information, I can't give you exact code, but, this is what you can do:
<?php
if(isset($_POST['itemName']) && isset($_POST['anotherItemName']) /* ...and so on */){
if($_POST['itemName'] == $validSomething)
echo 'WOW!';
}
else
echo 'error';
?>
What you are "echoing" is what you get in "success" data in your javascript.

AJAX: return true or false on 'success:'

I have the following AJAX script, but for some reason the var ok it's not returning true or false so the form can continue:
function ajax_call(email,title,url){
var email = document.getElementById("email").value;
var title = document.getElementById("title").value;
var url = document.getElementById("url").value;
var parametros = {"emaail":email, "tiitle":title, "uurl":url};
var ok = true;
$.ajax({
data: parametros,
url: 'validate.php',
type: 'post',
error: function () {
alert("An error has occurred! Try Again!");
},
success: function (response) {
if(response == 'bien') { ok = true; } else { $("#ajax_cal").html(response); ok = false; }
}
});
return ok;
}
HTML:
<form onsubmit="return ajax_call();">
...
</form>
PHP:
<?php
//////....
if(!empty($errors)) {
foreach($errors as $error) {
echo '<li>'.$error.'</li>';
}
} else { echo 'bien'; }
?>
Everything works good, except for the return value.
Thanks in advance.
Prevent the submit completely, send the ajax request, then if it's good, submit the form.
HTML:
<form id="myform">
...
</form>
JavaScript:
$("#myform").submit(function(e){
// prevent submit
e.preventDefault();
var email = document.getElementById("email").value;
var title = document.getElementById("title").value;
var url = document.getElementById("url").value;
var parametros = {"emaail":email, "tiitle":title, "uurl":url};
$.ajax({
data: parametros,
url: 'validate.php',
type: 'post',
context: this,
error: function () {
alert("An error has occurred! Try Again!");
},
success: function (response) {
if($.trim(response) == 'bien') {
this.submit(); // submit, bypassing jquery bound event
}
else {
$("#ajax_call").html(response);
}
}
});
});
You are returning ok at the end of your function. This is returned before your ajax request is sent and completed.
You cannot rely on the return value of your function, you should do something inside your "success" part. It basically depends on what you want to do with your return value
I'm a complete newbie to jquery but in some of the scripts I've been working on I've had to prefix the 'response' you have.
For instance...
if(response.tiitle == 'bien') { ok = true; } else { $("#ajax_cal").html(response); ok = false; }
Also be aware you have double letters in your "parametros" but I'm sure that was intentional (i.e. tiitle and not title etc).

Jquery Ajax Script Not Working

I have a problem with ajax/php script.
It is for checking Username avaibility for user registration.
javascript
$(document).ready(function()
{
$("#username").change(function()
{
var usr = $("#username").val();
if(usr.length >= 4)
{
$("#status").html('<img src="./style/images/loading.gif"> Checking availability...');
$.ajax(
{
type: "POST",
url: "./ps/ajax_validation.php",
data: "username="+ usr,
success: function(msg)
{
$("#status").ajaxComplete(function(event, request, settings)
{
if(msg == 'OK')
{
$(this).html(' <img src="./style/images/tick.gif" align="absmiddle">');
}
else
{
$(this).html(msg);
}
});
}
});
}
else
{
$("#status").html('<font color="red">The username should have at least <strong>4</strong> characters.</font>');
}
});
});
html
...
<input class="login_reg_field" id="username" name="username" type="text" value="<?php echo #$d['username']?>" />
<div id="status"></div>
...
ajax_validation.php
<?php
include("../core/config.php");
if(isset($_POST['username'])){
$username = $_POST['username'];
$test = $user->checkUsernameAvaible($username); //Return True if Username IS Avaible
if(!$test){
echo '<font color="red">The nickname <STRONG>'.$username.'</STRONG> is already in use.</font>';
}else{
echo "OK";
}
}
?>
The php script is working, i tried it manually with $_GET variables..
When trying on the form, it stay on Checking avaibility... and No Javascript error on Firefox Console.
Also i've checked with Tamper Data, that the ajax request it's being made, and it is.
The problem seems to be on $("#status").ajaxComplete(function(event, request, settings){ because i've tried with an alert after this line, and no alert popping up.
update..
success is called whn the ajax call succeeds. so ther eis no need to call ajaxComplete there.. (if u think there is the problem)..
success
A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.
you can just check the response data and do your stuff..
success: function(msg){
if(msg == 'OK')
{
$(this).html(' <img src="./style/images/tick.gif" align="absmiddle">');
}
else
{
$(this).html(msg);
}
}
i think the problem is here
$("#username").change(function()
{
change() on input text fires only when you click somewhere outside the input field.. //try it once.
what you need is keyup()
$("#username").keyup(function()
{
Ok Answering my own question, i've solved.
Want to thank itachi for letting me know to use .done instead of success:
The problem was there.
Here is the revised and working part of the script:
var req = $.ajax(
{
type: "POST",
url: "./ps/ajax_validation.php",
data: "username="+ usr,
}).done(function(msg)
{
if(msg == 'OK')
{
$("#status").html(' <img src="./style/images/tick.gif" align="absmiddle">');
}
else
{
$("#status").html(msg);
}
});

jQuery variable to php variable then use it on query

i have a problem when it comes to retrieving value from jQuery to php.i was able to get the value of my select and pass it to my php but i can't pass it back to php. here is the code...
<script>
$(document).ready(function()
{
$("select#months").change(function(event)
{
var m=$(this).val();
$.ajax({
type: 'POST',
url: "monthly_CRD.php",
data: {m: m},
success: function(){alert("updated")}
});
});
});
</script>
<div>
<select id="months">
<option value='00'>Month...</option>
<option value='01'>Jan</option>
<option value='02'>Feb</option>
<option value='03'>Mar</option>
<option value='04'>Apr</option>
</select>
<select id="years">
<?php
for($yr=10; $yr<=$year; $yr++)
{
echo "<option value='".$yr."'>".$years[$yr]."</option>";
}
?>
</select>
</div>
<?php
if (isset($_POST['m']))
{
$m = $_POST['m'];
echo $m;
} else {echo "fail";}
?>
it keeps on returning fail which means that isset is not working.
Change data: {m: m} to data: {"m":m}
Since you are looking at $_POST['m'] you need to define that key in your JSON. Currently you'd need to look inside $_POST['03'] if you selected Mar
If you mean that on page load, it returns fail, that is because on page load your $_POST array is probably empty.
If you want to know what was returned from your AJAX post, you need your success function to accept a parameter (like data) that jQuery will fill with the response to your post.
Then in the function body, you can write it to the DOM or your error console.
If you have an id to an element then just id is enough to select. Try this
$(document).ready(function()
{
$("#months").change(function(event)
{
$.ajax({
type: 'post',
url: "monthly_CRD.php",
data: { m: $(this).val()},
success: function(){
alert("updated")
}
});
});
});
$(document).ready(function()
{
$("#months").change(function(event)
{
$.ajax({
type: 'post',
url: "monthly_CRD.php",
data: '{ "m": "' + $(this).val() + '"}',
success: function(msg){
alert(msg)
},
error: function(msg) {
alert("An error happened: " +msg);
}
});
});
});
User fiddler of chrome tools to break on either success or error and check the value of the meesage property.

Categories