$.POST on a squarespace page - javascript

I have a custom form that posts to a 3rd party server as an appointment booking module. If i submit the form thru the action of the <form> tag i do recieve the email, but i would like to submit the form using $.POST so that i can alter the redirect URL.
I have jQuery running successfully on my site, and if i use:
$.post('URL', {data}).then(function () {alert('Form Submitted!')});
The redirect (or alert for this example) works fine, but the POST doesnt seem to actually run. Has anyone had a similar issue and found a way to resolve this?
ACTUAL CODE
I am using mailthis.to's API to avoid having to run a server just to do this
$('#sendForm').click(()=>{
$.post('https://mailthis.to/support#gadget-pro.com', {
Name:$('#Name').val(),
Email:$('#Email').val(),
Phone:$('#Phone').val(),
Device:$('#device').val(),
Repair:$('#repairType').val(),
Price:$('#price').val()
}).then(function (data) {
location.href = 'https://gadget-pro.com/formconfirm'
});
})

I would say to update your code to return back the page. you are likely not triggering the post to page properly or there is an error.
alos console.log the post data before to know what is being sent.
update your code to
console.log(data);
$.post('URL', {data}).then(function (retpage) {console.log(retpage)});

Related

Why Ajax is not able to send array data?

Trying to send form data to a PHP page, all parameters are sending successfully except data:imagesBase64
this imagesBase64 is an array which I am trying to send, a few hours ago everything was fine but now it is not working I really don't know why.
All values are Posting successfully only this value is not posting also I am not able to see error in console because it redirected to URL where I am posting the data
var imagesBase64 = ['abcdfd','dhydsu333ud','djhbsd'];
$(function () {
var frm = $("#saveform");
frm.submit(function (ev) {
$.ajax({
type: frm.attr("method"),
url: frm.attr("action"),
data: {
data: imagesBase64,
PubId: $("#Publications").val(),
sdate: $("#datepicker").val(),
pnumber: $("#pnumber").val()
},
cache: false,
error: function (err, data) {
console.log("There was an error. Try again please!" + data, err);
},
success: function (data) {
alert("New message received");
},
});
ev.preventDefault();
});
});
In PHP page -
print_r($_POST['data']);
it gives an error undefined data, though when I tried with postman everything is working fine.
also I am not able to see error in console because it redirected to URL where I am posting the data
That's the problem.
You are submitting data to the server using a regular form submission and not with Ajax. Since your Ajax code isn't used, the data added in from outside the form isn't included.
This is usually caused by the regular form submission interrupting the Ajax request, but since you have ev.preventDefault(); that shouldn't be the case here.
Possible reasons that might apply are:
var frm = $("#saveform") fails to find the form because the selector is wrong or the form is added after the document is loaded with other JS
You don't have jQuery loaded so the call to $ fails
You have jQuery Slim loaded which doesn't include an ajax method (moving the call to preventDefault so it is before the call to ajax would help catch this).
Your browser's developer tools should have an called something like "Persist Logs" which will prevent it from clearing the console when you navigate to a new page. Turn it on to aid your debugging. Here's what it looks like in Firefox:

Page redirect from external php file (in ajax call)

