Posting With AJAX not working, Can't get $_POST value - php

So I'm having a little issue. I am working on a site and this is the first I have used ajax to post to to a page. I have a form with a submit button and a link on it. When the submit button is pressed everything works but users should be able to click the link to by pass a page but I still need some information posted to that page so I googled ho to post with out a submit button and ajax came up so I figured I'd give it a shot. It seems to not be working. Here is the code that I am using.
$('#chkEndAccDate').click(function(evt){
alert("before ajax");
var totalcost = $('#total_cost').val();
$.ajax({
type: "POST",
url: "http://sandbox.phareconsulting.com/complete_order.php",
`enter code here`data: {cost : totalCost}
});
alert("after ajax");
});
This code also doesn't work when i try it
$(document).on('click','#chkEndAccDate',function(){
cost = $('#total_cost').val();
$.post("http://www.sandbox.phareconsulting.com/complete_order.php",
{cost: cost},function(d){
alert("post");
});
});
In the php file right now I am simply doing print_r($_POST); but the post array is empty. Can some one please help me out. I think that some of us just don't understand ajax correctly. I thought I did but I am not able to get it to work.
Thank you.

This should be proper syntax:
data: "{'cost':'" + cost+ "'}"

Use this
data:{cost: cost}
for sending the data.
Use this code:
$(document).on('click','#chkEndAccDate',function(){
cost = $('#total_cost').val();
$.post("http://sandbox.phareconsulting.com/complete_order.php",
{cost: cost},function(d){
});
});

s.d and Thiefmaster have already written the correct syntax, however, it may be a good idea to change the name of your variable so as to avoid confusion.
var totalCost = $('#total_cost').val();
Then use:
data: {cost : totalCost}

Its a good idea to use the jQuery Form Plugin to send ajax forms this will by itself grab the data and send it to the form action url.
This plugin also gives you functions that control the sending process . This is an example :
var bar = $('#progressBar');
var percent = $('#percent');
var status = $('#status');
$('#form-id').ajaxForm({
beforeSend: function() {
//validate the data
status.empty();
var percentVal = '0%';
bar.width(percentVal);
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
// draw a progress bar during ajax request
var percentVal = percentComplete + '%';
bar.width(percentVal);
percent.html(percentVal);
},
complete: function(xhr) {
bar.width("100%");
percent.html("100%");
}
});
Html for the progress bar :
<div id="progress">
<div id="bar"></div >
<div id="percent">0%</div >
</div>
css :
#progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
#bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px; }
#percent { position:absolute; display:inline-block; top:3px; left:48%; }

Related

Can't retrieve a specific portion of an HTML file (single.php) with AJAX in Wordpress

