I have been successful in returning the json responce from the ajax call to my php script that sends messages. When submitting data to the PHP script, if successful it should return a json string like the following...
{"status":"valid","message":"Your message was send successfully."}
I would like to check if the "status" equals valid and then show a div showing that the message has been sent. How would i go about doing this and this is the code i have so far...
$("#send").click(function() {
var complete = true;
$('input#fullname, input#email, input#subject, textarea#message').each(function() {
if ($(this).val()) {
$(this).css("background","#121212").css("color","#5c5c5c");
} else {
$(this).css("background","#d02624").css("color","#121212");
complete = false;
}
});
if (complete == true){
var name = $("input#fullname").val();
var email = $("input#email").val();
var subject = $("input#subject").val();
var message = $("textarea#message").val();
var data = 'name='+name+'&email='+email+'&subject='+subject+'&message='+message;
$.ajax({
type:"POST",
url:"resources/includes/contact.php",
data:data,
success:function(data){
alert(data);
}
});
}
});
Thanks,
Nathaniel Blackburn
you can do it like this
$.ajax({
type:"POST",
url:"resources/includes/contact.php",
data:data,
dataType: 'json',
success:function(response){
if(response.status="valid"){
......
}
}
});
In your success callback function, add
data = $.parseJSON(data);
if (data.status == "valid"){
//do stuff
}
change your success function to look like this:
success:function(data)
{
jsonObject = JSON.parse(data);
alert(jsonObject.status);
}
Related
I'm trying to display response.message as content to a tag with id test. It's getting displayed as undefined.
success:function(response){
console.log("response"+response); // works
var msg = response.message;
if(response.status=="success"){
console.log("response1"+msg);
document.getElementById('test').innerHTML = msg; //undefined
} else {
jQuery('#test').contents(msg);
document.getElementById('test').innerHTML = msg; //undefined
}
}
The way I normally handle this is parsing the JSON response for it to be made into a JavaScript object (Using JSON.parse), try this code below.
success: function(response) {
console.log("response" + response);
response = JSON.parse(response);
var msg = response.message; // works
if (response.status == "success") {
console.log("response1" + msg); // prints/works
document.getElementById('test').innerHTML = msg; //undefined
} else {
jQuery('#test').contents(msg);
document.getElementById('test').innerHTML = msg; //undefined
}
}
Alternatives
You should also be able to set the content type on the PHP page itself before the output using headers
header("Content-type:application/json");
You can also set the datatype to json in your ajax call which is pretty standard
$.ajax({
type: "POST",
url: "",
dataType: "json",
success: function(msg) {
//process success
}
...
});
The undefined isn't msg, the undefined is probably being return from document.getElementById('test').
So I have an onclick function which sends a message to another php file which sends the message to the database. I want to send to the php file, the whole form and a specific chat_index value. So far I have:
$(".comin").keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
var item_id = this.id;
alert(item_id);
if($.get('sendcom.php?q=' + item_id, $('#comform').serialize())) {
var a = $(".comin").val();
alert(a);
document.getElementById(item_id).value = "";
//sent and cleared
}
}
});
post your data in json format,
$(".comin").keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
var chatData = {
q: item_id,
formData:$('#comform').serialize()
}
$.ajax({
url: 'sendcom.php',
type: 'post',
dataType: 'json',
data: chatData,
success: function (data) {
$('#target').html(data.msg);
}
});
}
});
here is it my code i call ajax by jquery $.ajax
js
$("#form-login").submit(function(){
var email = $("#menu_username");
$.ajax({
type: "post",
url: "register_cmd.php",
data: {email:email},
dataType: "json",
cache:false,
success:function(data){
if(data.c == "ok"){
window.location.reload();
} else {
alert(data);
}
return false;
}
})
});
register_cmd.php
<?PHP
include 'system/library/main.php';
$main = new mainQuery();
$chk_email = $main->checkEmail($email);
?>
main.php
function checkEmail($email){
$result = "function here";
return $result;
}
then it return 500 internal server error i don't know why
I just had this problem myself, even though i couldn't find the reason for it in my case, when changing from POST to GET, the problem 500 error disappeared!
because GET method sends the encoded user information appended to the page request.
type:'POST'
to
type:'GET'
I doing little changes in your codes. Just try this
var email = $("#menu_username").val(); // if you want to take the value from email field
$.ajax({
type: "POST",
url: "register_cmd.php",
data: {email:email},
dataType: "json",
cache:false,
success:function(data){
if(data.result == "ok"){
window.location.reload();
} else {
alert(data.result);
}
return false;
}
});
AND change the codes in register_cmd.php as follows
<?PHP
include 'system/library/main.php';
$main = new mainQuery();
$chk_email['result'] = $main->checkEmail($email);
print_r(json_encode($chk_email)); // if you are using json, you should use json_encode before it returns.
?>
the function in main.php need's a class arround it
class mainQuery {
public function checkEmail($email){
$result = "function here";
return $result;
}
}
otherwise you cannot instance new mainQUery;
also on top of everything to debug set
error_reporting(E_ALL);
ini_set('display_errors', true);
500 are serverside errors and have nothing to do with ajax.
probably this line:
var email = $("#menu_username");
might have to be
var email = $("#menu_username").text();
//or
var email = $("#menu_username").val();
It doesn't matter if it's a POST or GET request.
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.
Sorry but I know something similar to this has already been posted. I have tried every single resource out there and did my research and I still couldn't find out what is wrong with my code. I am using a Ajax Post with php. Everything seems to be working fine except for the fact that the div is not reloading on submit. After I refresh the page what I posted came up. Can someone please tell me what I am doing wrong.
js code:
$(function() {
$('.error').hide();
$('input.text-input').css({
backgroundColor: "#FFFFFF"
});
$('input.text-input').focus(function() {
$(this).css({
backgroundColor: "#C0DDFA"
});
});
$('input.text-input').blur(function() {
$(this).css({
backgroundColor: "#FFFFFF"
});
});
$(".button").click(function() {
// validate and process form
// first hide any error messages
$('.error').hide();
var email = $("input#email").val();
if (email == "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
var dataString = '&email=' + email;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "../EdinburgCISD/Gorena/Gorena.php",
data: dataString,
success: function(data) {
$("#email").val('');
$("#div").fadeOut(1000);
// Change the content of the message element
$("#div").html(data);
// Fade the element back in
$("#div").fadeIn(1000);
}
});
return false;
});
});
html code:
This is where I have my div.
<div id="div"> <?php \\database select query ?> </div>
I am new to this website sorry if I posted something wrong...
did you get any error in console (firebug/developer tools) ?
otherwise you can try below
check with alert
$.ajax({
type: "POST",
url: "../EdinburgCISD/Gorena/Gorena.php",
data: dataString,
success: function(data) {
alert(data);//what you get here? are you getting "object" in alert? then you need to specify property or mention dataType
$("#email").val('');
$("#div").fadeOut(1000);
// Change the content of the message element
$("#div").html(data);
// Fade the element back in
$("#div").fadeIn(1000);
}
});
modified your code a bit see the comments, you should specify dataType:html (see the ajax part).
$(function() {
$('.error').hide();
$('input.text-input').css({backgroundColor:"#FFFFFF"});
$('input.text-input').focus(function(){
$(this).css({backgroundColor:"#C0DDFA"});
});//focus ends
$('input.text-input').blur(function(){
$(this).css({backgroundColor:"#FFFFFF"});
});//blur ends
$(".button").click(function() {
// validate and process form
// first hide any error messages
$('.error').hide();
var email = $("input#email").val();
if (email == "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
//var dataString = '&email=' + email; commented out
var dataString = email; //try insted this
//alert (dataString);return false;
$.ajax({
type: "POST",
dataType:'html', //or the appropiate type of data you are getting back
url: "../EdinburgCISD/Gorena/Gorena.php",
data: {email:dataString}, //in the php file do $email = $_POST['email'];
async:false, //not a good practice but you can try with it and without it
success: function(data) {
$("#email").val('');
$("#div").fadeOut(1000);
// Change the content of the message element
$("#div").html(data);
// Fade the element back in
$("#div").fadeIn(1000);
}
}); //ajax ends
return false;
});//click ends
});//document ready ends
update
see this fiddle you will get the idea http://jsfiddle.net/3nigma/LuCQw/ and the delay function is optional i have used it so that the effect is prominent