Moz API getting information via jQuery .Ajax - javascript

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);
?>

Related

Submit a Form Using Jquery Ajax

Fiddle And Code:
$("form.signupform").submit(function(e) {
var data = $(this).serialize();
var url = $(this).attr("action");
var form = $(this); // Add this line
$.post(url, data, function(data) {
try {
data = JSON.parse(data);
$(.result).html(data.result + " Watchlist");
} catch (e) {
console.log("json encoding failed");
return false;
}
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="result"></p>
<form class="signupform" method="post" action="admin/signupinsert.php" onsubmit="this.onsubmit=function(){return false;}">
<input type="text" name="firstname" />
<input type="submit" value="Sign Up"/>
</form>
admin/signupinsert.php code:
// Insert into DB code in PHP
$response = new \stdClass();
$response->result = "".$result."";
die(json_encode($response));
I am trying to submit this form using My Jquery Ajax Code. And the signupinsert.php file will return a value in $result variable. I am trying to print it inside <p class="result"></p>
But, the code re-directs users to signupinsert.php page.
What's wrong?
you must prevent the default action of submitting the form
$("form.signupform").submit(function(e) {
e.preventDefault(); // <-- add this
var data = $(this).serialize();
var url = $(this).attr("action");
also, in your php file return proper JSON and avoid parsing the response in javascript with JSON.parse(data);
the output in your php file should look like this
$response = new \stdClass();
$response->result = $result;
header('Content-Type: application/json');
print json_encode($response);
and in your success handler just process the data parameter as a normal json object
$.post(url, data, function(data) {
$(.result).html(data.result + " Watchlist");
}
Also, just a curiosity, what is this supposed to do?
$response->result = "".$result."";
Update:
I just realized why you had most of the issues:
$('.result').html(data.result + " Watchlist");
^ ^
see the missing quotes
you are redirecting because of action:
action="admin/signupinsert.php"
var url = $(this).attr("action");
got me?

ajax image upload to database

I'm unable to upload the image by ajax,it always redirect to the page whenever I click submit button and the data is not added to the database as well.
form
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>" id="ImageUploadForm" enctype="multipart/form-data">
<input type="text" name="caption" id="caption">
<input type="file" name="image" id="ImageBrowse"/>
<input type="submit" class="btn btn-success" value="Save" />
</form>
ajax
$(document).ready(function (e) {
$("#imageUploadForm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "<?php echo base_url();?>adminpromisess/addgal",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data) {
alert(data);
//$("#gallery-form").load(".gallery-form");
},
error: function() {
}
});
}));
});
add data to database function (controller)
public function addgal(){
$caption = $this->input->post('caption');
$promises = 00;
$description = $this->input->post('description');
$image = $_FILES['image']['name'];
if(move_uploaded_file($_FILES['image']['tmp_name'], 'assets/img/upload/promises_image/'.$image)){
$data = array(
'caption' => $caption,
'promises' => $promises,
'gal_desc' => $description,
'image' => $image
);
$result = $this->adminpromisesmodel->addGallery($data);
}else{
echo "Fail to upload file";
die();
}
}
note:model (query) to save the database is correct so i didn't post it
Try this
$('#imageUploadForm').on('submit', function(ev){
ev.preventDefault();
var forms = document.querySelector('form#imageUploadForm');
var request = new XMLHttpRequest();
var formDatas = new FormData(forms);
request.open('post','yourControllerFunction');
request.send(formDatas);
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
//Request was OK show success message
} else {
// Request not OK, show error message
}
}
});
In your controller's action (its a cakephp code)
if($this->request->is('post')){
$data = $this->request->data;
echo "<pre>",print_r($data),"</pre>";
//You should be able to see file data in this array
}
You can handle it just like a direct form submission on your controller
ImageUploadForm != imageUploadForm
Fix that typo causing the dead code (the form tag) to run and things should work as you expect.
Your browser, development tools, network tab should have shown a POST instead of a XHR because of that issue.

Can I call function by JavaScript?

