Can we have an Ajax Call inside Marketo Load script - javascript

Is it possible to call an Ajax from the Marketo script? Like the below given code.
I would need an ajax call as
I want to pass the Marketo Form values to a php file
then use the values to do some calculation
then to display the results on the page
<script src="//xxxxx.marketo.com/js/forms2/js/forms2.min.js"></script>
<form id="mktoForm_1"></form>
<script>
MktoForms2.loadForm("//aqq-abc.marketo.com", "xxx-XXX-xxx", id1, function(form) {
form.onSubmit(function() {
var vals = form.vals();
$.ajax({
type: "POST",
url: "http://localhost:3422/wordpress/wp-content/plugins/calM/new_generate.php",
data: {Value1:val[0],Value2: vals[1]},
success: function( data ) {
alert(data);
},
error: function( err ) {alert("Some thing went wrong! Please try again with your values.");}
});
});
});

This should work fine in principal. Depending on what you're trying to do onValidate may be a better callback event to use.

Yes I am able to call an ajax from Marketo Script. Need to add the jQuery lib too for this. The below is the complete working snippet.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//xxxxx.marketo.com/js/forms2/js/forms2.min.js"></script>
<form id="mktoForm_1"></form>
<script>
MktoForms2.loadForm("//aqq-abc.marketo.com", "xxx-XXX-xxx", id1, function(form) {
form.onSubmit(function() {
var vals = form.vals();
$.ajax({
type: "POST",
url: "http://localhost:3422/wordpress/wp-content/plugins/calM/new_generate.php",
data: {Value1:vals.Email,Value2: vals.Phone},
success: function( data ) {
alert(data);
},
error: function( err ) {alert("Some thing went wrong! Please try again with your values.");}
});
});
});

Related

Page is getting Submit Without Refresh Via Otp?

I got this website when I fill the information and try to send the OTP page reload
Here's the website:
https://tunisia.blsspainvisa.com/english/book_appointment.php
After you fill the information and click on (Request verification code) and you will know what I mean
What I tried is:
$(function () {
$('#tunisiaThird').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'https://tunisia.blsspainvisa.com/book_appointment.php',
data: $('#tunisiaThird').serialize(),
success: function () {
}
});
});
});
I'm only a client, so I'm using Tampermonkey to inject.
You need to read more about jquery ajax post or get method here:
https://api.jquery.com/jQuery.post/
And there are tons of questions here if you search you will find tons of examples
Here is a complete example, which is getting error messages from php part and displaying on html form.
Like this: in php : $error .= 'an error happend'; and ajax $('#result').html(data.error);
to display in html.
<div id="result"></div>
$(document).ready(function(){
$('#tunisiaThird').submit(function(event){
event.preventDefault();
var formValues = $(this).serialize();
$.ajax({
url:"book_appointment.php",
method:"POST",
data:formValues,
dataType:"JSON",
success:function(data){
if(data.error === 'ok'){
$('#result').html('Successfuly');
$('#tunisiaThird')[0].reset();
setTimeout(function() {
window.location = 'index.php';
}, 1000);
} else {
$('#result').html(data.error);
}
}
});
});
});

Query database on beforeunload event

I was wondering if its possible to send a query to the database on the beforeunload event.
$(window).on('beforeunload',function() {
console.log('beforeunload called. run query');
});
If so, how would I do it? I need to run a query to insert dynamic values into the database.
You could try this, but beware that the onbeforeunload event is limited for certain browsers..
window.onbeforeunload = mySession;
function mySession(){
$.ajax({
url: "/../../myPHP.php",
async: false,
type: "GET"
});
return "WhatEverMessageYouFeelLike";
}
and your PHP executing query from AJAX handling..
$delete = "DELETE FROM MyTable WHERE id=" .$_SESSION['mySessionVariable'];
// your query..
Use a jQuery AJAX call. Assuming you're POSTing your data, try this:
$.post(
'your/url',
{
your : "Post Vars"
},
function(data) {
// not sure if you'll need to do anything here actually.
},
'json' // or 'html', or whatever you want your return format to be
);
I thinks the best way to use post by jQuery is $.post() method.but u can also use $.ajax
Sample way to use is
jQuery
$.post( "ajax/test.html", function( data ) {
$( ".result" ).html( data );
});
jQuery Ajax
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});

Get done a php file with a simple click with jquery

