ajax with Jquery can't make working in wordpress - php

I am writing a plugin for a wordpress, where I use jquery for AJAX.
Following code doesn't work. I expect to show the content in results div when I type in input box.
Here is the code I use for ajax request. It is located on my theme header file.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript" >
$(document).ready(function(){
//alert("sjsjs");
$("#se").keypress(function(e){
// e.preventDefault();
var search_val=$("#se").val();
$.ajax({
type:"POST",
url: "./wp-admin/admin-ajax.php",
data: {
action:'wpay_search',
search_string:search_val
},
success:function(data){
$('#results').append(response);
}
});
});
});
</script>
html content in template file
<form name="nn" action="" method="post"></br></br>
<input id ="se" type="text" name="test" width="20" />
<input type="submit" id="clicksubmit" value="Submit" />
</form>
<div id="results">val is:
</div>
Here is the code in plugin file
function wpay_search() {
//global $wpdb; // this is how you get access to the database
$whatever = $_POST['search_val'];
$whatever += 10;
echo $whatever;
die(); // this is required to return a proper result
}
add_action('wp_ajax_wpay_search', 'wpay_search');
add_action('wp_ajax_nopriv_wpay_search', 'wpay_search');
I am new to wordpress plugin writing. Can anybody tell that where I have done the mistake?

Well one thing that obviously jumps out to me is this...
success:function(data){
$('#results').append(response);
}
Should be...
success:function(data){
$('#results').append(data);
}
Because you have no variable called response, you passed the function data as a variable, so you have to use that.
Also, you're passing search_string as a paremeter, when infact in your php file, the $_POST is looking for search_val.
So you need to send search_val as parameter and give your JavaScript search_val variable another variable name in the JavaScript, just for less confusion. In this case I made it search.
action:'wpay_search',
search_val:search
So overall it should look something like this...
$("#se").keypress(function(e){
e.preventDefault();
var search=$("#se").val();
$.ajax({
type:"POST",
url: "./wp-admin/admin-ajax.php",
data: {
action:'wpay_search',
search_val:search
},
success:function(data){
$('#results').append(data);
}
});
});

Related

value is not coming $POST array in php