I have a small problem with a feature that I'm trying to implement on my site. I want when I click on an excerpt from a blog post on my homepage that the content of the article (single.php) opens in a modal window.
I use jQuery and Ajax to do that and it works really well except that Ajax fetches me the entire contents of single.php file (ie the header with scripts, styles, doctype, footer, etc.). I would just like to get the div (#PostContainer) that includes the title of the article and the content.
You will probably tell me to just delete my header and footer of the single.php file, but this is not possible because it is important to keep intact my file to be able to access from the address of the blog post (www.mydomainname.com/blog-post1).
It turns out that I am not at all familiar with WordPress :/ This is the first time I build a theme. The codes I shared with you run like a charm on WordPress but recovers me all of my single.php file (header + content in my div #postContainer + footer). I would like to recover only the contents of my div #postContainer.
I'm stuck :/
Someone would help me please ?
Thank you so so much for your time !
Here are my codes :
HTML :
<a class="hs-inner-click modal" data-content="<?php the_permalink(); ?>" rel="<?php the_ID(); ?>" href="<?php the_permalink(); ?>">
CSS :
.modal-window {
position: fixed;
left: 50%;
top: 50px;
width: 720px;
background-color: #fff;
transform: translate(-50%, 0);
z-index: 11;
}
.modal-shade {
position: fixed;
height: 100%;
width: 100%;
background-color: rgba(0, 0, 0, .7);
z-index: 10;
}
.modal-close {
position: absolute;
top: 10px;
right: 10px;
}
JQUERY & AJAX in a JS file :
(function($) {
$.fn.modal = function (opt) {
var settings, createModal, closeModal, body;
settings = $.extend({
'modal': 'jquery-modal',
'close': 'jquery-modal-close',
'closeText':'',
'shade': 'jquery-modal-shade'
}, opt);
body = $('body');
closeModal = function(modal, shade) {
modal.remove();
shade.remove();
};
createModal = function(data) {
var shade, close, modal;
shade =$('<div />', {
class: settings.shade
}).on('click', function() {
closeModal(modal, shade);
});
close =$('<a />', {
text: settings.closeText,
class: settings.close,
href: '#'
}).on('click', function(e) {
closeModal(modal, shade);
e.preventDefault();
});
modal =$('<div />', {
html: data,
class: settings.modal
}).append(close);
body.prepend(shade, modal);
};
this.on('click', function(e) {
var self =$(this);
$.ajax({
url:self.data('content'),
type: 'get',
cache: false,
}).done(function(data) {
createModal(data);
}).error(function() {
createModal('There is a mistake');
});
e.preventDefault();
});
};
})(jQuery);
I would suggest to use WordPress REST API V2 for the request without the need of selecting a div or loading single.php without header & footer.
This will allow you to load post content by just calling an endpoint similar to this: /wp-json/wp/v2/posts/<id>
Full API reference here.
Alternatively I am not sure if it will work but jquery code might help you (execute onload of modal): $("#jquery-modal").load("www.mydomainname.com/blog-post1 #postContainer");
ADDITIONALLY: On ajax success append content on a dummy div and use it to find only the part of the page you need and return it.
That's the way jquery load() actually works if you check the source.
jQuery( "<div>" ).append( jQuery.parseHTML(data) ).find("#postContainer");

Image Map Coordinates Hover with ajax not working

I'm having an image map with ajax hover to retrieve information from database table major_occurrence. But it's seems not working at all with the ajax call.
The hover is clickable so that it will redirect to another doRpMap.php showing the occurrence details.
Please advise on this matter. Thanks. *Pardon me being a programming newbie.
Am I doing the correct way for:
the variable to call back getOccCount.php $result in my Main Page?
how to insert the ajax call() into my <span>?
getOccCount.php
<?php
$location_id = $_GET['location_id'];
$query = "SELECT COUNT(occurrence_id) FROM major_occurrence WHERE '$location_id' = location_id GROUP BY location_id";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
$array = mysql_fetch_row($result); //fetch result
echo json_encode($array);
?>
Main page
<style type="text/css">
#map {
margin:0;
padding:0;
width:950px;
height:1211px;
background:url(images/Campus-Map.jpg);
background-size: 950px 1211px;
font-family:arial, helvetica, sans-serif;
font-size:8pt;
}
#map li {
margin:0;
padding:0;
list-style:none;
}
#map li a {
position:absolute;
display:block;
background:url(blank.gif);
text-decoration:none;
color:#000;
}
#map li a span { display:none; }
#map li a:hover span {
position:relative;
display:block;
width:200px;
left:20px;
top:20px;
border:1px solid #000;
background:#fff;
padding:5px;
filter:alpha(opacity=80);
opacity:0.8;
}
#map a.rpc{
top: 1060px ;
left: 585px;
width: 78px;
height: 65px;
}
</style>
<body>
<script>
$(document).ready(function() {
$('#map span').hover(function () {
var $t = $(this);
var location_id = $t.attr("location_id");
$.ajax({
url: 'getOccCount.php',
data: "{location_id: location_id}",
dataType: 'json',
method: 'GET',
success: function (result) {
$t.html('Total Number of Occurrence: ' + result[0]);
}
}
});
});
</script>
<ul id="map">
<li><a class="rpc" href="doRPMap.php?location_id=1"><span location_id="1"><b>RPC</b></span></a></li>
</ul>
</body>
A complete solution will require some work. Let me give you a few ideas. I apologize for having trouble with formatting ... the {} function here doesn't seem to work properly for me.
As you stated, you want to query the number of incidents for a given location. In your getOccCount.php I don't see any mechanism of passing a location id. It appears that the query always returns ALL occurrences. You probably want to add a line similar to
$location_id = #$_REQUEST['location_id'];
and use that value in a WHERE clause in your query.
The <span> you have in your html doesn't have a location_id attribute:
<span><b>RPC</b></span>
So the line where you try to retrieve that attribute will not find anything:
var location_id = $(this).attr("location_id");
You're doing the same ajax call twice, in two different ways. The whole block starting with $.ajax({ makes a call to getOccCount.php, however, I don't see you doing anything with the data passed to the success callback.
Then again in the success callback function you write $.get("getOccCount.php", ... which essentially does the same call again. This time you're trying to pass the location_id parameter, which we already know is not looked at in getOccCount.php.
Where you are trying to store the result back in the span that the user hovered over you use $('#map>span') as a selector which will store the result in ALL spans.
So, a start to your solution could look like this:
<body>
<script>
$(document).ready(function() {
$('#map span').hover(function () {
var $t = $(this);
var location_id = $t.attr("location_id");
$.ajax({
url: 'getOccCount.php',
data: "{location_id: location_id}",
dataType: 'json',
method: 'GET',
success: function (result) {
$t.html('Total Number of Occurrence: ' + result[0]);
}
});
});
});
</script>
<ul id="map">
<li><a class="rpc" href="doRPMap.php?locID=1"><span location_id="1"><b>RPC</b></span></a></li>
</ul>
</body>
Like I said, a full solution will require more work, especially on passing the location_id into your query. Hope that my ideas will help make progress.

how to fadeout multiple elements with javascript in onclick function

SOF users: today I have another challenge for you:
I have this piece of code, a part of jquery Uploader. Each file uploaded uses this code, where I create correct answer if file was uploaded ok or not.
When a file is uploaded ok, I put a delete button (cannot use form tag here). I want to add a fadeout effect.
EDIT: now all the interesting code.
<script>
var conexion;
var numarch = 0;
var idactual = 0;
function crearXMLHttpRequest(){
var xmlHttp=null;
if (window.ActiveXObject)
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
else
if (window.XMLHttpRequest)
xmlHttp = new XMLHttpRequest();
return xmlHttp;
}
function borrar_archivo(iddiv, ruta, header){
conexion=crearXMLHttpRequest();
idactual = iddiv;
conexion.onreadystatechange = procesarEventos;
conexion.open(header, ruta, true);
conexion.send(null);
}
function procesarEventos(){
var detalles = document.getElementById(idactual);
if(conexion.readyState == 4){
var resultado = conexion.responseText;
if(resultado.indexOf("true")!=-1){
nomArchivo = conexion.responseText.split(":",1);
nombreArchivo = nomArchivo[0].substring(1);
detalles.innerHTML = "<p style='float: left; clear:left; color: #66CC00; font-size:12px;'>"+nombreArchivo+" ha sido borrado.";
}
else{
detalles.innerHTML = "<p style='float: left; clear:left; font-size:12px;' class='text-danger'>Ha habido un error al borrar el archivo.</p>";
}
}
else{
detalles.innerHTML = "<p style='float: left; clear:left; font-size:12px;'>Cargando...</p>";
}
setInterval(function(){
$("#"+idactual).fadeOut(1000);
},1500);
}
$(function(){
$('#fileupload').fileupload({
dataType: 'json',
done: function (e, data){
$.each(data.result.files, function (index, file) {
numarch++;
$('<div id="archivo_'+numarch+'" />').appendTo('#files');
if (file.error){
$('<img style="width: 16px; float: left; clear:left; margin-right: 10px;" src="img/x.png" title="Error" alt="Error"/>').appendTo('#archivo_'+numarch);
$('<p style="float: left; font-size:12px;" class="text-danger"/>').text(file.error).appendTo('#archivo_'+numarch);
}
else{
var newFileDiv = $("<img style='width: 16px; float: left; clear:left; margin-right: 10px;' src='img/v.png' title='Archivo subido OK' alt='Archivo subido OK'/><p style='float: left; color: #66CC00; font-size:12px;'>"+file.name+"</p><div style='float :left; height: 5px;margin-left: 25px;' class='btn btn-danger delete' onclick=borrar_archivo('archivo_"+numarch+"','"+file.deleteUrl+"','"+file.deleteType+"')><i style='top: -5px;left: -5px;' class='glyphicon glyphicon-trash'></i><span style='top: -6px;position: relative;'>Borrar</span></div>");
$('#archivo_'+numarch).append(newFileDiv);
}
});
},
progressall: function (e, data){
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .progress-bar').html(progress + '%');
$('#progress .progress-bar').css('width',progress + '%');
}
});
});
</script>
I just founded that I can "delete" one item ok. but when I use multiple buttons to delete a lot of items, the function breaks, only deleting last elements I clicked...
I want to do this fadeout effect asynchronous.(that is the reason for the setInterval instead setTimeout)...
But nothing works for me. Now I am little lost about this.
Any help, please?
EDIT 2:
Now, trying I find how to delete 2 or more items, but the fadeout() effect only works on first one:
function borrar_archivo(iddiv, ruta, header){
conexion=crearXMLHttpRequest();
idactual = iddiv;
conexion.onreadystatechange = procesarEventos;
conexion.open(header, ruta, true);
conexion.send(null);
setInterval(function(){
$("#"+idactual).fadeOut(1000);
},1500);
setInterval(function(){
$("#"+idactual).remove();
},1000);
}
Any idea why this happend? and how to solve it?
So let's say you have a delete button:
$deletebutton.on('click', function (e) {
$(e.currentTarget).fadeOut();
});
Recommended: console.log(e) - you can find many other items in there you can access that may be helpful
But what if you dont want to remove the item you clicked on?
change .fadeOut to...
$itemtoremove.fadeOut();
Ok, until a lot of research, I founded the solution:
When you have a bunch of elements with a Delete button, all buttons calls to the same function: this is a problem when you work with timers, because when you are in "the waiting time" and you re-execute that timers, the inner action of the timer can be stopped(overwrited before has been sended).
The solution I found is this: put the wait time lesser than the fadeout time, not allowing the inner function to be stopped. Why this works? I don't know, but you can overclick the buttons and all the inner functions work.
I paste here my code. If you need more code to understand it, write it: idactual is the id name of the div to be faded out. numarc is the number used to identify each div: (e.g.: idactual = archivo_1 , numarch = 1)
setInterval(function(){
$("#"+idactual).fadeOut(1500, function(){
var i=0;
for(i=1;i>numarc;i++){
elemento=$(document).getElementById("archivo_"+i);
texto = elemento.innerHTML;
if(texto.indexOf("borrado")!=-1){
elemento.remove();
}
}
});
},100);

Element requiring 2 clicks until it shows

I am trying to make a quote form appear on click, the element is first prepended it then needs to run through ajax to get the content for the element
HTML
<input type="button" class="used_result_icon used_result_nav_enquire" car="'.$full_listing_name.'" />
CSS
#used_car_quote {background:#fff; border:2px solid #bebebe; border-radius:5px; display:none; font-size:20px; left:500px; min-height:350px; position:fixed; width:640px; z-index:100;}
AJAX
$(document).on("click", ".used_result_nav_enquire", function() {
car = $(this).attr('car');
$('#used_car_quote').show();
$('#used_results_sort').prepend('<div id="used_car_quote"></div>');
$.ajax({
type : 'POST',
url : 'http://localhost/carprice/ajax/used-quote-results.php',
data : 'car='+car,
success : function(data) {
$("#used_car_quote").html(data);
}
});
});
Its very strange, I click on the button once, and nothing happens, then I click again, and the form appears.
Use this code in AJAX Success $('#used_car_quote').show();
$(document).unbind("click").bind('click', ".used_result_nav_enquire", function() {
car = $(this).attr('car');
$('#used_results_sort').prepend('<div id="used_car_quote"></div>');
$.ajax({
type : 'POST',
url : 'http://localhost/carprice/ajax/used-quote-results.php',
data : 'car='+car,
success : function(data) {
$("#used_car_quote").html(data);
$("#used_car_quote").show();
}
});
});
I am trying to style it as well, but this is very strange, if I click on it once, then it is not positioned right, close it then click again, and it is
$(document).on("click", ".used_result_nav_enquire", function() {
win_width = $(window).width();
form_width = $('#used_car_quote').width();
left = (win_width-form_width)/2;
win_height = $(window).height();
form_height = $('#used_car_quote').height();
top = (win_height-form_height)/2;
car = $(this).attr('car');
$('#used_results_sort').prepend('<div id="used_car_quote">test</div>');
$('#used_car_quote').css({'left':left,'top':top});
$.ajax({
type : 'POST',
url : 'http://localhost/carprice/ajax/used-quote-results.php',
data : 'car='+car,
success : function(data) {
$("#used_car_quote").html(data);
$('#used_car_quote').show();
}
});
});

button click event not working after append data from php

I am loading html with javascript from php to a div using $.get() to a div. the button click event is working fine. then adding again same thing again to different div with different id, but it is not working. can anyone can help me. my code is this
<style>
.loadWindow {
width:333px;
height: 202px;
padding: 5px 5px 0 5px;
font: 12px Arial, Helvetica, sans-serif;
border:double;
}
#loadWindow {
display:none;
}
<div id="main-box">
<div class="loadWindow" id="loadWindow"></div><button id="make">make</button>
My javascript code is below
$(function(){
$('#make').click(function(){
var id = $('.loadWindow').length;
var aw = $('#loadWindow').clone().attr("id", "window"+id);
//load data from php
$.get("mydata.php", function(data) {
aw.html(data);
$('#main-box').append(aw);
aw.show();
}, 'json');
});
});
`
My mydata.php code is below
echo '<div><button id="closeBtn">Close</button></div><script>$("#closeBtn").click(function(){alert("Close button Clicked!");});</script>';
I want click event work for each window separately(individually) and display the alert. In this code click event is not working according to the window. What can I do?
Working demo http://jsfiddle.net/QYEWs/13/
Please use .on API to it attaches an event handler function for one or more events to the selected elements.
API: http://api.jquery.com/on/
Plz Note: your append will make the DOM invalid as your id will always be same make it a class
to attach click event on dynamically added html in DOM
This should help, :)
like this
Attaché click event to close button like this:
$("#main-box").on("click",".closeBtn", function() {
alert("Close button Clicked!");
});​
$(function(){
$('#make').on('click', function(){
var id = $('.loadWindow').length;
var aw = $('#loadWindow').clone().attr("id", "window"+id);
//load data from php
$.get("mydata.php", function(data) {
aw.html(data);
$('#main-box').append(aw);
aw.show();
}, 'json');
});
});
$(function(){
$('#make').click(function(){
var id = $('.loadWindow').length;
var aw = $('#loadWindow').clone(true).attr("id", "window"+id);
//load data from php
$.get("mydata.php", function(data) {
aw.html(data);
$('#main-box').append(aw);
aw.show();
}, 'json');
});
});

Categories