send variable with ajax when load page - javascript

try setting my code for send variable from view to controller,but my code is not run and show error
Uncaught ReferenceError: $ is not defined
view
<script type="text/javascript">
$(document).ready(function() {
var st = $('#st').val();
var postdata = { st: st };
$.ajax({
type: 'POST',
url: '<?= base_url();?>task_tickets/tes',
data: postdata,
success: function(response) {
console.log(response);
}
});
});
</script>
controller
function cek(){
echo $st;
}

Looks like either you have not included jQuery plugin or added after your JavaScript code. $ is alias to jQuery.
In your view before script tag, include this
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.js"></script>

Related

Send variable to PHP file

In a WordPress post I'm trying to send data to a PHP file stored in the root folder of my website with this code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" type="text/javascript">
console.log('hi');
var cen = document.getElementById("centro").value;
$.ajax({
url: 'centroUser.php',
type: "POST",
data: { 'cen': cen },
success: function(data){
console.log(data);
}
});
</script>
centroUser.php:
<?php
$uid = $_POST['cen'];
echo($uid);
?>
The problem is that I can't get it to work, the variable $uid doesn't get echoed and even the console.log('hi') doesn't get called. I'm new to AJAX so I don't really know what I'm doing wrong, I have tried looking for other answers but I couldn't find something that worked.
Your <script> tag has a src and a body.
Try:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
console.log('hi');
var cen = document.getElementById("centro").value;
$.ajax({
url: 'centroUser.php',
type: "POST",
data: { 'cen': cen },
success: function(data){
console.log(data);
}
});
</script>
If the src has a URI value, user agents must ignore the element's contents and retrieve the script via the URI - see here.

Ajax call in wordpress doesn't go to admin-ajax.php

I'm trying to call a function using ajax in a wordpress admin submenu. Here is my code.
jQuery('#deleteProj').submit(ajaxSubmit);
function ajaxSubmit(){
var tobeDeleted = jQuery(this).serialize();
alert(tobeDeleted);
jQuery.ajax({
type:"POST",
url: ajaxurl,
data: tobeDeleted,
success:function(){ alert(tobeDeleted);},
error:function(errorThrown){alert(errorThrown);}
});
return false;
}
However, the code opens a new page querying the admin.php file looks like this:
wp/wp-admin/admin.php?q=id&action=deleteproj
I'm really at a loss for why this is happening. I'm calling the function from inside my plugin's admin menu
Update
The issue turned out to be that I had to define the php functions on the main file of my plugin. I also made sure to absolutely define the location of admin-ajax.php this allowed the jQuery to properly execute.
Try this:
jQuery('#deleteProj').submit(function() {
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
var formData= jQuery(this).serialize();
jQuery.ajax({
url:ajaxurl,
action:'function_name',
data:formData,
type: "POST",
success: function(data) {
// return
}
});
return false;
});
Regards:)
It seems like you are redirecting instead of ajaxing ,try changing you submit event to a click event
jQuery('#deleteProj').find('[type="submit"]').click(function(e){
e.preventDefault();
var tobeDeleted = jQuery(this).serialize();
alert(tobeDeleted);
jQuery.ajax({
type:"POST",
url: ajaxurl,
data: tobeDeleted,
success:function(){ alert(tobeDeleted);},
error:function(errorThrown){alert(errorThrown);}
});
});
If you have written the code in side your php file, then the answer from Gulshan is correct, but if you have written this code in a different .js file you can not access the ajax url into it. Then you need to localize the script to add the ajax url.
Please follow the example code :
wp_enqueue_script( 'mainscript', get_template_directory_uri() . '/js/main.js', array(), 'v1', true );
wp_localize_script( 'mainscript', 'sitesettings', array('ajaxurl' => admin_url( 'admin-ajax.php' )));
for both the function you need place same handle [ 'mainscript' ], now in your main.js file you need to write the following code :
jQuery('#deleteProj').submit(function() {
var ajaxurl = sitesettings.ajaxurl; // here you are accessing the admin-ajax.php
var formData= jQuery(this).serialize();
jQuery.ajax({
url:ajaxurl,
action:'function_name',
data:formData,
type: "POST",
success: function(data) {
// return
} });
return false;
});
Hope this work for you

How to upload a HTML variable to a PHP file using AJAX