Hi I want to to run function for searching word in database. The function is in this location: media/search, up to now it was possible to run this function with this JS by "search_query":
final_transcript = capitalize(final_transcript);
var queryTextField = document.getElementById("search_query");
queryTextField.value = final_transcript;
....
"search_query" is id in this input:
<form class="input-group navbar-form" action="<?php echo base_url();?>media/search" method="post"></li>
<li style="margin-top:8px;"><input type="text" class="form-control" placeholder="Search subtitles..." id="search_query" name="string" /></li>
<li style="margin:8px><button type="submit" class="btn btn-info" name="btn_search"><i class="search "></i></button>
I want to change it so I don't want to use this HTML code. I want to implement "calling" function media/search in JS instead of:
var queryTextField = document.getElementById("search_query");
Let me know if I misunderstood you, but if I understand you correctly, you want to trigger the search with javascript?
And it looks like you want to do this without jQuery?
//get search string inputted by user
var queryTextField = document.getElementById("search_query");
var query = queryTextField.value
//pass base url to javascript
var base_url = '<?php echo base_url();?>'
//create new request
var request = new XMLHttpRequest();
//set up what you want to do with returned data
request.onreadystatechange=function()
{
//if call was successful
if (request.readyState==4 && request.status==200)
{
//response will be in here
//request.responseText;
}
}
//set as post, the url, send asynchronously
request.open('POST', base_url+'media/search', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(query);
With jQuery:
$.ajax({
type: 'POST',
url: base_url+'media/search',
data: query,
success: function(data_return) {
//do something with returned data
}
});
See:
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
and
http://api.jquery.com/jquery.ajax/
I have not tested the above code, but it should put you on the right path.

how to html form post - file uploading and reading json response from php server

i am trying file uploading to php my server.file and data uploading through multi part /form-data ,the file and data received on php server but in my php server return json response .please help me how to read json response in my webpage and if its success(code=0) means it redirect another page .the php sever is common for both android and web pages .json response look like {"code":0,"message":"success"}
<div style="height:0px;overflow:hidden">
<form id="myForm" action="http://192.168.2.4/digiid/api/addid"
method="post" enctype="multipart/form-data" runat="server">
<input type="file" name="file" id="file" onchange="showMyImage(this)" />
<input type="hidden" name="userid" value="<?php echo $_SESSION["userid"]?>">
<input type="hidden" id="inputfilename" name="filename" value="here">
</form>
</div>
<a class="button1" id="browseButton" onclick="" style="width:12%;height: 30px; text-decoration:none;"><font color="white" size="5px">Select ID</font></a>
<br/>
<div>
<img src='images/capture_picture_size.png' id='imgscreen' width='200' height='200'>
<br/>
<p id="filename" style="color: #ffffff; font-size: 20px" >
Title of the ID<br/></p>
<a class="button1"onclick="myFunction()" style= " width:12%;height: 30px; text-decoration:none;"><font color="white" size="5px">Save ID</font></a></form>
</div>
<script>
function myFunction() {
document.getElementById("myForm").submit();
}
</script>
<script>
browseButton.onclick=function chooseFile() {
document.getElementById("file").click();
};
function showMyImage(fileInput) {
var files = fileInput.files;
var file = files[0];
var imageType = /image.*/;
var img=document.getElementById("imgscreen");
var reader = new FileReader();
reader.onload = (function(aImg) {
return function(e) {
//x=e.target.result
img.src = e.target.result;
var extfilename=file.name;
document.getElementById("filename").innerHTML=extfilename.slice(0,-5) ;
document.getElementById("inputfilename").value=extfilename.slice(0,-5);
};
})(img);
reader.readAsDataURL(file);
}</script>
I think it should work for you. Using AJAX, as I do
//Your php code
$arrToJSON = array(
"dataPHPtoJs"=>"yourData",
"asYouWant"=>"<div class=\".class1\">soemting</div>"
);
return json_encode(array($arrToJSON));
//Your javaScript code
$(document).on("event", "#idElement", function(){
//Data you want to send to php evaluate
var dt={
ObjEvn:"btn_Login",
dataJsToPHP: $("#txt_EmailLogin").val()
};
//Ajax
var request =$.ajax({//http://api.jquery.com/jQuery.ajax/
url: "yourServer.php",
type: "POST",
data: dt,
dataType: "json"
});
//Ajax Done catch JSON from PHP
request.done(function(dataset){
for (var index in dataset){
dataPHPtoJsJS=dataset[index].dataPHPtoJs;
asManyasYouWantJS=dataset[index].asYouWant;
}
//JavaScript conditions. Here you can control the behaivior of your html object, based on your PHP response
if(dataPHPtoJsJS){
$( "#idYourHtmlElement" ).removeClass( "class1" )
$( "#idYourHtmlElement" ).addClass( "class2" )
}
});
//Ajax Fail
request.fail(function(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
}
You should probably use an AJAX call. Here's a solution using jQuery:
<script type="text/javascript">
$(document).ready(function(){
$("#browseButton").click(function(){
var url = "";
var formdata = $("#myForm").serialize();
$.ajax({
url: url,
type: 'POST',
data: formdata,
dataType: 'json',
cache: false,
contentType: false,
processData: false,
success: function(response){
if(response.status == "success"){
// Success
} else {
// Failure
}
},
error: function(response){
// Error
}
});
});
});
</script>
In order to redirect the user, you can use: window.location.href = " ... your_url ...";
Here's an explanation on how to use jQuery AJAX and multi-part data:
Sending multipart/formdata with jQuery.ajax
try json_decode.
$data = ({"code":0, "message":"success"});
$array = json_decode($data, true);
by passing 2nd parameter to true you will get response in array instead of object.
the array will be then populated as follow:
array (size=2)
'code' => int 0
'message' => string 'success' (length=7)
Your JSON response would be a kind of associative array in php.
Encode your array data into JSON using "json_encode" and return values as you want .
$arr = array('status' => $status, 'status2' => $status2, );
echo json_encode($arr);
NOTE: If you are using ajax to call php file then do not use any php echo/print in that file and not even HTML. ECHO only "json_encode();" Nothing else.
To sum it up:
Upload your data to server using AJAX with native JS (>=IE10) or jQuery
Catch (xhr.responseText in native JS) and parse the response
Redirect with window.location.href="success.php"

Trying to scrape hidden download links

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!

Categories