I have searched the internet a lot for an answer to my question and have not found exactly what I was looking for. So the standard way, from what I have seen, to accomplish this is to use jQuery's submit and AJAX to send the data and redirect to another PHP page. However, I have multiple problems with this. First of all, AJAX. Regular AJAX does not work on Wordpress sites, from what I have seen. How do I get plain old regular AJAX to work? I have not seen a single good tutorial for this that is in plain English for Dummies. Second of all, the PHP redirect. I just want it to send to PHP already on the page. I just want data to go from my Javascript into my PHP already on the page. I don't need a redirect. So, my final question is, can those two problems be fixed in order to do it the traditional way? Or is there a better way to do it that circumvents these problems? I am a complete beginner, BTW- been doing web programming for less than five months. So please, for Dummies or Complete Idiot's language if you can. Here's the form I am submitting from:
<form method="post">
Search By File Name: <input type="text" name="searchterms" placeholder="search"></input>
<button type="submit" name="SearchSubmit">Display Results</button>
</form>
Here's the PHP I want to execute:
$submit=$_POST['SearchSubmit'];
$results=$_POST['searchterms'];
if(isset($submit))
{
//whole bunch of stuff, like sql queries and file generation
}
There are 3 part of code,
HTML where data want to show.
<div id="msg_alert"></div>
Jquery for ajax;
$('#msg_form').submit(function (event) {
event.preventDefault();
action = 'messaging_post';
user_id = $('#msg_form #user_id').val();
$.ajax({
type: 'POST',
dataType: 'json',
url: ajax_auth_object.ajaxurl,
data: {
'action': action,
'user_id': user_id
},
success: function (data) { //alert(data.message);
if (data.log== true) {
$('#msg_alert').val(data.message);
}
else {
$('#msg_alert').val('There is an error');
}
}
});
});
Third is PHP:
add_action('init', 'ajax_review_loading');
function ajax_review_loading() {
wp_localize_script( 'ajax-auth-script', 'ajax_auth_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'redirecturl' => home_url(),
'loadingmessage' => __('Sending user info, please wait...')
));
add_action( 'wp_ajax_messaging_post', 'messaging_post' );
}
function messaging_post(){
/// Your work here.
echo json_encode(array('log'=>true, 'message'=> $htm));
die();
}
For working you must add wp_enqueue_script to ajax_review_loading function
add_action('init', 'ajax_review_loading');
function ajax_review_loading() {
wp_enqueue_script('ajax-auth-script', get_template_directory_uri() );
wp_localize_script( 'ajax-auth-script', 'ajax_auth_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'redirecturl' => home_url(),
'loadingmessage' => __('Sending user info, please wait...')
));
add_action( 'wp_ajax_messaging_post', 'messaging_post' );
}
function messaging_post(){
/// Your work here.
echo json_encode(array('log'=>true, 'message'=> $htm));
die();
}
You might need 2 php files, the one that generates the page that you are already seeing, let's call it "my_page.php", and the one that generates the data that you load in that first page without refreshing it, let's call it "livedata.php".
So for example if "my_page.php" generates the following html:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
function refresh_data(start_at) {
$("#data_updates_go_here").empty(); // Clear previous contents of the div for refresh
$.getJSON("livedata.php?start_at=" + start_at,
function(json_returned) {
$.each(json_returned, function(key, value){
$("#data_updates_go_here").append(key + " = " + value + "<br />");
});
});
}
</script>
Data: <br/>
<div id="data_updates_go_here">
</div>
<input type=button onClick="refresh_data(1);" value="Refresh data at 1">
<input type=button onClick="refresh_data(3);" value="Refresh data at 3">
You can see that when you load "my_page.php", it won't display any data. inside of the div.
Now "livedata.php" on it's side will have to generate a json structure, as you can see above, it can receive parameters, so you can use them for instance, to limit a query to a database or for any other purposes that you need a parameter to be passed to your php. In the example, "livedata.php" should return a 'json' structure. For instance, your php code could be
<?php
header('Content-Type: application/json');
if ($_REQUEST['start_at'] == 1) {
echo json_encode(array('value1' => 'data1', 'value2' => 'data2'));
} else if ($_REQUEST['start_at'] == 3) {
echo json_encode(array('value3' => 'data3', 'value4' => 'data4'));
} else {
echo json_encode(array('value1' => 'data1', 'value2' => 'data2'));
}
?>
You can see how you can control the values refreshed by passing a different value for "start_at".
Related
I'm new to stackoverflow (as a member at least) and I have a question.
I'm also new to PHP by the way.
Thing is:
I want to dynamically fill a second dropdown list with entries based on a first dropdown list (I want to show cities based on a selected province).
I managed to get the selected province to an external PHP file with an AJAX call in Javascript.
But when I include the external PHP file in my original PHP file, the variable of the external file is undefined.
The AJAX call is fired with an onchange event on the first dropdown menu.
And maybe you can also help with how I use that variable to get the right content in the second dropdown. I've used a multidimensional Array for that.
HTML:
echo('<select name="provincie" id="provincie" onchange="ProvinciePHP()">');
foreach ($provincie as $provincies){
echo ("<option> $provincies </option>");
}
echo ('</select>');
echo('<select name="stad" id="stad"> </select>')
PHP ARRAY:
$provincie = array(
'Selecteer een provincie',
'Drenthe',
'Flevoland',
'Friesland',
'Gelderland',
'Groningen',
'Limburg',
'Noord-Brabant',
'Noord-Holland',
'Overijssel',
'Utrecht',
'Zeeland',
'Zuid-Holland',
);
$stad = array(
'Drenthe' => array("Assen", "Emmen", "Hoogeveen", "Meppel"),
'Flevoland' => array("Almere", "Biddinghuizen", "Dronten", "Lelystad"),
'Friesland' => array("Heerenveen", "Joure", "Leeuwarden", "Sneek"),
'Gelderland' => array("Apeldoorn", "Arnhem", "Nijmegen", "Zutphen"),
'Groningen' => array("Delfzijl", "Groningen", "Stadskanaal", "Veendam"),
'Limburg' => array("Maastricht", "Roermond", "Sittard", "Venlo"),
'Noord-Brabant' => array("Breda", "Den Bosch", "Eindhoven", "Tilburg"),
'Noord-Holland' => array("Alkmaar", "Amsterdam", "Haarlem", "Hilversum"),
'Overijssel' => array("Deventer", "Enschede", "Hengelo", "Zwolle"),
'Utrecht' => array("Amersfoort", "Breukelen", "Utrecht", "Zeist" ),
'Zeeland' => array("Goes", "Middelburg", "Terneuzen", "Vlissingen"),
'Zuid-Holland' => array("Alphen a/d Rijn", "Den-Haag", "Rotterdam", "Schiedam"),
);
function getProvincie(){
var provincie = $('#provincie option:selected').val();
$.ajax({
type: "POST",
url: "getprovincie.php",
data: {data: provincie},
success: function(data) {
alert(data);
$('#stad').css('display','inline');
},
error: function(data) {
}
});
}
//PHP page to where the AJAX call points:
<?php
$resultaat = $_POST['data'];
echo($resultaat);
I'm trying to post data on my HTML code to CI with Ajax. But I got no response?
Here is my JS Code
$(document).ready(function(){
$("#simpan").click(function(){
nama_pelanggan = $("#nama_pelanggan").val();
telp = $("#telp").val();
jQuery.ajax({
type: "POST",
url: "http://192.168.100.100/booking_dev/booking/addBookingViaWeb/",
dataType: 'json',
data : {
"nama_pelanggan":nama_pelanggan,
"telp":telp,
},
success: function(res) {
if (res){
alert(msg);
}
}
});
});
});
And here is my form
<form>
Nama Pelanggan <br>
<input type="text" name="nama_pelanggan" id="nama_pelanggan"><br>
Telepon<br>
<input type="text" name="telp" id="telp"><br>
<input type="button" name="simpan" id="submit" value="Simpan">
</form>
and here is my contoller function code
public function addBookingViaWeb(){
$data = array(
'nama_pelanggan' => $this->input->post('nama_pelanggan'),
'telp'=>$this->input->post('telp')
);
echo json_encode($data);
}
Here is my post param
But I got no response
any idea?
add method in from if you use post then
<form method="post" action ="" >
Try using JQuery form serialize() to declare which data you want to post. It automatically put your form input into ajax data. Example :
first set ID to your form tag
<form id="form">
then
$.ajax({
type:'POST',
url : 'http://192.168.100.100/booking_dev/booking/addBookingViaWeb/',
data:$('#form').serialize(),
dataType:'JSON',
success:function(data){
console.log(data);
}
});
First problem I see is in your ajax submission code. Change
$("#simpan").click(function(){
to
$("#submit").click(function(event){
Notice that I added the event parameter. You now need to prevent the default submission behavior. On the first line of your click method add
event.preventDefault();
Now I'm assuming that your url endpoint http://192.168.100.100/booking_dev/booking/addBookingViaWeb/ can handle POST requests. Usually this is done with something like PHP or Ruby on Rails. If I was doing this in PHP I would write something like the following:
<?php
$arg1 = $_POST["nama_pelanggan"];
$arg2 = $_POST["telp"];
// do something with the arguments
$response = array("a" => $a, "b" => $b);
echo json_encode($response);
?>
I personally don't know anything about handling POST requests with js (as a backend) but what I've given you should get the data over there correctly.
I got solution for my problem from my friend xD
just add header("Access-Control-Allow-Origin: *"); on controller function
Thank you for helping answer my problem.
I am trying to replace page reloading PHP scripts in a web page with AJAX calls.
I am using JQuery to run the AJAX scripts but it doesn't seem to be doing anything so I attempted to write an incredibly basic script just to test it.
My directory is as follows
public_html/index.php
/scripts/phpfunctions.php
/jqueryfunctions.js
index.php contains
<!DOCTYPE html>
<html>
<head>
<!-- jquery functions -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="scripts/jqueryfunctions.js"></script>
<!-- php functions -->
<?php include 'scripts/phpfunctions.php' ?>
</head>
<body>
<button type="button" id="testButt">TEST</button>
</body>
</html>
Then the phpfunctions.php page which I am trying to call contains just an echo if an argument is set
<?php
if(isset($_GET["action"])) {
echo "test has been run";
}
?>
The jqueryfunctions.js script I am trying to run is
$(document).read(function () {
$('#testButt').on('click', function () {
console.log("jquery call worked"); // this bit does run when button is clicked
$.ajax({ // this bit doesn't seem to do anything
url: 'scripts/phpfunctions.php?action=run_test',
type: 'GET',
success: function (data) {
$('#ajaxdata').html(data);
},
error: function (log) {
console.log(log.message);
}
});
});
});
I see that the jqueryfunctions.js function is being called by the first console.log but it doesn't seem to be calling my phpfunctions.php function.
I was expecting to see the php echo "test has been run" but this doesn't happen.
Did I miss something?
You should use isset() method:
<?php
if(isset($_GET["action"])) {
if($_GET["action"] == "run_test") {
echo "test has been run";
}
}
?>
and if you are using ajax then why do you need to include it on index page:
<?php include 'scripts/phpfunctions.php' ?>
and i can't find this element $('#ajaxdata') on your index page.
Also you can check the network tab of your inspector tool to see the xhr request to the phpfunctions.php and see if this gets successfull or there is any error.
I think problem is here:
$(document).read(function() {
$('#testButt').on('click', function() {
console.log("jquery call worked"); // this bit does run when button is clicked
$.ajax({ // this bit doesn't seem to do anything
url: 'scripts/phpfunctions.php',
type: 'GET',
data: {action:'run_test'}, // <------ Here
success: function(data) {
$('#ajaxdata').html(data);
},
error: function(log) {
console.log(log.message);
}
});
});
});
jQuery says:
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting.
So you should set data: {key:'value'}
Most things look fine, but your data attribute is designed for "POST" requests, try to add the data to the url as follows:
$( document ).read( function ()
{
$( '#testButt' ).on( 'click', function ()
{
console.log( "jquery call worked" ); // this bit does run when button is clicked
$.ajax( { // this bit doesn't seem to do anything
url: 'scripts/phpfunctions.php?action=run_test', // Add the GET request to the end of the URL
type: 'GET',
//data: 'action=run_test', Unrequired noise :P (this is for post requests...)
success: function ( data )
{
$( '#ajaxdata' ).html( data );
},
error: function ( log )
{
console.log( log.message );
}
} );
} );
} );
And also (as mentioned in my comments), you need to finish your bodys closing tag:
</body> <!-- Add the closing > in :P -->
</html>
I hope this helps :)
Where do you load ajaxfunctions.js? It look like in your code you never load the resource
And change
<button id="xxx">
In
<button type="button" id="xxx">
So the page isn't reloaded
I'm trying to do a custom AJAX action on WordPress but it isn't working. I have the following form:
<form method='post' name='form-bid-<?php echo get_the_ID() ?>' class="bid-form">
<input type='submit' name='<?php echo get_the_ID()?>' value='Licitar' class='bidvalue'>
<?php wp_nonce_field('ajax-bid-nonce', $post->ID); ?>
</form>
The form is this way because it's generated inside a loop, one for every post on the site, therefore I use the post ID as the unique name for the input.
Then, I capture the form submit on a custom JavaScript file:
jQuery(document).ready(function($) {
// Perform AJAX bid on form submit
$('form.bid-form').on('submit', function(e) {
var action = 'ajaxbid';
var auction_id = e.target.name.substring('form-bid-'.length);
var security_container = "#".concat(auction_id);
var security = $(security_container).val();
$.ajax({
type: 'POST',
dataType: 'json',
url: ajax_bid_object.ajaxurl,
data: {
'action': action,
'id': auction_id,
'security': security
},
success: function(data) {
console.log(data);
}
});
e.preventDefault();
});
});
This part works, and it prints 0 on the console upon success.
Finally, I have a PHP file where I register the script and have the function I want to call upon the form submission:
function ajax_bid_init() {
wp_register_script('ajax-bid-script', get_template_directory_uri() .'/js/ajax-bid-script.js', array('jquery') );
wp_enqueue_script('ajax-bid-script');
wp_localize_script( 'ajax-bid-script', 'ajax_bid_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
));
// Enable the user with no privileges to run ajax_bid() in AJAX
add_action( 'wp_ajax_nopriv_ajaxbid', 'ajax_bid' );
}
add_action('init', 'ajax_bid_init');
function ajax_bid() {
// First check the nonce, if it fails the function will break
check_ajax_referer( 'ajax-bid-nonce', 'security');
echo json_encode(array('message'=>__('SUCCESS')));
die();
}
For now, all I wanted was the function to return that array and display it on console. However, the code never seems to run through here, and the AJAX response is always 0.
I have done a quite similar approach to both login and registration on the website and they both work. I've compared the 3 endless times and I cannot seem to find what I'm missing here.
Found the issue! I forgot to mention I was trying to do this with a logged user, so the problem was this line:
add_action( 'wp_ajax_nopriv_ajaxbid', 'ajax_bid' );
It should be this instead:
add_action( 'wp_ajax_ajaxbid', 'ajax_bid' );
I copied the first from my login and register forms, which made sense to be only available for non-logged users. The bids however are the exact opposite.
Just for future reference, you can register both (wp_ajax and wp_ajax_nopriv) for the same function if you want it to be executable for both logged and non-logged users.
I am attempting to scrape a website for download links, but the links are written out like this:
<form action="" method="post" name="addondownload" id="addondownload" >
<input type="hidden" name="addonid" id="addonid" value="2109" />
<input class="red_btn" type="submit" name="send" value="Download Now!" />
</form>
and the only thing i can find that relates to this that would produce a download link of any sort is a jQuery file:
download_addon.js
jQuery(document).ready(function() {
// prepare Options Object
var options5 = {
url: url,
data: { action : 'downloadfileaddon' },
success: function(e) {
//alert(e);
//var count = e.length - 1;
var check = e.substring(0,5);
if(check == 'http:'){
//var url = e.substring(0,count);
window.location = e;
}else{
alert(e);
}
}
};
// pass options to ajaxForm
jQuery('#addondownload').ajaxForm(options5);
});
My question is, is this file responsible for returning the download link the user's browser? If so, is there a way to simulate the passing of data to this file in a php script? Perhaps in a cURL request?
Well after a bit of digging and some wireshark business, it turns out that the post should look like this:
$url = "http://www.website.com/wp/wp-admin/admin-ajax.php";
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array(
"addonid" => $mod_id,
"send" => "Download+Now!",
"action" => "downloadfileaddon"
)
));
It seems as though calling the post the website frontpage was not what needed to be done, and in fact it was a php script that is not included on the html for the website!
Good old wireshark!