Wordpress: POST to .php with Ajax - javascript

I'm having a lot of trouble with getting this code working:
<script type = "text/javascript">
jQuery(document).ready(function($){
$('#submitbutton').click(function(){
var email=document.getElementById('emailadd').value;
var password=document.getElementById('pass').value;
$.ajax({
type: "POST",
url: "/wp-content/themes/roots-master/login.php",
data: {emailaddress:'email', password:'password'},
dataType: "text",
success:function(response){
alert("success");
}
});
});
});
</script>
When I comment out the $.ajax function, the javascript works fine(I tested it with an alert). However, the $.ajax part doesn't seem to be working. Does anybody have any suggestions?
When I change the code to the following, the javascript appears to not work as well:
$('#submitbutton').click(function(){
var email=document.getElementById('emailadd').value;
var password=document.getElementById('pass').value;
$.ajax({
alert(password);
});
});
I am using wordpress so I didn't put any links to jquery in the head. Instead, I put the following into my functions.php and then jquery started working.
wp_deregister_script('jquery');
wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery /1/jquery.min.js', false, '1.9.1', false);
wp_enqueue_script('jquery');
UPDATE: For some reason, when I put an alert after the $.ajax, it works!
jQuery(document).ready(function($){
$('#submitbutton').click(function(){
var email=document.getElementById('emailadd').value;
var password=document.getElementById('pass').value;
$.ajax({
dataType: "html",
type: "POST",
evalScripts: true,
url: "/wp-content/themes/roots-master/login.php",
data: {emailaddress:'email', password:'password'},
dataType: "text",
success:function(){
alert("success");
}
});
alert("testing");
});
});
Does anyone know why this would be?