I am Totally Newbie, i just want a very very simple example for my question.
Think i have this piece of PHP code :
<?php
echo "Test";
?>
And a piece of jquery like this :
$(document).ready(function() {
$('.div').click(function(){
$('.loading').show();
// DO PHP NOW
$('.loading').hide();
});
});
And HTML :
<div class="div">Click here</div>
I want a simple code , to connect Jquery to PHP file.
When the .div clicked, then php code get happen with No refreshing the page. Just this.
How should i do this ?
(i need a simple way to ajaxify a PHP !)
+ If i want to do Ajax, i have to write code for every every PHP code i write or one piece of Ajax code for ALL PHP codes ?
thanks
If you want to display some value from php in your div use $(".div").load("/url/to/your/php");
Or use
$.post("url/to/php",{val:val,val:val},function(callback){
alert("callback");
$(".div").html(callback);
}
Or AJAX
$.ajax({
url: "/php/code/sd.php",
type: "POST",
date: {
username: "asdasd",
password: "asdasd"
},
success: function(callback){
$(".div").html(callback);
}
});
$(function() {
$('.div').click(function(){
var $this = $(this);
$('.loading').fadeIn(200);
$.ajax({
url: 'url_to_your_file.php',
type: 'GET',
data: {},
success: function(data) {
//do smthing OR
$(data).insertAfter($this);
},
error: function(e) {
//do smthing when error
alert('Error happen!');
console.log(e);
},
complete: function(data) {
$('.loading').fadeOut(200);
}
});
});
});

Using Two jQuery Ajax Methods in Script

Can you please let me know how I can use two Ajax call in one script and avoid conflicts? For example, I have a script like this:
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: 'POST',
url: 'nearest.php',
success: function( resp1 ){
$("#div1").html(resp1);
}
});
$.ajax({
type: 'POST',
url: 'closettime.php',
success: function( resp2 ){
$("#div2").html(resp2);
}
});
</script>
Can you please let me know how I can use both methods in the script? Thanks.
Just close DOM ready with }); at the bottom of your script block and you're all set:
$(document).ready(function() {
$.ajax({
type: 'GET',
url: 'nearest.php',
success: function( resp1 ){
$("#div1").html(resp1);
}
});
$.ajax({
type: 'GET',
url: 'closettime.php',
success: function( resp2 ){
$("#div2").html(resp2);
}
});
});// <------ YOU'RE MISSING THIS
The requests should work fine. And since you're not posting any data to the URLs I might suggest that you use type:'GET'.
Maybe you want to use the $.when method http://api.jquery.com/jquery.when/
jQuery.when understanding
possibly put one in the callback of the other, I don't understand the problem off the top my head. But if div2 is inside div 1 or something you can control the order in that fashion

jquery .ajax always returns error - data being added to database

I am trying to add users to a database using jquery ajax calls. The users get added just fine to the database, but the ajax always returns with error. I'm not sure how to retrieve the specific error either. Below is my code, form, php, and jquery.
Here is the jquery
$(document).ready(function() {
//ajax call for all forms.
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
dataType: 'json',
data: form.serialize(),
success: function (response) {
alert('something');
},
error: function() {
alert('fail');
}
});
});
});
Here is the PHP
<?php
include 'class_lib.php';
if(isset($_POST['username'])) {
$user = new Users;
$user->cleanInput($_POST['username'], $_POST['password']);
if($user->insertUser()) {
echo json_encode('true');
} else {
echo json_encode('false');
}
}
Here is the HTML
<div id='newUser' class='tool'>
<h3>New User</h3>
<form method='post' name='newUser' data='../php/newUser.php'>
<span>Username</span><input type='text' name='username'><br>
<span>Password</span><input type='password' name='password'>
<input type='submit' name='submit' class='button' style='visibility: hidden'>
</form>
<span class='result'> </span>
</div>
#Musa, above you mentioned
My guess is its a parsing error, try removing dataType: 'json', and see if it works
You absolutely solved the problem I was having! My ajax post request was similar to above and it just kept returning to the 'error' section. Although I checked using firebug, the status was 200(ok) and there were no errors.
removing 'dataType:json' solved this issue for me. Thanks a lot!
Turns out I had to add async: false to the $.ajax function. It wasn't getting a response back from the php.
I know this is an old question but I have just run into a weird situation like this ( jquery ajax returns success when directly executed, but returns error when attached to button, even though server response is 200 OK )
And found that having the button inside the form tags caused JQuery to always return error. Simply changing the form tags to div solved the problem.
I believe JQuery assumes the communication should be form encoded, even though you say it is application/json.
Try moving your button outside your form and see what happens...
I had the same problem and discovery there. All the time the problem is the version of my jQuery, I had use jquery version (jquery-1.10.2.js) but this version is not Ajax stablish. So, I change version for (jquery-1.8.2.js) and this miracle heppened.
Good Luck Guy!
You should specify status Code 200 for successful response.
<?php
http_response_code(200);
?>
See here: http://php.net/manual/en/function.http-response-code.php
The first solution
Try to remove dataType in your js file like that:
$(document).ready(function() {
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
data: form.serialize(),
success: function (response) {
alert('something');
},
error: function() {
alert('fail');
}
});
});
});
The second solution
Send a real clean JSON to AJAX like that:
PHP
if(isset($_POST['username'])) {
$user = new Users;
$user->cleanInput($_POST['username'], $_POST['password']);
if($user->insertUser()) {
$error = [
"title"=> 'true',
"body"=> 'some info here ... '
];
echo json_encode($error);
} else {
$error = [
"title"=> 'false',
"body"=> 'some info here ... '
];
echo json_encode($error);
}
}
JavaScript
$(document).ready(function() {
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
dataType: 'json',
data: form.serialize(),
success: function (data) {
let x = JSON.parse(JSON.stringify(data));
console.log(x.title);
console.log(x.body);
},
error: function() {
//code here
}
});
});
});

Categories