Ajax is not getting results - ajax

I just got into ajax and I cannot understand what is wrong about the code?
index.html
<html>
<head>
<title>Ajax call</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
<head>
<body>
<script>
var UserID = 'myname';
var EmailAddress = 'myname#mail.com';
$.ajax({
url: "ajax.php",
type: "get", //send it through get method
data:
{
ajaxid: 4,
UserID: UserID,
EmailAddress: EmailAddress
},
success: function(response)
{
//Do Something
Alert("Sucess");
},
error: function(xhr)
{
//Do Something to handle error
Alert("Failure");
}
});
</script>
</body>
</html>
ajax.php
<?php
foreach ($_GET as $key => $value) {
echo $key . ' => ' . $value . '<br />';
}
?>
After resolving this issue, my main goal is to replace the code in the php file with a function that connects to a SQL Server and retrieve some data using the data sent by the ajax call. I will try this later.
Regards,
Elio Fernandes

Change Alert("smth") to alert("smth")
Then in success function you need to "send" server response to html
success:function(response){
alert('success')
$('body').append(response)
}

Related

Vue JS Ajax Calls

I am trying to make the change from jQuery to Vue.js and am having some difficulty running an Ajax Call using vueresource. Below is a sample script I am using, with both jQuery and Vuejs. Both trying to access the same ajax call. The jQuery call works, the vuejs call doesn't. The sendAjax method is being called because the first 2 alerts show - then nothing.
Edit - this is only causing an error while running the Ajax call through Wordpress. Outside of WP, it does work. Any ideas??
<!DOCTYPE html>
<html>
<head>
<title>Vue Resource</title>
<script src="https://cdn.jsdelivr.net/npm/jquery#3.2.1/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/vue/latest/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-resource#1.5.1"></script>
</head>
<body>
<button id="jQueryAjax">Jquery AJAX</button>
<div id="myvue">
<button #click.prevent="sendAjax()">AJAX</button>
</div>
<script>
let AjaxUrl = "http://localhost:8888/mySite/wp-admin/admin-ajax.php";
const postData = { action: 'my_ajaxcall', function: 'AjaxTest' };
Vue.use(VueResource);
const ajax_app = new Vue({
el: '#myvue',
methods: {
sendAjax() {
alert("VueAjax");
alert(JSON.stringify(postData));
this.$http.post(AjaxUrl, postData).then(res => {
alert(JSON.stringify(res));
});
}
}
});
$("#jQueryAjax").click(function() {
alert("jQueryAjax");
alert(JSON.stringify(postData));
alert(AjaxUrl);
$.ajax({
type: 'POST',
url: AjaxUrl,
data: postData,
dataType: 'json',
success: function(data) {
alert(JSON.stringify(data));
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error");
}
});
});
</script>
</body>
</html>
You AJAX call probably encounters an error and you handle only the successful calls. Please extend your sendAjax function like this:
this.$http.post(AjaxUrl, postData).then(res => {
alert(JSON.stringify(res));
}, err => {
alert(err);
});
Now an error should be alerted.
BTW: It is better to use console.log() instead of alert(), it is much more readable and you won't have to confirm every alert.
After #mbuechmann pointing me to be able to see the actual error, I was able to determine that the issue I was having was actually to do with Wordpress. In order to use the Wordpress Ajax handler, you need to send an action to the REQUEST header. To do this, you need to send FormData, and without sending headers.
This code was found in this question : Custom Shortcode AJAX 400 Bad Request and enabled me to get my Fetch working with Wordpress.
var data = new FormData();
data.append( 'action', 'aj_ajax_demo' ); data.append( 'nonce', aj_ajax_demo.aj_demo_nonce );
fetch(aj_ajax_demo.ajax_url, {
method: 'POST',
body: data, }).then(response => {
if (response.ok) {
response.json().then(response => {
console.log(response);
});
} });

Ajax post calling wrong url

