I have a JSON request using post method using ajax within this code
$(document).ready(function() {
$(document).on('submit', '#registration_check', function() {
var data = $(this).serialize();
$.ajax({
type: 'POST',
url: 'apidomain.com',
data: data,
success: function(data) {
$("#registration_check").fadeOut(500).hide(function() {
$(".result_1").fadeIn(500).show(function() {
$(".result_1").html(data);
});
});
}
});
return false;
});
});
the response will return 3 fields like name, email, phone on this element:
<div id="result_1"></div>
it's working nice so far, but want I plan to do is I want to display the alert or popup message if the ajax response found some of return value null. For example:
If JSON response return:
name: jhon, email: jhon#doe.com, phone: 123456789
user will redirect to the other page (done so far)
But if JSON response return
name: jane, email: jane#doe.com, phone:
The popup or alert will appeared, within text phone number empty.
If your data is a JSON object then you can do:
success: function(data) {
for (var i in data) {
if (!data[i]) {
alert(/* MESSAGE HERE */)
return;
}
}
// Your regular code here
}
You can make an associative array of your values in php file and echo it in the json format like
echo json_encode($array);
Then you will receive this in your ajax response like this
var objs = JSON.parse(data);
Then you can parse the values by keys like name, email and phone as you defined in associative array in your php file
console.log(objs.name);
console.log(objs.email);
console.log(objs.phone);
This is how you can parse the values individually. You can also apply conditions by your own way
First thing that comes to my mind: Do you need the JSON response in the document element or is it, that you dont know how to work with jQuery Ajax?
Anyway, this solution should help you in both cases:
$(document).ready(function()
{
$(document).on('submit', '#registration_check', function()
{
var data = $(this).serialize();
$.ajax({
type : 'POST',
url : 'apidomain.com',
data : data,
dataType: 'json', // tell jQuery, that the response data will be a JSON - it will be parsed automatically
success : function(data)
{
// now you have a parsed JSON object in the 'data' var
var show_alert = false;
if (data.phone === null || !data.phone.length) {
show_alert = true;
}
if (data.email === null || !data.email.length) {
show_alert = true;
}
if (show_alert) {
alert('here is the alert :)');
}
$("#registration_check").fadeOut(500).hide(function()
{
$(".result_1").fadeIn(500).show(function()
{
$(".result_1").html(JSON.stringify(data));
});
});
}
});
return false;
});
});
Related
Im quiet confused with this code. Im reading this code of ajax which inserts the data automatically. but what im confused is this line if(result=='12') then trigger ajax what does 12 means why it should be 12 then conditioned to before ajax. Apparently im still learning ajax thanks. P.S this is working well btw im just confused with the code
here is the full code of the create function javascript / ajax
$('#btnSave').click(function(){
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
//validate form
var empoyeeName = $('input[name=txtEmployeeName]');
var address = $('textarea[name=txtAddress]');
var result = '';
if(empoyeeName.val()==''){
empoyeeName.parent().parent().addClass('has-error');
}else{
empoyeeName.parent().parent().removeClass('has-error');
result +='1'; //ALSO THIS NUMBER 1 WHY SHOULD IT BE 1?
}
if(address.val()==''){
address.parent().parent().addClass('has-error');
}else{
address.parent().parent().removeClass('has-error');
result +='2'; //ALSO THIS NUMBER 2 WHY SHOULD IT BE 2?
}
if(result=='12'){ //HERE IS WHAT IM CONFUSED
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response){
if(response.success){
$('#myModal').modal('hide');
$('#myForm')[0].reset();
if(response.type=='add'){
var type = 'added'
}else if(response.type=='update'){
var type ="updated"
}
$('.alert-success').html('Employee '+type+' successfully').fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}else{
alert('Error');
}
},
error: function(){
alert('Could not add data');
}
});
}
});
As I have explained in my commentaries, and since you wanted an example. This is how I will proceed in order to avoid checking for result == '12':
$('#btnSave').click(function()
{
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
// Validate form
var empoyeeName = $('input[name=txtEmployeeName]');
var address = $('textarea[name=txtAddress]');
var formValid = true;
if (empoyeeName.val() == '')
{
empoyeeName.parent().parent().addClass('has-error');
formValid = false;
}
else
{
empoyeeName.parent().parent().removeClass('has-error');
}
if (address.val() == '')
{
address.parent().parent().addClass('has-error');
formValid = false;
}
else
{
address.parent().parent().removeClass('has-error');
}
// If form is not valid, return here.
if (!formValid)
return;
// Otherwise, do the ajax call...
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response)
{
if (response.success)
{
$('#myModal').modal('hide');
$('#myForm')[0].reset();
var type = '';
if (response.type=='add')
type = 'added';
else if (response.type=='update')
type ="updated";
$('.alert-success').html('Employee ' + type + 'successfully')
.fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}
else
{
alert('Error');
}
},
error: function()
{
alert('Could not add data');
}
});
});
It's just checking existence of values and appending string to it.
if(empoyeeName.val()=='')
This check empty name and add error if name is empty. else it concat 1 to result.
if(address.val()=='')
This check empty address and add error if address is empty. else it concat 2 to result.
So if both of them are non empty that means result will be 12 and than only you make ajax call else show error.
I have an AJAX call, as below. This posts data from a form to JSON. I then take the values and put them back into the div called response so as to not refresh the page.
$("form").on("submit", function(event) { $targetElement = $('#response'); event.preventDefault(); // Perform ajax call // console.log("Sending data: " + $(this).serialize()); $.ajax({
url: '/OAH',
data: $('form').serialize(),
datatype: 'json',
type: 'POST',
success: function(response) {
// Success handler
var TableTing = response["table"];
$("#RearPillarNS").empty();
$("#RearPillarNS").append("Rear Pillar Assembly Part No: " + response["RearPillarNS"]);
$("#TableThing").empty();
$("#TableThing").append(TableTing);
for (key in response) {
if (key == 'myList') {
// Add the new elements from 'myList' to the form
$targetElement.empty();
select = $('<select id="mySelect" class="form-control" onchange="myFunction()"></select>');
response[key].forEach(function(item) {
select.append($('<option>').text(item));
});
$targetElement.html(select);
} else {
// Update existing controls to those of the response.
$(':input[name="' + key + '"]').val(response[key]);
}
}
return myFunction()
// End handler
}
// Proceed with normal submission or new ajax call }) });
This generates a new <select id="mySelect">
I need to now extract the value that has been selected by the newly generated select and amend my JSON array. Again, without refreshing the page.
I was thinking of doing this via a button called CreateDrawing
The JS function for this would be:
> $(function() {
$('a#CreateDrawing').bind('click', function() {
$.getJSON('/Printit',
function(data) {
//do nothing
});
return false;
});
});
This is because I will be using the data from the JSON array in a Python function, via Flask that'll be using the value from the select.
My question is, what is the best way (if someone could do a working example too that'd help me A LOT) to get the value from the select as above, and bring into Python Flask/JSON.
In my webpage I am using jQuery/Ajax to save form data. After save the data using php I am showing successful message like bellow :
if($sql){
$sql_result[] = "<div class='success'>updated</div>";
}
echo end($sql_result);
In Ajax return data I am checking a condition if message is contain updated then I will hide a html element but It's not working.
Here is my jQuery code:
function save_email (element, event) {
e = $(element);
event.preventDefault();
var formData = new FormData(e.parents('form')[0]);
$.ajax({
data : formData,
cache : false,
contentType: false,
processData : false,
url : 'save_email.php',
type : 'POST',
xhr : function () {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success : function (data) {
$("#email_success").html(data);
//$("#email_success").show('slow').delay(3000).hide('slow');
if(data == "<div class='success'>updated</div>" ) {
$("#save_email_button").hide('slow');
$(".delete_ex_email_label").hide('slow');
}
},
});
}
Console log data
Updated:
alert(data) is showing this :
It's not uncommon to end up with extra whitespace in php text/html output
That is one reason it's easier to use json and check object properties , especially over comparing a complex string like you are doing.
However using trim() when comparing string results is generally a good idea
try
$.trim(data) === "<div class='success'>updated</div>")
I am trying to get the id, where the user clicked, and pass it to my controller via AJAX.
For some reason, when i try to show what i am receiving in my controller, it show an empty array.
Any idea why my alert return an empty Array?
JS Function:
function categorySelected(elem) {
$.ajax({
url: "/newgallery/creative-fields-click",
type: "POST",
data: elem.id
}).done(function (response) {
alert(response);
});
}
PHP:
public function creativeFieldsClickAction()
{
$idSelected = $this->_request->getPost();
print_r( $idSelected );
exit();
}
Data should be JSON, not integer.
data: { elemid : elem.id }
Then in PHP data can be found from $_POST['elemid']. In your code it could be like
$this->_request->getPost()['elemid'];
Or something like that.
Try by changing
In ajax
data: { id : elem.id }
And in action of controller
$ids = $_POST;
print_r($ids);
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I need some help. I'm using AJAX to submit my form to one location and then to another location. once its posted to that second location it sends an email with php to whoever I want, but i cant seem to get it to work. Can some one please help.
Here is my code below:
$(document).ready(function(){
$('input#submit').submit(function(event){
var dataString = $('form :input').serialize();
$.ajax({
type: 'GET',
url: 'http://www.domain.com/sendmail.php',
data: dataString,
success: function(result){
$('p#message').text('SUCCESS!!!');
},
error: function(result){
$('p#hint').text('there was an error');
}
});
event.preventDefault();
});
});
Unless you have some algorithms already in place, you will have problems on the server side handling the data. You may want to prepare the data and than stringify it to JSON. I would also keep the ajax functionality in its own function an use the promise feature. That way you can also use it for other calls within your script.
ajax function with deferred
function ajaxsend(data, url) {
var deferred = $.ajax({
type: 'POST',
url: url,
data: data,
dataType: "json",
});
return deferred.promise();
}
form data handling and preparation
$("form").submit(function (event) {
event.preventDefault();
var formdata = $('form').serializeArray();
var formobject = {};
// transform data to prepare for JSON
$(formdata).each(function (e) {
formobject[formdata[e].name] = formdata[e].value;
});
var data = {
json: JSON.stringify(formobject)
};
var url = 'http://www.domain.com/sendmail.php';
var url2 = 'some_other.php';
ajaxsend(data, url).done(function (response) {
// handle returned results
console.log(response);
}
ajaxsend(data, url2).done(function (response) {
// handle returned results
console.log(response);
}
}
At the server side you receive the value with:
$data = json_decode($_POST['json']);
Then you can access your data with the fieldnames of your form. For instance ..
$data -> firstname;
You can send a response from the php file:
if(success == true) {
$result = array("success" => true , "message" => "form submitted");
echo json_encode($result);
}
if(success == false) {
$result = array("success" => false , "message" => "an error occured");
echo json_encode($result);
}
At the javascript side you can catch the response values
console.log(response.success);
console.log(response.message);
Check the difference:
$('form').submit(function(event){ // 'input#submit' is a button and cannot be "submited", just clicked
var dataString = $(this).serialize(); // suffisant
$.ajax({
type: 'GET',
url: 'http://www.domain.com/sendmail.php',
data: dataString,
success: function(result){
$('p#message').text('SUCCESS!!!');
return true; // trigger the form default action
},
error: function(result){
$('p#hint').text('there was an error');
}
});
event.preventDefault();
});