On my website I am trying to basically generate a random code (which I will set up later) and then pass that code into a PHP file to later retrieve it when the client needs it. But my code just isn't working.
Here is the code:
Javascript/HTML:
function init() {
var code = "12345";
$.ajax({
type: 'POST',
url: 'codes.php',
data: { code: code},
success: function(response) {
$('#result').html(response);
}
});
}
PHP:
<?php
$code = $_POST['code'];
echo $code
?>
So what I understand that is supposed to happen is that the code is uploaded or 'posted' to the php file and then the #result is the echo $code. None of that happens and I have no idea.
Your code working perfect with some basic changes.
You need a html element with id 'result'.
And then you need to call your init() as per requirement.
<div id="result"></div>
<script>
function init() {
var code = "12345";
$.ajax({
type: 'POST',
url: 'codes.php',
data: { code: code},
success: function(response) {
$('#result').html(response);
}
});
}
init();
</script>
I tried this on my server in the head of my document, and it worked :)
I used on complete instead of on success.
<script type="text/javascript" src="https://code.jquery.com/jquery.min.js"></script>
<script>
function init() {
$.ajax({
type: "POST",
url: "codes.php",
data: {
'code': '12345'
},
complete: function(data){
document.getElementById("result").innerHTML = data.responseText
},
});
}
init();
</script>
with codes.php the same as you have :)
just a few notes:
Make sure you point your url to the correct file. You can check it by using the console network. Or you can simply print anything out, not just the $_POST data. e.g:
echo 'Test info';
Open browser developer panel, to see if is there any client code issue. For example, document with id 'result' existed, or you have not included jquery in. The developer console will tell you everything on the client side. For Chrome, check it out here https://developer.chrome.com/devtools
Have you actually called init() ?

Can we have an Ajax Call inside Marketo Load script

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.");}
});
});
});

CKEDITOR ajax posts

I am trying to make an admin page using AJAX so when the client updates information in the CKEDITOR it doesn't have to take him to a new page. Getting data from input fields are easy enough using the .val() function, but because textareas are not updated on the fly, I can't use that same function. Heres as far as I got:
// this replaces all textarea tags into CKEDITORS
<script type="text/javascript">
CKEDITOR.replaceAll();
</script>
//this attempts to grab all data from inputs and textareas
$(function() {
$("#submit").click(function() {
var newsTitle = $("#newsTitle").val();
var editNews = CKEDITOR.instances.editNews.getData();
var contactTitle = $("#contactTitle").val();
var editContact = CKEDITOR.instances.editContact.getData();
var linksTitle = $("#linksTitle").val();
var editLinks = CKEDITOR.instances.editLinks.getData();
$.ajax({
type: "POST",
url: "update.php",
data: 'newsTitle='+newsTitle+'&editNews='+editNews+'&contactTitle='+contactTitle+'&editContact='+editContact+'&linksTitle='+linksTitle+'&editLinks='+editLinks,
cache: false,
success: function(){
updated();
}
});
return false;
});
});
the getData() function seemed like it would work because I tested it with alerts and it was grabbing the data from the editors, but once I would try and update, it wouldn't work...
any ideas?
This code replaces the textarea:
<script type="text/javascript">
CKEDITOR.replace( 'TEXTAREA_ID', {
extraPlugins : 'autogrow',
removePlugins : 'resize',
entities : false
});
</script>
In the JS file this is the code and I am using Jquery Validator Plugin:
$(document).ready(function(){
jQuery.validator.messages.required = "";
$("#FormID").validate({
submitHandler: function(){
var ContentFromEditor = CKEDITOR.instances.TEXTAREA_ID.getData();
var dataString = $("#FormID").serialize();
dataString += '&ContentFromEditor='+ContentFromEditor;
$.ajax({
type: "POST",
url: "Yourfile.php",
data: dataString,
cache: false,
success: function(html){
YOU WORK WITH THE RETURN HERE
},
error: function(xhr, ajaxOptions, thrownError){
alert(xhr.responseText);
}
});
return false;
}
});
});
This is the line that most of the time creates the error:
CKEDITOR.instances.TEXTAREA_ID.getData();
After the instances always comes the ID of the textarea.
I have my own config.js that you can get from the ckeditor website or from the examples.
Tage a look at the CKEditor function/adaptor for jQuery
http://docs.cksource.com/CKEditor_3.x/Developers_Guide/jQuery_Adapter
Because setting and retrieving the editor data is a common operation, the jQuery Adapter also provides the dedicated val() method:
// Get the editor data.
var data = $( 'textarea.editor' ).val();
// Set the editor data.
$( 'textarea.editor' ).val( 'my new content' );
With this code, my problems were solved.
I updated the field running ckeditor to be seen in serialize.
$('#form').find('.class').each(function(index) {
$(this).val(CKEDITOR.instances[$(this).attr('id')].getData());
});

Categories