This is my ajax function and
$('#save_form_3').button({
icons: {
primary: "ui-icon-disk"
}
})
.click(function (event) {
if($('#guarantor_details').validate().form()){
var form_3_data = $("#guarantor_details").serialize();
$.ajax({
type: "POST",
url: "insert.php",
data: form_3_data,
success: function(response, textStatus, xhr) {
alert(response);
if(response=="success"){
alert(response);
}
},
error: function(xhr, textStatus, errorThrown) {
}
});
return false;
}
});
first alert gives me message "success" and second alert doesn't execute. seems like if condition not working under success function.
any idea why it doesn't?
im using jquery-1.6.2.min.js.
maybe problem in jquery 1.6.2 or am i doing something wrong?
Thanks
if($SQL_INSERT){
echo "success";
}else{
echo mysql_error();
}
thats insert.php anyway
if($.trim(response)=="success") works
try removing any whitespaces/newlines outside the tags in your insert.php file.
Maybe you could use a simple regex?
Instead of response=="success", try /success/.test(response)
This will return true if success is anywhere in the response string.
Related
In my dashboard.php I have a Javascript function that is called based on the user clicking a button. When the button is clicked, it calls a JavaScript function called getTeamMembers and values are passed across to it. The values passed across to this function are then sent to a PHP function (which is also located in dashboard.php).
However I am not getting any success and was hoping that someone could guide me on where I am going wrong. I am a noob when it comes to AJAX so I assume I am making a silly mistake.
I know my function is definitely getting the intended variable data passed to it, after doing a quick window.alert(myVar); within the function.
This is what I have so far:
function getTeamMembers(teamID,lecturer_id) {
var functionName = 'loadTeamMembersChart';
jQuery.ajax({
type: "POST",
url: 'dashboard.php',
dataType: 'json',
data: { functionName: 'loadTeamMembersChart', teamID: teamID, lecturer_id: lecturer_id },
success: function(){
alert("OK");
},
fail: function(error) {
console.log(error);
},
always: function(response) {
console.log(response);
}
}
);
}
Before calling the desired php function, I collect the sent varaibles just before my php Dashboard class starts at the top of the file. I plan to pass the variables across once I can be sure that they are actually there.
However, when I click the button, nothing can be echo'd from the sent data.
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
if (!empty($_POST["teamID"]) && !empty($_POST["lecturer_id"]))
{
$teamID = $_POST['teamID'];
$lecturer_id = $_POST['lecturer_id'];
echo $teamID;
echo " is your teamID";
}
else
{
echo "no teamID supplied";
}
}
you else statement in you success function , and that's not how you set fail callback, try the following and tell us what do you see in the console.
function getTeamMembers(teamID,lecturer_id) {
jQuery.ajax({
type: "POST",
url: 'dashboard.php',
dataType: 'json',
data: {functionname: 'loadTeamMembersChart', arguments: [teamID, lecturer_id]},
success: function(data) {
console.log(data);
},
fail: function(error) {
console.log(error);
},
always: function(response) {
console.log(response);
}
});
}
Seems like your function is not returning a success message when getting into the following statement.
if ($result) {
"Awesome, it worked"
}
Please try to add a return before the string.
if ($result) {
return "Awesome, it worked";
}
It can be other factors, but the information you provided is not enough to make any further analysis.
onSubmit: function(invalid, e) {
e.preventDefault();
if(!invalid)
{
alert("test");
$.post('login.php', this.$form.serialize(), function(response) {
// asdasd
}, 'json');
}
}
I get the alert box but the post doesn't seem to work. Is there anything clearly wrong in the above code?
I am using IdealForms.
The request works, there must be an issue in your server side code. Make sure that:
1) login.php exists and it's in the right path.
2) Your PHP script echos JSON. Try a simple test script:
<?php
// login.php
echo json_encode(array('value' => true)); // send as JSON
Then in JavaScript log the response to the console (press F12 or Cmd+Shift+I):
onSubmit: function(invalid, e) {
e.preventDefault();
if(!invalid) {
$.post('login.php', this.$form.serialize(), function(response) {
console.log(response);
}, 'json'); // read as JSON
}
}
The console should output an object {value: true}.
PS: I'm the developer of Ideal Forms.
All you need to do is call JQuery, and use code like this:
$.ajax({
type: "POST",
url: "login.php",
data: $(this).serialize(),
success: function() {
alert('success');
}
});
Hello i'm using an ajax script redirecting to a php page where i make the validation. After there are no validation errors i want to redirect to another page but i cant manage to make it work. here is my script:
<script type="text/javascript" src="js/jquery.form.js"></script>
<script type="text/javascript" >
$(document).ready(function() {
$("#imageform").ajaxForm({
target: \'#preview \',
});
});
</script>
and here is the external php were i make the validation
<?php
require_once('../core/dbconfig.php');
mysql_query("SET NAMES utf8");
$fname=$_POST['name'];
$email=$_POST['email'];
$country=$_POST['country'];
$city=$_POST['city'];
$type=$_POST['type'];
$story=$_POST['story'];
$cookie=$_COOKIE['cookie'];
$sizee = $_FILES['img1']['size'];
if (!$fname or !$city or !$email or !$country or (!$story && $sizee==0))
{
if ($sizee==0 && !$story)
{
echo'<p style="color:red;">Please upload a photo or type your story.<p>';
}
if(!$fname)
{
echo'<p style="color:red;">Please enter your name.<p>';
}
$regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
if (preg_match($regex, $email)) {
}
else
{
echo'<p style="color:red">Please enter a valid email.<p>';
}
if(!$country)
{
echo'<p style="color:red">Please select your country.<p>';
}
if(!$city)
{
echo'<p style="color:red">Please enter your city.<p>';
}
}
else
{
....
}
what i want to achiev is that after all the conditions are completed to redirect to a confirmation page. If i use a succes:window.location.href = "example.php" doesnt work as intended.
Thnx in advance.
$(myform).ajaxForm({
beforeSend: function() {
},
error: function() {
},
complete: function(response) {
window.location.href='yourfile.php'
}
});
With ajaxForm you'r can use function complete, according to documentation this function... "A function to be called when the request finishes (after success and error callbacks are executed)".
But you need consider property async, By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false.
$(myform).ajaxForm({
async: true,
error: function(response) {
//something is wrong
},
complete: function(response) {
window.location.href='yourfile.php'
}
});
OR
$(myform).ajaxForm({
async: false,
error: function(response) {
//something is wrong
},
complete: function(response) {
window.location.href='yourfile.php'
}
});
$.ajax({
type: "POST",
dataType: "json",
url: "friends/get_user_friends",
data:{
action:"action",
type:"type"
},
success: function (response) {
window.location.href = "http://google.com";
},
error: function (response, ajaxOptions, thrownError) {
}
});
I am trying to POST some data to my ASP.Net MVC Web API controller and trying to get it back in the response. I have the following script for the post:
$('#recordUser').click(function () {
$.ajax({
type: 'POST',
url: 'api/RecordUser',
data: $("#recordUserForm").serialize(),
dataType: 'json',
success: function (useremail) {
console.log(useremail);
},
error: function (xhr, status, err) {
},
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
alert("Error");
}
else {
var data = xhr.responseText;
alert(data);
//...
}
}
});
});
The problem with this script is that whenever I try to post the data, the jQuery comes back in "error" instead of "success".
I have made sure that there is no problem with my controller. I can get into my api method in debug mode whenever the request is made and can see that it is getting the data from the POST request and is returning it back. This controller is quite simple:
public class RecordUserController : ApiController
{
public RecordUserEmailDTO Post(RecordUserEmailDTO userEmail)
{
return userEmail;
}
}
I am not sure how I can get jQuery to print out any useful error messages. Currently when I try to debug the jQuery code using Chrome console it shows an empty xhr.responseText, nothing in "err" object and "status" set to "error" which as you see is not quite helpful.
One more thing that I have tried is to run the following code directly from the console:
$.ajax({
type: 'POST',
url: 'api/RecordUser',
data: {"Email":"email#address.com"},
dataType: 'json',
success: function (useremail) {
console.log(useremail);
},
error: function (xhr, status, err) {
console.log(xhr);
console.log(err);
console.log(status);
alert(err.Message);
},
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
alert("Error");
}
else {
var data = xhr.responseText;
alert(data);
}
}
});
i.e. using the same script without actually clicking on the button and submitting the form. Surprisingly, this comes back with the right response and I can see my data printed out in console. For me this atleast means that my Web API controller is working fine but leaves me with no clue as to why it is not working on clicking the button or submitting the form and goes into "error" instead of "success".
I have failed to find any errors in my approach and would be glad if someone could help me in getting a response back when the form is posted.
As suggested by Alnitak, I was using complete callback along with success and error ones. Removing complete from my code fixed the issue.
Thanks to Alnitak.
I am new to jquery and coding in general. This is what I am trying to do:
When a link is clicked, expand the #country_slide div
Show "loading" text
If ajax is successful, put the contents of an html file into the div
Otherwise alert an error and close the div
This is the code I now have:
http://jsfiddle.net/spadez/n9nVs/5/
window.onload = function () {
var a = document.getElementById("country_link");
a.onclick = function () {
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
beforeSend : function() {
$("#country_slide").show();
$("#country_slide").val('<p>Loading</p>')
},
success: function (data, textStatus) {
$("#country_slide").html(data);
alert('request successful');
},
error: function (xhr, textStatus, errorThrown) {
alert('request failed');
$("#country_slide").hide();
},
complete : function() {
$('.loader').hide();
},
});
return false;
}
}
When the link is clicked, I never see the loading text in the box. Please can someone tell me where I have gone wrong here? Also if anyone can offer any words of advice about my first jquery script I would really appreciate it.
Your anchor's id is country, not country_link. So:
var a = document.getElementById("country");
or just use jQuery's id selector:
var a = $("#country");
or even better directly chain:
$(function() {
$('#country').click(function () {
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
beforeSend : function() {
$("#country_slide").show();
$("#country_slide").html('<p>Loading</p>')
},
success: function (data, textStatus) {
$("#country_slide").html(data);
alert('request successful');
},
error: function (xhr, textStatus, errorThrown) {
alert('request failed');
$("#country_slide").hide();
},
complete : function() {
$('.loader').hide();
},
});
return false;
}
});
Notice that I have used the $(document).ready function instead of window.onload. Also I have replaced the onclick event subscription with jQuery's click function. If you are using jQuery it would be better to take full advantage of it.
Working jsFiddle Demo
You don't have any country_link element in your page.
Instead of using window.onload you can use DOM ready.
Attach click handler by jQuery with .on() method.
The .val() method is for <input />. For other elements, use .html() instead.
// DOM ready instead of window.onload
$(function () {
// attach click handler by jQuery instead of onclick
$('#country').on('click', function () {
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
beforeSend : function() {
$("#country_slide").show();
// val() method is for <input />
// use html() instead
$("#country_slide").html('<p>Loading</p>')
},
success: function (data, textStatus) {
$("#country_slide").html(data);
alert('request successful');
},
error: function (xhr, textStatus, errorThrown) {
alert('request failed');
$("#country_slide").hide();
},
complete : function() {
$('.loader').hide();
},
});
return false;
});
});
References:
.html() - jQuery API Documentation
.on() - jQuery API Documentation
.val() - jQuery API Documentation
jQuery( callback ) - jQuery API Documentation
On the fiddle you have
<a href="#" id="country">
Where it should be:
<a href="#" id="country_link">
or change the JS to be
var a = document.getElementById("country");
Because there is no element with an ID country_link
document.getElementById() returns null if the element isn't found
document.getElementById('country').onclick = ...; //should work
In JavaScript, null is a special primitive and you cannot add properties to primitive types.
You have to add an element with id=country_link and the this code will work as NOX said. I have tried that in jsfiddle. try it using
$("#country").click(function(){
// your code goes here
})
that will works.
document.getElementById("country_link"); shall be replaced by document.getElementById("country"); as "country_link" is not the id of any <a> tag in the mark up.
If you are using jQuery library you may handle event like-
$(document).on("click","a",function(){
//ajax stuff
});
Updated Your jsfiddle Code. Just check. its going to failure method. In your workspace you should have the test.html returning the actual data. Thanks.
Don't use plain JS if you already have jQuery (it will be easier for you):
;$(document).ready(function(){
$(country_link).click(function () {
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
beforeSend : function() {
$(country_slide).show();
$(country_slide).val('<p>Loading</p>');
},
success: function (data, textStatus) {
$(country_slide).html(data);
alert('request successful');
},
error: function (xhr, textStatus, errorThrown) {
alert('request failed');
$(country_slide).hide();
},
complete : function() {
$('.loader').hide();
},
});
return false;
});
});