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();
});
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I was looking for a way to select elements that we echoed by PHP using JS.
I found out there is a way by using "delegate()". So, here I am trying to select the element which is clicked upon, then retrieve details corresponding to it from the database.
The console prints "Error!"
Is there something that I am missing. I am still learning jQuery. Is there any other way to do what I am trying to do?
NOTE: Also for some reason, this script does not work in an external JS file.
This is the script I wrote
$("body").delegate( "li.allfriends", "click", function() {
var friend = $(this).html();
var username = "<?php echo $_SESSION['user'] ?>";
var data = { 'action': 'showExpenses', 'username': username, 'friend': friend };
$.ajax({
url: 'ajax.php',
dataType: 'json',
data: data,
method: 'POST',
success: function (data) {
console.log('Success!');
console.log(data);
},
error: function (error) {
console.log('Error!');
}
});
});
This is where I am processing it
if($_POST['action'] == 'showExpenses') {
$username = $_POST['username'];
$friend = $_POST['friend'];
$rows = $misc->showExpensesForSelectedFriend($username, $friend);
return json_encode($result);
}
This is the final function where I am retrieving data
public function showExpensesForSelectedFriend($username, $friend) {
$username = $this->sql->escape($username);
$friend = $this->sql->escape($friend);
$rows1 = $this->sql->getDatas('expense', 'paidBy', $username, 'owedBy', $friend);
$rows2 = $this->sql->getDatas('expense', 'paidBy', $friend, 'owedBy', $username);
foreach($rows2 as &$item) {
array_push($rows1, $item);
}
return $rows1;
}
Console prints Error!, Later I checked showExpensesForSelectedFriend() was working fine.
Maybe this should be your problem. json_encode($result); try to make this variable into an array like this.
if($_POST['action'] == 'showExpenses') {
$username = $_POST['username'];
$friend = $_POST['friend'];
$rows = $misc->showExpensesForSelectedFriend($username, $friend);
$result = array();
if(count($rows) == 0) {
$result['status'] = 0;
}
return json_encode($result);
}
You can call the return value such data.status.
$.ajax({
url: 'ajax.php',
dataType: 'json',
data: data,
method: 'POST',
success: function (data) {
console.log('Success!');
console.log(data.status);
},
error: function (error) {
console.log('Error!');
}
});
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;
});
});
I want to know is that possible to send data from one ajax by another ajax or not?
Sounds confusing I know, but here is explanation:
I have payment method where it gets data and handling them by Ajax (unfortunately the creators of this API limited their code a lot) so even if i try to add input request in controller code of that Ajax nothing will work, that's why I need to make another Ajax to handle that input request.
Lets explain more by codes:
controller
public function orderspayonline(Request $request, $id){
error_log('masuk ke snap token dri ajax');
$midtrans = new Midtrans;
//products data + user info etc.
//here magic happens
try
{
$snap_token = $midtrans->getSnapToken($transaction_data);
echo $snap_token;
}
catch (Exception $e)
{
return $e->getMessage;
}
}
If I add anything (I mean anything) in that try{ part it will stop functioning and return error! `even I tried to redirect back my users except echoing token code that gave error as well. So it seems I really don't have any option here but to create new function and Ajax.
JavaScript
<script type="text/javascript">
$('.pay-button').click(function (event) {
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});
event.preventDefault();
// $(this).attr("disabled", "disabled");
var prdfoId = $(this).data('id');
$.ajax({
url: '{{url("orderspayonline")}}/'+encodeURI(prdfoId),
type: "POST",
cache: false,
success: function(data) {
var resultType = document.getElementById('result-type');
var resultData = document.getElementById('result-data');
function changeResult(type,data){
$("#result-type").val(type);
$("#result-data").val(JSON.stringify(data));
}
snap.pay(data, {
onSuccess: function(result){
changeResult('success', result);
console.log(result.status_message);
console.log(result);
$("#payment-form").submit();
},
onPending: function(result){
changeResult('pending', result);
console.log(result.status_message);
$("#payment-form").submit();
},
onError: function(result){
changeResult('error', result);
console.log(result.status_message);
$("#payment-form").submit();
}
});
}
});
});
</script>
The part I need to manipulate is snap.pay(data, { where results gets back.
Currently they are return in console and disappear in a sec as the result of echo $snap_token; in my controller.
I have tried to get them in hidden input, but as I mentioned I cannot get results because I can't change my try code, even I tried to get them after catch part closed, the same thing happens Error.
Question
How can I get my results in controller?
I need to update my database with that results.
Thanks.
From what I can see you have two choices.
Add another client-side AJAX call within the snap.pay function
Redirect the submission of payment-form towards your own app and then do the onward submission from the server-side.
Option 1:
function serverSubmit(d) {
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});
$.ajax({
url: '{{url("newroute")}}',
type: "POST",
cache: false,
data: d
});
};
Then amend snap.pay to submit, e.g.
snap.pay(data, {
onSuccess: function(result){
changeResult('success', result);
console.log(result.status_message);
console.log(result);
serverSubmit(result); // <----------
$("#payment-form").submit();
}
...
You may want to encrypt the data if it is sensitive, and you may want to decide not to submit the form if you don't get a successful result from the serverSubmit. You may also want to submit supplemental data beyond the result, but this is a start.
Option 2
Change the <form id="payment-form... action to {{url('newroute')}}
In your controller add a new method and map a post newroute to it.
public function new_method(Request $request)
{
$data = $request->validate(...);
YourModel::create($data); //however you want to save it
$url = 'old_form_submit_URL';
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* There was an error */ }
}
This question already has answers here:
event.preventDefault() vs. return false
(14 answers)
Closed 6 years ago.
after submitting a form to email i get 2 email instead 1 how can i fix it? I need that only 1 letter come to email
js:
app.controller('threeCtrl',function($scope){
$("#subBusinessOne").click(function() {
var url = "businessFormOne.php";
$.ajax({
type: "POST",
url: url,
data: $("form#businessFormOne").serialize(),
success: function(data)
{
var name = $("input[name=name]").val("");
var rel= $("input[name=phone]").val("");
}
});
return false; // avoid to execute the actual submit of the form.
});
});
php:
<?php
$ToEmail = 'myemail.com';
$EmailSubject = 'Охрана бизнес-обьектов';
$mailheader = "From: ".$_POST["email"]."\r\n";
$MESSAGE_BODY = "Имя: ".$_POST["name"]."";
$MESSAGE_BODY .= "Телефон: ".$_POST["phone"]."";
mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("Failure");
?>
I guess that #subBusinessOne is a form submit button. You're sending an AJAX request and then submitting the form again as a normal HTTP request.
Instead of detecting button click event, you should check if the form has been submitted, then prevent default action and send the AJAX request. Your JS code would then look like this:
app.controller('threeCtrl',function($scope){
$("#businessFormOne").submit(function(e) {
e.preventDefault(); // this is to avoid the actual submit
var url = "businessFormOne.php";
$.ajax({
type: "POST",
url: url,
data: $("form#businessFormOne").serialize(),
success: function(data)
{
var name = $("input[name=name]").val("");
var rel= $("input[name=phone]").val("");
}
});
});
});
app.controller('threeCtrl',function($scope){
$("#subBusinessOne").submit(function(e) {
e.preventDefault();
var url = "businessFormOne.php";
$.ajax({
type: "POST",
url: url,
data: $("form#businessFormOne").serialize(),
success: function(data)
{
var name = $("input[name=name]").val("");
var rel= $("input[name=phone]").val("");
}
});
});
});
Use .preventDefault()
app.controller('threeCtrl',function($scope){
$("#subBusinessOne").click(function(e) {
e.preventDefault();
var url = "businessFormOne.php";
$.ajax({
type: "POST",
url: url,
data: $("form#businessFormOne").serialize(),
success: function(data)
{
var name = $("input[name=name]").val("");
var rel= $("input[name=phone]").val("");
}
});
return false; // avoid to execute the actual submit of the form.
});
});
I guess you are trying to make cross AJAX request, and it's reason why you got 2 email instead 1. Because first request with method OPTIONS (to check available to send requests from other domains) and second request with method POST
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I have simple registration form. Ajax and form works fine but can't connect them by variable, I mean when ajax check that email is in database register should stop by variable error but it isnt.
Code:
$('.login').submit(function(e) {
e.preventDefault();
var error = 0;
var self = $(this);
var $name = self.find('[type=name]');
var $email = self.find('[type=email]');
var $pass = self.find('[type=password]');
//MY AJAX
var email = $email.val();
$.ajax({
url: 'http://localhost/FPD/nowe/inc/rejestracja.php?action=emailcheck',
data: {
'email': email
},
type: 'POST',
success: function(odp) {
if (odp == 1) {
createErrTult("Błąd! taki email już istnieje w bazie!", $email)
//THAT ERROR VARIABLE DOESNT WORK OUTSIDE AJAX FUNCTION
error++;
}
},
error: function(xhr, textStatus, error) // THOSE ROWS
{
alert(error);
}
});
if (error!=0)return;
//THAT STILL WORKS EVEN AJAX ERROR
self.find('[type=submit]').attr('disabled', 'disabled');
self.children().fadeOut(300,function(){ $(this).remove() })
$('<p class="login__title">sign in <br><span class="login-edition">welcome to A.Movie</span></p><p class="success">You have successfully<br> signed in!</p>').appendTo(self)
.hide().delay(300).fadeIn();
// var formInput = self.serialize();
// $.post(self.attr('action'),formInput, function(data){}); // end post
}); // end submit
The reason is ajax is called Asynchronously. You have to make async: false in your ajax call. So your code will become :
$.ajax({
url: 'http://localhost/FPD/nowe/inc/rejestracja.php?action=emailcheck',
data: {
'email': email
},
async : false, //<----
type: 'POST',
success: function(odp) {
if (odp == 1) {
createErrTult("Błąd! taki email już istnieje w bazie!", $email)
//THAT ERROR VARIABLE DOESNT WORK OUTSIDE AJAX FUNCTION
error++;
}
},
error: function(xhr, textStatus, error) // THOSE ROWS
{
alert(error);
}
});
This will ensure that nothing will executed after ajax call unless you get your response.