Good day.
I want to know why is my project calling the wrong url? The code is:
SCRIPT
$.ajax({
type: "POST",
url: "/Application/Franchise",
data: JSON.stringify(sendInfo),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
$('#myModal3').modal('hide'); //hide the modal
},
error: function () {
alert("Error while inserting data");
}
});
CONTROLLER
public class ApplicationController : Controller
{
public ActionResult Franchise()
{
return View();
}
}
I even tried changing the url by 'Url.Action("Franchise", "Application")' but still the system kept on bringing me to http://localhost:49267/Home/Franchise.
I can't understand what is wrong here. Is there a bug in jquery ajax url post?
Thanks in advance.
UPDATE
<button class="btn btn-success" type="button" id="btnCapture">Submit</button>
#section Scripts{
<script src="~/Scripts/webcam.min.js"></script>
<script src="~/Scripts/webcam.js"></script>
<script language="JavaScript">
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 90
});
Webcam.attach( '#my_camera' );
</script>
<script language="JavaScript">
function take_snapshot() {
Webcam.snap( function(data_uri) {
document.getElementById('results').innerHTML =
'<img id="base64image" src="' + data_uri + '"/>';
} );
}
</script>
<script>
$(document).on("click", ".open-camera", function () {
var myBookId = $(this).data('id');
$(".modal-body #franid").val(myBookId);
})
</script>
<script>
$(function(){
$('#btnCapture').on('click', function(){
var file = document.getElementById("base64image").src;
var franid = $("#franid").val();
var sendInfo = {
Imagee: file,
FranIDD: franid
};
$.ajax({
type: "POST",
url: "/Application/Franchise",
data: JSON.stringify(sendInfo),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
$('#myModal3').modal('hide'); //hide the modal
},
error: function () {
alert("Error while inserting data");
}
});
});
});
</script>
}
This is all my code.
Ok. So I found my problem. It was in my controller.
In my controller I tried adding return RedirectToAction("Franchise", "Home"); after the save command. As soon as I commented this, everything worked.
Thanks for the help again guys.
Please use the browser to access directly, not from within the IDE directly access, from the localhost:49267 should be from the IDE access, and you will write URL as http://www.google.com try.

Admin ajax in wordpress is not working

I am using admin ajax but it is not working. Kindly, help me to find out the problem. Here is jquery code
jQuery(document).ready(function($) {
jQuery('#newPostsForm').submit(ajaxSubmit);
function ajaxSubmit(){
var newPostsForm = jQuery(this).serialize();
jQuery.ajax({
type:"POST",
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: newPostsForm,
success:function(data){
jQuery("#feedback").html(data);
}
});
return false;
}
}):
If I alert the var "newPostsForm" , it shown the posted values.but it is now proceeding to ajax. Here is the from I am using
<form type="post" action="" id="newPostsForm">
<input type="hidden" name="action" value="addPosts"/>
<!-- input fields -->
</form>
An here is the WordPress function I am using. this function is another file. HTML and javascript are in same file
function addPosts(){
echo "<pre>";
print_r($_POST);
die();
}
add_action('wp_ajax_addPosts', 'addPosts');
add_action('wp_ajax_nopriv_addPosts', 'addPosts'); // not really needed
Check to see if the script is getting processed by PHP before it is sent to the client. Change the code to something similar to this:
jQuery(document).ready(function($) {
jQuery('#newPostsForm').submit(ajaxSubmit);
function ajaxSubmit() {
var newPostsForm = jQuery(this).serialize();
var url = "<?php echo admin_url('admin-ajax.php'); ?>";
alert("Submitting to URL: " + url);
jQuery.ajax({
type:"POST",
url: url,
data: newPostsForm,
success:function(data){
jQuery("#feedback").html(data);
},
error: function (xhr, status, err) {
alert("Got status " + status + " and error: " + err);
}
});
return false;
}
});
If you get an actual URL like https://mysite.example.org then check that the URL goes to a valid location. If you get <?php echo admin_url('admin-ajax.php'); ?> then your code is not getting processed by PHP, and the AJAX call will fail because you are not using a valid URL.
The problem seems that the AJAX URL is not accessible in JS code. If the JS code written into a PHP page then only the code will work. Because the PHP code cant be executed into the JS files.
NOW the solution is to localized the JS file. Please follow the code.
wp_localize_script( 'handle', 'settings', array('ajaxurl' => admin_url( 'admin-ajax.php' )));
Write the above code just under where you have enqueued your js file.
NOW in JS file :
jQuery.ajax({
type:"POST",
**url: settings.ajaxurl,**
data: newPostsForm,
success:function(data){
jQuery("#feedback").html(data);
}
});
Hope it will work at your choice.