I have this Salesforce "Web-to-Lead" form that I'm working with (on an IIS server), and I got it validating properly in an Ajax call (using the roscripts.com ajax validation as a starting point... this uses the Mootools library to carry out its Ajax functions), as well as sending all of the validated data using cURL, however I want the form to redirect to a new page after validation succeeds. The Ajax call runs every time the Submit button is clicked and either displays errors on the page or runs whatever is included in the "else" section of the validation code.
The Ajax function:
window.addEvent('domready', function() {
$('registerForm').addEvent('submit', function(e) {
new Event(e).stop();
var log = $('log_res').empty().addClass('ajax-loading');
this.send({
update: log,
onComplete: function() {
log.removeClass('ajax-loading');
//adding a header redirect here works, but redirects every time ajax call runs, regardless if validation succeeds or not
}
});
});
});
The "action" php file function:
<?php
if (rule){ //validation errors }
else { //where all of the logic happens after validation succeeds
//cURL function
//redirect attempts:
header( 'Location: http://www.place.com'); // doesn 't work
echo '<meta http-equiv="refresh" content="2" ; url="http://www.place.com">'; //resets the form, but doesn't redirect to www.place.com
};
?>
I'm totally stumped here, I can't get this darn thing to redirect, no matter how hard I try. Any help would be greatly appreciated!
From what I can tell of MooTools AJAX, the onComplete handler will fire any time AJAX is finished -- even when there are errors. That may be fine for removing your loading message, but you'll probably want to use onSuccess for a successful handler and onFailure for a failed request. While your script doesn't appear to be using MooTools directly, this is how MooTools AJAX works.
See the "Ajax!" section on http://mootools.net/ for an example.

how to send asynchronous request to php page using jquery ajax

i am new to web development creating a kind of social networking website for college project. I want to include update the messages count in the message menu every time there is a new msg in the database for the user(like facebook message menu on homepage)
But it's frustrating learning ajax, however after searching on web and reading some topics from some books I came to the solution that i can make an $ajax call in my js file in the homepage and send data ('name'=>'user') stored in javascript cookie that i have created on loading of home page after the user login, to a php file which will search across the recent_msg table in database to fetch the recent message for the logged in user if any after fetching the php file will create the html file with code snippet and further another jquery code will append that snippet from file to the message list menu.
the PHP part is not the problem but how can i send the username to the php file using jquery ajax api, here is the code what i think i can apply but i am doubtful in that if this is the correct way
$(document).ready(function{
setInterval ( function()
{
var usr = getCookie("name");
$.ajax ( {
url: '/phpScripts/recent_msg.php',
type: 'POST',
data: usr,
success: function(data){
}
} );
},10);
});
what is the purpose of success function in the code?
data needs to be in the form of an object / key-value-pair (EDIT: or if a string, as a valid querystring). data: { name: usr }. However, since it's in a cookie, your PHP page will have direct access to that cookie. It's safer to let your session cookie tel the PHP page who the user is instead of relying on an AJAX call to tell the PHP page who it is.
http://php.net/manual/en/features.cookies.php
So I'd drop data from your AJAX call altogether, and in your PHP page, use $_COOKIE["name:"]
Then whatever HTML gets passed back from the PHP page will arrive in the data call. If it's HTML, then simply add it to your HTML to some message div, such as.
<div id="recent-messages"></div>
<script type="text/javascript">
$(document).ready(function{
setInterval ( function()
{
var usr = getCookie("name");
$.ajax ( {
url: '/phpScripts/recent_msg.php',
type: 'POST',
data: usr,
success: function(data){
$('#recent-messages').html(data);
}
} );
},10);
});
</script>
The success function executes whenever your ajax call completes successfully. This means that the page actually exists and no server-side errors occurred on the page. The variable data will contain whatever information is returned from the page on the sever /phpScripts/recent_msg.php. Generally this is either json or xml, but it entirely depends on your implementation of recent_msg.php.
If the user has to log in that means you have to have created a session. In that case you can store the logged in user's information such as their name in $_SESSION on the server and there is no need to store it as a cookie. Since $_SESSION is already on the server, there is no need to send that data via ajax in any case.

jQuery: handling mixed html/js ajax response

Having trouble accessing javascript code in a mixed html/js ajax response. jQuery ajax doc states:
If html is specified, any embedded JavaScript inside the retrieved
data is executed before the HTML is returned as a string
Which I can confirm by adding a simple snippet to the html reply:
<script type="text/javascript"> alert($(this)); </script>
How then to retain access to the js code vs. one-and-done execution?? Trying to implement a modal login (to prevent data loss on session timeout in form submission screens). Of course I need to be able to access the ajax'd js code to then validate email/password fields and ajax authenticate user credentials on the remote server.
Here's the modal login coffeescript snippet:
# submit form
$.ajax
success: (data) -> ...
error: (data) ->
popAuth(data.responseText) if(data.status == 401)
popAuth = (title) ->
$.fancybox({
href: "/login"
ajax: { type: "GET" }
title: title
})
Perhaps I can add a success callback to popAuth() ajax options to store the returned js code? How about jQuery "live" handler? Unfortunate that this scenario is not as straight forward as one would hope ;-) I have seen $.getScript as an option, but would prefer to not separate html from js since server-side already assembles html + js and the original ajax call pulls it all down in one go. (i.e. avoid creating a dedicated server-side controller to send back js file content bundle)
I am of course open to alternative solutions to workaround this issue. For example, I could store login fields and js login validation code on every screen (JVM CRUD application living behind WordPress front end so every screen is basically auth required) in a hidden div, and then pop the modal login window "locally", which I assume would get around the annoying one-and-done js execution of remote ajax content.
Anyway, Ideas appreciated! client-side is both wonderfully simple and...horribly complex ;-)
Ok, fending off the veritable deluge of responses, I'll take a stab myself.
As I understand it now, since mixed html/js content is one-and-done executed, we have one chance to capture ajax response js code and bind it to current scope.
First, in the original ajax call (i.e. form submit that returns a potential 401 not authorized status) set the context of the modal login's ajax setup to $(this), the currently executing scope that contains jquery validation and other shared js code needed for modal login ajax submit to work.
In my case, using fancybox, adding context param it now looks like:
popAuth = (title) ->
$.fancybox({
href: "/login"
ajax: { type: "GET" }
context: $(#)
title: title
})
Then, since the parent window contains the majority of needed javascript, the only requirement is to create a js file that binds modal login form button click event to validation and $.ajax submission.
# login.coffee
jQuery ->
$('#loginSubmit').click (e) ->
e.preventDefault()
isValid = $('#loginForm').validate().form()
if isValid
$('#spinner').show()
$.ajax
data: $('#loginForm').serialize()
success: (data) ->
$('#status').fadeOut()
location.href = '/foo'
error: (data) ->
$('#status > div').html( data.responseText )
$('#status').fadeIn()
complete: () ->
$('#spinner').hide()
Done, all good, works ;-)

using Blobstore Python API with ajax

there is any sample showing how to use the blobstore api with ajax?
when i use forms works fine, but if i use jquery i don't know how to send the file and i get this error:
blob_info = upload_files[0]
IndexError: list index out of range
I have this code in javascript
function TestAjax()
{
var nombre="Some random name";
ajax={
type: "POST",
async:true,
//dataType:"json",
url:"{{upload_url}}",
data:"nombreEstudio="+nombre,
error: function ()
{
alert("Some error");
$("#buscando").html("");
},
success: function()
{ alert("it's ok") }
};
$.ajax(ajax);
}
When i use forms the file it's sended with a input tag (exactly like the doc's sample)
I wrote a series of posts about exactly this.
Somehow you still need to get the multipart form data request to the server... so when you're using forms, I assume your <form> tag has something like this on it: enctype="multipart/form-data", right?
When you're just sending a "POST" via ajax, you're losing that multipart request, which is where your file is.
There are some jQuery "ajax file upload" plugins out there that may help you out.
Hope this helps!
** EDIT **
I guess one thing I can add to this is usually ajax file uploads (on the client) are implemented by either creating a hidden iframe, and using that iframe to submit a form, or using a form and posting it via JavaScript.

Categories

Resources