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!
Related
So I'm having some issues with my AJAX form submission and I can't seem to figure out why, below I will be explaining all the steps that I will be taking to attempt to submit the form.
The scripts are enqueued [WORKS]: Ensures that the file holding the ajax request is loaded which it is.
function enqueue_scripts()
{
if (!is_admin()) {
wp_register_script('profile_edit_submit', content_url() . '/mu-plugins/fleishmanhillard/scripts/frontend-profile-edit.js', ['jquery'], '', true);
wp_localize_script( 'profile_edit_submit', 'profile_edit', [
// This will generate the admin URL that we can use on the front-end of our website
'ajax_url' => admin_url('admin-ajax.php'),
// Pass in a custom nonce name for JS
'nonce' => wp_create_nonce('update_profile_validation'),
]);
wp_enqueue_script('profile_edit_submit');
}
}
add_action('wp_enqueue_scripts', 'enqueue_scripts');
This updates the post ID's post_content [WORKS]: On submission, it updates the database content of the right ID.
if (strtolower($_SERVER['REQUEST_METHOD']) === "post") {
// #todo: Make sure that the account is associated with the logged in account on profile edits
// If profile isn't empty, continue
if (!empty($profile)) {
// Grab the content submitted
// #todo: Figure out how to set the $_POST request to a function
$post_content = $_POST['content'];
wp_update_post([
'ID' => $profile->get_id(),
'post_content' => $post_content,
]);
}
}
HTML [WORKS]:
<form action="" id="profile_update" method="POST">
<input type="text" name="content" id="post_content" class="required">
<input type="hidden" name="submitted" id="submitted" value="true" />
<button type="submit"><?= 'Update Post' ?></button>
</form>
PROBLEM: So the submission works but it refreshes the page on submit, but I'd like to move forward with an AJAX submission but I don't know where to begin.. here is what I have, but it's not working correctly.
(function ($) {
$(function($) {
$('.profile_update').on('click', function() {
$.ajax({
type: 'POST',
url: profile_edit.ajaxurl,
data: {
}
});
});
});
})(jQuery);
When I submit the form, it updates the database and also changes the server request from GET to POST.
we have to change the javascript.
(function ($) {
$(function($) {
$('#profile_update').on('submit', function(e) {
$.ajax({
type: 'POST',
url: profile_edit.ajaxurl,
data: $('#profile_update').serialize();
});
return false;
});
});
})(jQuery);
change the html this way
<form action="" method="POST">
<input type="text" name="content" id="post_content" class="required">
<input type="hidden" name="submitted" id="submitted" value="true" />
<button type="button" id="profile_update"><?= 'Update Post' ?></button>
</form>
you are selecting a CSS class by using . in jQuery you need to use #
it should be
$('#profile_update')
Hi everyone I had written code to capture image of div tag when click on button and javascript code will capture that image ,but i want to save that captured image using codeigniter but we can't using default codeigniter upload method because upload only work for input type file which create one object but here getting captured image by javascript so i want to upload that image in folder so please tell me how to do that using codeigniter.below i mentioned my code.
Html code....
<div id="target" style="border: 1px solid #CCC;padding: 5px;margin: 5px;">
<div>
<p>PHP is a server-side scripting language designed primarily for web development.</p>
</div>
</div>
<form method="POST" enctype="multipart/form-data" id="form1">
<input type="hidden" name="img_value" id="img_value" value="" />
</form>
<input type="submit" value="Screenshot" onclick="capture();" />
javascript code to captured image and call ajax to save image
<script type="text/javascript">
function capture() {
$('#target').html2canvas({
onrendered: function (canvas) {
//Set hidden field's value to image data
$('#img_value').val(canvas.toDataURL("image/png"));
//Submit the form1
var hid_img=$("#img_value").val();
$.ajax({
url: "<?= base_url('controller/save_img') ?>",
type: "POST",
data: {
hid_img: hid_img,
},
success: function (response) {
$(".show_img").html(response);
}
});
}
});
}
</script>
code in controller method of codeigniter to save image in folder...
public function save_img() {
$data = $this->input->post($hid_img);
$file = md5(uniqid()) . '.png';
// remove "data:image/png;base64,"
$uri = substr($data,strpos($data,",")+1);
// save to file in uploads folder of codeigniter
file_put_contents('./uploads'.$file, base64_decode($uri));
}
to store image in table
$res=$this->db->insert('demo',array('img'=>base_url('uploads/').$file));
$detail = $this->db->select('*')->from('demo')->where('id', $this->db->insert_id())->get()->row();
echo '<img src="'.base_url('uploads/').$detail->message.'" style="width:500px;"/>';
As you correctly elucidated the upload library only works with file inputs and not base64 streams. So you can't use that.
Using your method, you have a few errors in your code that need to be addressed:
$this->input->post($hid_img) should be $this->input->post('hid_img')
./uploads should probably have an end slash: './uploads/'.$file
Use this sample. It is working good. First, if you check upload library.
$config = array(
'upload_path' => "./uploads/",
'allowed_types' => "gif|jpg|png|jpeg|pdf",
'overwrite' => TRUE,
'max_size' => "2048000", // Can be set to particular file size , here it is 2 MB(2048 Kb)
'max_height' => "768",
'max_width' => "1024"
);
$this->load->library('upload', $config);
if(!$this->upload->do_upload('taskcat_img'))
{
echo $this->upload->display_errors();
}
else
{
$data = $this->upload->data();
$imgval = array('success' => 'success' ,'data_image' => $data["file_name"]);
echo json_encode($imgval );
}
I'm having issues getting data back from the moz api using php and ajax. I would like the user to be able to enter a url and then have a function that replaces a divs html. the hello.php is from the Moz Api. I'm using MAMP and my code is as follows:
<div class="container">
<h1>hello from gulp automation tool</h1>
<form method="post" action="">
<label for="url">Enter URL:</label><input value="" type="url" name="url" id="url"/>
<input type="submit" value="Get URL Metrics!"/>
</form>
<div class="info">
</div>
</div>
<script>
$(document).ready(function(){
$('form').on('submit', function(e){
e.preventDefault();
var dataUrl = $('form input[type=url]').val();
$.ajax({
url: "hello.php",
type: "POST",
method: "POST",
dataType: 'json',
data: dataUrl,
success: function(response){
$('.info').html(
response[0].pda
);
}
});
});
});
</script>
Below is the code that is in the hello.php file.
<?php
// Add your accessID here
$AccessID = 'mozscape-a034cdc391';
// Add your secretKey here
$SecretKey = '6ac62e3e6df3ad617c7cf3fef891df9d';
// Set the rate limit
$expires = time() + 300;
// Put each parameter on a new line.
$stringToSign = $accessID."\n".$expires;
// Get the "raw" or binary output of the hmac hash.
$binarySignature = hash_hmac('sha1', $stringToSign, $secretKey, true);
// Base64-encode it and then url-encode that.
$urlSafeSignature = urlencode(base64_encode($binarySignature));
// Add up all the bit flags you want returned.
// Learn more here: https://moz.com/help/guides/moz-api/mozscape/api-reference/url-metrics
$cols = "68719476736";
// Put it all together and you get your request URL.
$requestUrl = "http://lsapi.seomoz.com/linkscape/url-metrics/? Cols=".$cols."&AccessID=".$accessID."&Expires=".$expires."&Signature=".$urlSafeSig nature;
// Put your URLS into an array and json_encode them.
$batchedDomains = array($_POST['data']);
$encodedDomains = json_encode($batchedDomains);
// Use Curl to send off your request.
// Send your encoded list of domains through Curl's POSTFIELDS.
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => $encodedDomains
);
$ch = curl_init($requestUrl);
curl_setopt_array($ch, $options);
$content = curl_exec($ch);
curl_close( $ch );
$contents = json_decode($content);
print_r($contents);
?>
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".
So all I am trying to accomplish is simply upload a file with codeigniter using the File Uploading Class
For my controller I have the following code:
function do_upload()
{
$config['upload_path'] = './assets/productImages/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
var_dump($error);
}
else
{
$data = array('upload_data' => $this->upload->data());
}
}
And then my form is as follows:
$data['productImage'] = array(
"name" => "userfile",
"id" => "product_image",
);
// displays out as:
<input type="file" name="userfile" value="" id="product_image">
My javascript is as follows which uses an onchange action to trigger the upload process.
$("document").ready(function(){
$("#product_image").change(function() {
var path = $(this).val();
var dataString = 'userfile=' + path;
//alert(dataString); return false;
$.ajax({
type: "POST",
url: "/account/do_upload/",
data: dataString,
success: function(data) {
alert(data);
}
});
return false;
});
});
When I run this code, I receive this message in the javascript alert
You did not select a file to upload.
What do I need to add to make this work? I'm guessing it has something to do with processing the upload through the javascript ajax.
*UPDATE DUE TO COMMENTS *
My form tag is as follows:
$data['newPostForm'] = array('id' => 'newPostForm', 'type' => 'multipart');
// And echoes out as :
<form action="http://myurl.com/index.php/account/submitPost" method="post" accept-charset="utf-8" id="newPostForm" type="multipart">
Your codeigniter code looks fine.
The problem is that you can't upload files directly through Ajax. You need to do it though an iframe.
This plugin here works a treat.
Or if you only need it to work in html 5 then this should do the treat
http://www.devbridge.com/projects/html5-ajax-file-upload/