I am building a simple sign up form using ajax when I creating a data object and pass to PHP file.It shows variables and doesn't show values of that PHP variable.
The code of HTML of form is
<form id="myForm" name="myForm" action="" method="POST" class="register">
<p>
<label>Name *</label>
<input name="name" type="text" class="long"/>
</p>
<p>
<label>Institute Name *</label>
<input name="iname" type="text" maxlength="10"/>
</p>
<div>
<button id="button" class="button" name="register">Register »</button>
</div>
</form>
The code of js is
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var form=$("#myForm").serialize();
$("#button").click(function(){
$.ajax({
type:"POST",
url: "mainlogic.php",
data:form,
success: function(result){
alert(result);
}
});
});
})
</script>
The code of PHP is
(mainlogic.php)
if(isset($_POST)) {
print_r($_POST);//////varaibles having null values if it is set
$name=trim($_POST['name']);
echo $name;
}
You are serializing your form on document load. At this stage, the form isn't filled yet. You should serialize your form inside your button click event handler instead.
$(document).ready(function(){
$("#button").click(function(){
var form=$("#myForm").serialize();
$.ajax({
type:"POST",
url: "mainlogic.php",
data:form,
success: function(result){
alert(result);
}
});
});
})
In this code you serialize blank form, just after document is ready:
<script>
$(document).ready(function(){
var form=$("#myForm").serialize();
$("#button").click(function(){
$.ajax({
type:"POST",
url: "mainlogic.php",
data:form,
success: function(result){
alert(result);
}
});
});
})
</script>
Valid click function should begins like:
$("#button").click(function(){
var form=$("#myForm").serialize();
$.ajax({...
It means - serialize form right after button clicked.
var form = $("#myForm").serialize();
That is the line that collects the data from the form.
You have it immediately after $(document).ready(function() { so you will collect the data as soon as the DOM is ready. This won't work because it is before the user has had a chance to fill in the form.
You need to collect the data from the form when the button is clicked. Move that line inside the click event handler function.
The problem is that you calculate the form values at the beginning when loading the page when they have no value yet. You have to move the variable form calculation inside the button binding.
<script>
$(document).ready(function(){
$("#button").click(function(){
var form=$("#myForm").serialize();
$.ajax({
type:"POST",
url: "mainlogic.php",
data:form,
success: function(result){
alert(result);
}
});
});
})
</script>
Alpadev got the right answer, but here are a few leads that can help you in the future:
ajax
You should add the below error coding in your Ajax call, to display information if the request got a problem:
$.ajax({
[…]
error: function(jqXHR, textStatus, errorThrown){
// Error handling
console.log(form); // where “form” is your variable
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
$_POST
$_POST refers to all the variables that are passed by the page to the server.
You need to use a variable name to access it in your php.
See there for details about $_POST:
http://php.net/manual/en/reserved.variables.post.php
print_r($_POST); should output the array of all the posted variables on your page.
Make sure that:
⋅ The Ajax request ended correctly,
⋅ The print_r instruction is not conditioned by something else that evaluates to false,
⋅ The array is displayed in the page, not hidden by other elements. (You could take a look at the html source code instead of the output page to be sure about it.)

How to pass data from a PHP file back to the original without page refresh?

I am trying to have the output from a PHP file display in the original page containing the form, without having to refresh the page.
I am currently using AJAX to do so but I am not able to pass the value of the submitted PHP file back to the index.php page - this needs to be done without having the page refreshed.
Overall
User enters some data and submits the form
That data is passed to a PHP file through AJAX
Some pieces of data, which were manipulated through the PHP file, are then echoed out onto the original index.html file without the page refreshing
Below you will find the code that I am currently using to try and achieve this.
index.php
<form>
<input type="text" name="hi">
<input type="submit">
</form>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
});
});
});
</script>
post.php
<?php
echo "Hello";
$name = $_POST['hi'];
echo $name . "This is a test";
?>
I would appreciate any help, thanks!
How about this simple solution. Just copy and paste this code into a file called index.php and whatever text you enter in the input field will be outputted by PHP. Hope it helps!.
<?php
$data = array();
if(isset($_POST['userText']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH'])){
$data = 'The data you entered is: ' . $_POST['userText'];
echo json_encode($data);
die();
}
?>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<form>
<input type="text" name="hi" id = "someID">
<input type="submit" id = "sendInfo">
</form>
<div id = "random"></div>
<script type = "text/javascript">
$("#sendInfo").click(function(){
var someText = document.getElementById("someID").value;
var userText = JSON.stringify(someText);
$.ajax({
url: "index.php",
method: "POST",
dataType: "json",
data: {userText: userText},
success: function (result) {
console.log(result);
$("#random").html(result);
}
});
return false;
});
</script>
</body>
</html>
Add 'success' to your object and pass in a parameter to the function. That will hold the results from the php file.
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
success: function(results) {
console.log(results);
}
});
What this does is, on a successful ajax call, stores all of the content sent from the post.php file into the results variable.' In this case it will be whatever $name is and 'This is a test.'

Cant .ajax() submit a php form that has been loaded onto main page with jQuery .load()

I'm having the following problem. Below is an explanation of what my PHP pages are and how they work. When I access form.php directly and try to submit it via AJAX, it works perfectly.
Problem - When I .load() form.php into main.php, none of the jQuery code within form.php fires. (verified through firebug) No submits, no alerts, nothing. How can I get the jQuery code within form.php to work when its loaded into main.php?
main.php -> This is the main PHP page which has a link on it. Once this link is clicked, the following jQuery code fires to load "form.php" within a div called #formcontainer. This is the code within main.php that loads form.php.
Foobar
<div class="formcontainer"></div>
<script type="text/javascript">
$(document).ready(function(){
$("#addHomeProfile").click(function(){
$(".formcontaineropen").load("form.php");
});
});
</script>
form.php -> this is a form that gets loaded above. It submits data to MySQL through an jQuery .ajax() POST. Here is the jquery code which submits the form, which has an ID called #homeprofile.
<form id="homeprofile"> <input type="text" name="name" id="name" />
<input type="submit" value="submit" id="submit"></form>
<script type = "text/javascript">
$(document).ready(function() {
$('#homeprofile').submit(function(e){
e.preventDefault();
alert("form submitted");
$.ajax({ // Starter Ajax Call
type: "POST",
url: 'update.php',
data: $('#homeprofile').serialize(),
});
});
});
Use on() for this like,
$(document).on('submit','#homeprofile',function(e){
e.preventDefault();
alert("form submitted");
$.ajax({ // Starter Ajax Call
type: "POST",
url: 'update.php',
data: $('#homeprofile').serialize(),
});
return false;
});
You should be using the .on() syntax for targeting dynamically created elements (elements loaded into the DOM by JS or jQuery after the initial rendering)
Good
// in english this syntax says "Within the document, listen for an element with id=homeprofile to get submitted"
$(document).on('submit','#homeprofile',function(e){
//stop the form from submitting
e.preventDefault();
// put whatever code you need here
});
Not as good
// in english this syntax says "RIGHT NOW attach a submit listener to the element with id=homeprofile
// if id=homeprofile does not exist when this is executed then the event listener is never attached
$('#homeprofile').on('submit',function(e){
//stop the form from submitting
e.preventDefault();
// put whatever code you need here
});
Hopefully this helps!
Small issue is that you reference formcontaineropen in the jquery call (this is probably a typo?). The cause is that that a JS code loaded via AJAX will get interpreted (therefore eval() is not needed) but the document ready event will get triggered immediately (which may be before the AJAX loaded content is actually inserted and ready in the document - therefore the submit event may not bind correctly). Instead you need to bind your code to success of the AJAX request, something like this:
main.php:
<html>
Foobar
<div class="formcontainer"></div>
<script src='jquery.js'></script>
<script type="text/javascript">
$(document).ready(function(){
$("#addHomeProfile").click(function(){
$(".formcontainer").load("form.php", '',
function(responseText, textStatus, XMLHttpRequest) {
onLoaded();
});
});
});
</script>
form.php:
<form id="homeprofile"> <input type="text" name="name" id="name" />
<input type="submit" value="submit" id="submit"></form>
<script type="text/javascript">
function onLoaded() {
$('#homeprofile').submit(function(e){
e.preventDefault();
alert("form submitted");
$.ajax({ // Starter Ajax Call
type: "POST",
url: 'update.php',
data: $('#homeprofile').serialize(),
});
});
};
</script>
My solution is somewhat peculiar but anyhow here it is.
This would be your main.php:
Foobar
<div class="formcontainer"></div>
<script type="text/javascript">
$(document).ready(function(){
$("#addHomeProfile").click(function(){
$(".formcontaineropen").load("form.php", '', function(response){
var res = $(response);
eval($('script', res).html());
});
});
});
</script>
And this is your form.php:
<form id="homeprofile"> <input type="text" name="name" id="name" />
<input type="submit" value="submit" id="submit"></form>
<script type = "text/javascript">
$('#homeprofile').submit(function(e){
e.preventDefault();
alert("form submitted");
$.ajax({ // Starter Ajax Call
type: "POST",
url: 'update.php',
data: $('#homeprofile').serialize(),
});
});
</script>

Insert record using jQuery after ajax call doesn't work

I have an insert and load record (jQuery & PHP) script working fine without using AJAX. but after the AJAX call, insert (jQuery) doesn't work.
This is my code:-
$(".insert").live("click",function() {
var boxval = $("#content").val();
var dataString = 'content='+ boxval;
if(boxval==''){
alert("Please Enter Some Text");
}
else{
$.ajax({
type: "POST",
url: "demo.php",
data: dataString,
cache: false,
success: function(html){
$("table#update tbody").prepend(html);
$("table#update tbody tr").slideDown("slow");
document.getElementById('content').value='';
}
});
}
return false;
});
$(".load").live("click",function() {
$.ajax({
type: "POST",
url: "test.php",
success: function(msg){
$("#container").ajaxComplete(function(event, request, settings){
$("#container").html(msg);
});
}
});
});
});
Definitely recommend using your browsers dev tools to examine the exact request that is submitted and see if there is a problem there first.
You might also want to change the way you pass the dataString to the ajax request.
If your boxval has a "&" in it then you'll end up with an incorrectly formatted string. So, try initialising data instead as:
var data = {};
data.content = boxval;
This will ask jQuery to escape the values for you.
I'd be curious to see your form markup and your back-end PHP code; it may provide a clue.
Often I'll have a form variable called 'action', just to tell the PHP code what I want it to do (especially if that PHP script is a controller for many different actions on an object). Something like <input type="hidden" name="action" value="insert"/> or even multiple <input type="submit" name="action"/> buttons, each with a different value. In the PHP code I'll have something like:
switch ($_POST['action']) {
case 'insert':
// insert record and send HTML
break;
// other actions
}
If you've done something like this, perhaps the PHP is looking for the presence of a variable that doesn't exist.
Without being able to look at your code, I'd highly recommend the incredibly handy jQuery Form Plugin http://jquery.malsup.com/form/ . It allows you to turn a form into an AJAX form, formats your data properly, and doesn't forget the data from any of your form elements (except <input type="submit"/> buttons that weren't clicked on, which is the same behaviour that a non-AJAX form exhibits). It works just like the standard $.ajax() method.
I solved the problem
I replaced this code
$("#container").ajaxComplete(function(event, request, settings){
$("#container").html(msg);
});
with
$("#container").html(msg);
Thank you very much for your answers
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.clicker').click(function(){
var fname = $('.fname').val();
var lname = $('.lname').val();
var message=$('.message').val();
$.ajax({
type:"POST",
url: "submit.php",
cache:false,
data: "fname="+fname+"&lname="+lname+"&message="+message,
success: function(data){
$(".result").empty();
$(".result").html(data);
}
});
return(false);
});
});
</script>
</head>
<body>
<div>Data Form</div>
<form id="form1" name="form1" method="post" action="">
<input name="fname" type="text" class="fname" size="20"/><br />
<input name="lname" type="text" class="lname" size="20"/><br />
<div class="result"><textarea name="message" rows="10" cols="50" class="message"> </textarea></div>
<input type="button" value="calculate" class="clicker" />
</form>
</body>
</html>
submit.php
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("ajaxdb",$con);
$fname=$_REQUEST['fname'];
$lname=$_REQUEST['lname'];
$message=$_REQUEST['message'];
$sql="insert into person(fname,lname,message) values('$fname','$lname','$message')";
mysql_query($sql) or die(mysql_error());
echo "The data has been submitted successfully.";
?>