Codeigniter ajax pass variable class

My AJAX in view
<script type="text/javascript">
$(document).ready(function(){
$('.calendar .day').click(function(){
var day_data= $(this).find('.content').html();
if($(this).find('.content').html()!=null){
$.ajax({
url: "<?php echo base_url('calendar/pass_name')?>/",
method:"POST",
data:day_data,
success:function(data){
alert(data);
}
})
My controller
function pass_name(){
$name=$this->input->post('.calendar .day');
echo $name;
return $this->load->model('calendar_model')->get_description($name);
}
My model
function get_description($name){
$query=$this->db->select('description')->from('calendar')->where('name'==$name);
return $query;
}
What I would like to do is pass this variable through ajax, run a db query and return the result in a popup box.
Thanks in advance for any tips.
Try This code:
<script type="text/javascript">
$(document).ready(function(){
$('.calendar .day').click(function(){
var day_data= $(this).find('.content').html();
if($(this).find('.content').html()!=null){
$.ajax({
url: "<?php echo base_url('calendar/pass_name')?>/",
type:"POST",
data:{day_data:day_data},
success:function(data){
if(data==1)
{
$('#response').html(data);
}
}
})
</script>
Changer IN Your Controller
function pass_name()
{
$name=$this->input->post('day_data');
if($this->load->model('calendar_model')->get_description($name)==TRUE)
{
return 1;
}
}

Ajax response inside a div

I am trying to show the value of ajax response inside a div and for that I have the following code in my view file.
<script type="text/javascript" src="MY LINK TO JQUERY"></script>
<script type="text/javascript">
$(function(){ // added
$('a.vote').click(function(){
var a_href = $(this).attr('href');
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>contents/hello",
data: "id="+a_href,
success: function(server_response){
if(server_response == 'success'){
$("#result").html(server_response);
}
else{
alert('Not OKay');
}
}
}); //$.ajax ends here
return false
});//.click function ends here
}); // function ends here
</script>
<a href="1" title="vote" class="vote" >Up Vote</a>
<br>
<div class="result"></div>
my Controller (to which the ajax is sending the value):
function hello() {
$id=$this->input->post('id');
echo $id;
}
Now what I am trying achieve is get the server_response value (the value that is being sent from the controller) in side <div class="result"></div> in my view file.
I have tried the following code but its not showing the value inside the div.
Could you please tell me where the problem is?
The problem is that you have mixed arguments of Ajax success handler. First goes data which your script gives back, then goes textStatus. Theoretically it can be "timeout", "error", "notmodified", "success" or "parsererror". However, in success textStatus will always be successful. But if you need to add alert on error you can add error handler. And yes, change selector in $("#result") to class. So corrected code may look like this:
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>contents/hello",
data: "id=" + a_href,
success: function(data, textStatus) {
$(".result").html(data);
},
error: function() {
alert('Not OKay');
}
});​
success: function(server_response) {
$(".result").html(server_response);
}​
<div class="result"></div> // result is the class
The selector should be .result not #result
Try changing <div class="result"></div> to <div id="result"></div>, because that's what you're referencing in your ajax success function
$("#result").html(server_response);

Resources