Solved it!! It should have looked like this:
$('#submitbutton').click(function(j){
j.preventDefault();
I was missing the preventDefault()...doh!

Related

How can I do a conditional statement so ajax fetchs the correct xml document

I have a simple code to fetch a xml file and display it as a drop down list. However, I would like to fetch the xml file according to a condition. If it equals to study1 then .ajax selects ctc3.xml, else it selects ctc5.xml.
My code was working fine if I was fetching a specific xml file, but the conditional does not work.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script lang="Javascript"> $.noConflict();
jQuery(document).ready(function($) {
var myField = $("#myList") var myOutputField = $("#myOutput").parent().parent().find("input");
myOutputField.attr("readonly",true);
var studyID="${studyName}";
if (studyID!="Test"){
$.ajax({
type: "GET",
url: "includes/ctcae3.xml",
dataType: "xml",
success: parseXML
});
}
else {
$.ajax({
type: "GET",
url: "includes/ctcae5.xml",
dataType: "xml",
success: parseXML
});
}
function parseXML(xml){
$(xml).find("atccode").each(function(){
myField.append($("<option />").val($(this).attr("code")).text($(this).find("description").text()));
});
myField.val(myOutputField.val());
}
myField.change(function(){
myOutputField.val(myField.val());
myOutputField.change();
});
});
</script><select id="myList"> <option val="None"/>None </select> `
problem resolved. Clearly my brain was already fried. It was just a matter of adding the ';' to var myField = $("#myList");

Why is my jquery/ajax post not registering in my php code?

So I am trying to build a single page application using PHP and AJAX but I am having some issues with my navigation.
I have a file controller.php that controls the page to be displayed. The code that handles a post request is as follows
EDIT: Forgot to mention that echoing $_POST['page'] shows nothing
if(!isset($_POST['page'])){
include('Pages/landing_page.php');
echo "empty";
}
else{
echo $_POST['page'];
if($_POST['page'] == 'landing_page'){
include('Pages/landing_page.php');
}
if($_POST['page'] == 'forum'){
include('Pages/forum.php');
echo "forum hit";
}
}
The post request is generated with $.ajax function as follows
$(document).ready(function(){
$("#home_link").on('click', ()=>{
alert("Working");
$.ajax({
type: "POST",
url: "controller.php",
data: "page=landing_page"
});
});
$('#forum_link').on('click', ()=>{
$.ajax({
type: "POST",
url: "controller.php",
data: "page=forum",
success: function(){
alert("Callback Works");
}
});
});
});
I know the jquery click is working because I get the original "Working" alert as well as the callback alert if I click on the forum link.
I am using the Netbeans built in PHP development server but I have also tested it on a proper apache2 server that is well configured for PHP and AJAX.
Any help would be appreciated, thanks!
As I understand the question, this should work:
PHP: (all the same)
if(!isset($_POST['page'])){
include('Pages/landing_page.php');
echo "empty";
}
else{
echo $_POST['page'];
if($_POST['page'] == 'landing_page'){
include('Pages/landing_page.php');
}
if($_POST['page'] == 'forum'){
include('Pages/forum.php');
echo "forum hit";
}
}
JS:
$(document).ready(function(){
$("#home_link").on('click', ()=>{
alert("Working");
$.ajax({
type: "POST",
url: "controller.php",
data: "page=landing_page"
});
});
$('#forum_link').on('click', ()=>{
$.ajax({
type: "POST",
url: "controller.php",
data: "page=forum",
success: function(data){
$("#container").html(data);
alert("Callback Works");
}
});
});
});
You need to take the data returned from the function and put it somewhere, presumably into a container element.
If this isn't what you are trying to do, please comment.

How to resolve jQuery conflict?

I have a jQuery custom file which is disabling or conflicting my other jQuery file, please how do i resolve this. Please see below:
My Custom file:
$(".search").keyup(function()
{
var searchid = $(this).val();
var dataString = 'search='+ searchid;
if(searchid!='')
{
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
cache: false,
success: function(html)
{
$("#result").html(html).show();
}
});
}return false;
});
Conflicting Files:
<script src="js/jquery.isotope.min.js"></script>
<script src="js/nprogress.js"></script>
I would be more than happy if this is resolved.
I'm assuming that you know for certain jQuery is conflicting - you've checked the console errors, etc.
You could wrap your jQuery in a self-executing anonymous function as follows:
(function($) {
$(".search").keyup(function()
{
var searchid = $(this).val();
var dataString = 'search='+ searchid;
if(searchid!='')
{
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
cache: false,
success: function(html)
{
$("#result").html(html).show();
}
});
}return false;
});
})(jQuery);
EDIT - a bit of explanation of what's happened above. In order to prevent any potential conflicts with other scripts / frameworks we are passing the jQuery object as an argument to our function (hence function($)). The benefits of doing this is that you can now use $ locally within the function at will. Without fear of conflicting with other scripts on a global scope.
I Was able to fix the problem by just wrapping it with:
$(document).ready(function() {
//-----
});

How to alert ajax response

I've read dozens of related posts, but I still can't get this to work.
I want to alert the response in jquery I get from PHP.
PHP:
$msg=array();
if(empty($whatever)){
$msg['cenas']="Não há contas";
}else{
$msg['cenas']="Há contas";
};
echo json_encode($msg);
JS:
$.ajax({
url: 'myscript.php',
dataType: 'json',
success: function(response){
alert(response.cenas);
}
});
PHP is echoing
{cenas: "Há contas}"
But I can't get it to alert in JS.
The php should echo back {"cenas": "Há contas"}, but what did you get in the alert? Did you get an undefined? If so, try to use jQuery.parseJSON before alert. e.g:
$.ajax({
url:"myscript.php",
dataType: "json",
success:function(data){
var obj = jQuery.parseJSON(data);
alert(obj.cenas);
}
});
You should tell jQuery to expect (and parse) JSON in the response (although jQuery could guess this correctly...) and you should write your javascript correctly:
$.ajax({
url: 'myscript.php',
dataType: 'json',
success: function(response){
alert(response.cenas);
}
});
Try
$.ajax({
url:"myscript.php",
dataType: "json",
success:function(data){
alert(data.cenas);
}
});
You have a syntax error.
Check out the Docs for $.ajax

$.ajax interfering with .hide() and .show() Jquery in this script

(In Firefox and IE9 it doesn't work. In Chrome, this works)
If I remove the ajax, the hide / show JQuery works. Any solutions?
<form id="ppform" action="blah.asp" method="post">
<div id="saleload">Blah</div>
<button id="sendbutton">Send</button>
</form>
$(document).ready(function(){
$('#saleload').hide();
$('#sendbutton').click(function() {
$('#saleload').show();
$.ajax({
type: "POST",
url: /blah/blah.asp,
data: reqBody,
dataType: "json",
success:function(data,textStatus){
if (data.redirect) {
window.location.href = data.redirect;
}else{
$("#ppform").replaceWith(data.form);
}
}
});
});
});
This line:
$("#ppform").replaceWith(data.form);
is replacing the whole form contents with the response from your Ajax request. This means the click handler you setup will be gone too, because #sendbutton will be gone. Even if you have another button with the same ID inside data.form, it won't work. You have to use event delegation instead:
$(document).ready(function(){
$('#saleload').hide();
$(document).on('click', '#sendbutton', function(){
$('#saleload').show();
$.ajax({
type: "POST",
url: "/blah/blah.asp",
data: reqBody,
dataType: "json",
success:function(data,textStatus){
if (data.redirect) {
window.location.href = data.redirect;
} else {
$("#ppform").replaceWith(data.form);
}
}
});
});
});
Also: you seem to be posting an undefined variable reqBody to your server, and, as lonesomeday said above, you were missing quotes around the URL.
The obvious reason is that there is an error with your Javascript that causes the whole section not to execute. Quickly looking through your code shows this line:
url: /blah/blah.asp,
Strings need to be enclosed in quotation marks:
url: "/blah/blah.asp",

Categories

Resources