Pass a JS variable to a PHP variable

I have a JavaScript value given by Google maps and I need to save it in a MySQL database.
Actually I have the variable
<script>
...
var lugar = results[0].geometry.location;// this gives me a latitud, longitud value, like: -34.397, 150.644
...
</script>
And I need to pass that variable to the PHP variable lugar
<?
$lugar= ?????
?>
You can use jQuery ajax for this, but you need to create another script that save on your database:
<script>
$.ajax({
url: "save.in.my.database.php",
type: "post",
dataType:"json",
data: {
lugar: results[0].geometry.location
},
success: function(data){
alert('saved');
},
error: function(){
alert('error');
}
});
</script>
"save.in.my.database.php" receives a $_POST['lugar'] and you can save on your database.
You will need to pass it via a form submission, cookie, or through a querystring.
You can POST through a form or pass it in the URL if you're doing it on page transition, then just use $_POST or $_GET to receive the variable.
If you need it done seamlessly then you might want to look at using AJAX.
TIZAG AJAX Tutorial
This will convert js variable to php variable
<script>
function sud(){
javavar=document.getElementById("text").value;
document.getElementById("rslt").innerHTML="<?php
$phpvar='"+javavar+"';
echo $phpvar.$phpvar;?>";
}
function sud2(){
document.getElementById("rslt2").innerHTML="<?php
echo $phpvar;?>";
}
</script>
<body>
<div id="rslt">
</div>
<div id="rslt2">
</div>
<input type="text" id="text" />
<button onClick="sud()" >Convert</button>
<button onClick="sud2()">Once Again</button>
</body>
Demo: http://ibence.com/new.php

Categories