Data manipulation for Instgram API with Ajax and JSON - javascript

Im trying to retrieve users from Instagram API whose names contain the certain word from a JSON file , by using this jQuery
I had to make a PHP file as a server in my local host i named it ' get_info.php' and it return an Array of elements
but for some reason I can't seem to display the output after manuplating the data :(
I'm new to Ajax and JSON, could you possibly help me find the error in my code?
here's my JavaScript
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" >
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
var jsonObj ;
var q = document.getElementById('keyword').value;
ajaxRequest.open('POST', 'get_info.php?keyword='+ q , true);
// callback function to handle the server response
ajaxRequest.onreadystatechange = function() {
if (ajaxRequest.readyState == 4) {
if ((ajaxRequest.status >= 200 && ajaxRequest.status < 300) || ajaxRequest.status === 304) {
var jsonObj = ajaxRequest.responseText;
jsonStr = JSON.parse( jsonObj );
}
}
}
$(document).ready(function () {
$("#submit").click(function(){
$.ajax({
type: 'GET',
url:'get_info.php',
data: { keyword: q },
success: function(jsonStr) {
$.each( jsonStr.data , function(index, element) {
var res ;
res += '<img src="'+element.username+'"/>';
res += '<img src="'+element.profile_picture+'"/>';
});
$("#photos").html(res);
}
});
});
});
}
</script>
The HTML only has these tags.
<form id="form" method="POST" onclick="ajaxFunction();" >
<input value="" id="keyword" type="text" required>
<input value="search" id="submit" type="submit" >
</form>
<div id="photos"> </div>

To avoid confusion, jquery ajax is enough
<script>
$(document).ready(function () {
var q = document.getElementById('keyword').value;
$("#submit").click(function(e){
e.preventDefault();
$.ajax({
type: 'GET',
url:'get_info.php',
data: { keyword: q },
success: function(jsonStr) {
var element = jsonStr.data;
var res ;
for(var i = 0; i<element.length;i++) {
res += '<img src="'+element[i].username+'"/>';
res += '<img src="'+element[i].profile_picture+'"/>';
}
$("#photos").html(res);
}
});
});
});
</script>
Remove the onclick from form
<form id="form" method="POST" >
<input value="" id="keyword" type="text" required>
<input value="search" id="submit" type="submit" >
</form>
<div id="photos"> </div>
Check and let me know what you are getting in the console

<?php
//Get data from instagram api
$keyword = $_GET['keyword'];
if(!isset($_GET['count'])) $count = 20;
else $count = $_GET['count'];
//Query need client_id or access_token
$query = array(
'client_id' => '',
'count' => $count
);
$url = 'https://api.instagram.com/v1/users/search?q='.$keyword.'&'.http_build_query($query);
try {
$curl_connection = curl_init($url);
curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);
//Data are stored in $data
$data = curl_exec($curl_connection);
curl_close($curl_connection);
echo $data;
} catch(Exception $e) {
return $e->getMessage();
}
?>

Related

Probleme with ajax

I need help with my project, i have to do an 'drag n drop' zone, and, when the image is droped, it must be saved on the server (via PHP, which I succeeded), but also appear on the HTML thanks to the response from AJAX via PHP. I don't know what to do anymore, here is some code bugs. Each time I see the JS alert announces: 'An exception is produced: undefined'. I don't use Jquery or anyting else, it's just vanilla PHP and Javascript, Thanks for your help
Sorry for my bad English, I'm french :)
my code :
<body onload="init()" >
<div id="drop_file_zone" ondrop="upload_file(event)" ondragover="return false">
<div id="drag_upload_file">
<p>Drop file here</p>
<p>or</p>
<p><input type="button" value="Select File" onclick="file_explorer();"></p>
<input type="file" id="selectfile">
</div>
</div> <br>
<img id = "imageSource" src="uploads/"/>
<script type="text/javascript">
var fileobj;
var url = "ajax.php";
function upload_file(event) {
event.preventDefault();
var target = document.getElementById ("drop_file_zone");
for (var i = 0; i < 1; i++) {
var fileobj = event.dataTransfer.files[i];
ajax_file_upload(fileobj);
}}
function file_explorer() {
document.getElementById('selectfile').click();
document.getElementById('selectfile').onchange = function() {
fileobj = document.getElementById('selectfile').files[0];
ajax_file_upload(fileobj);
};
}
function init() {
request = new XMLHttpRequest();
var x = document.getElementById("imageSource");
}
function prepareData() {
let url = "ajax.php";
makeRequest( url, fileobj );
}
function ajax_file_upload(file_obj) {
request.onreadystatechange = alertContents;
var formData = new FormData();
formData.append('file', file_obj);
request.open('POST', url)
request.send(formData)
}
function alertContents() {
try {
if (request.readyState === XMLHttpRequest.DONE) {
if (request.status === 200) {
var reponse = JSON.parse( request.reponseText);
x.setAttribute("src", 'uploads' + reponse.text);
//document.getElementById("imageSource").src = reponse.text;
} else {
alert("Un problème est survenu au cours de la requête.");
}
}
}
catch( e ) {
alert("Une exception s’est produite : " + event.description);
}
}
</script>
</body>
</html>
And my PHP
<?php
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/'. $_FILES['file']['name']);
$test = '{ "text":"uploads/'.$_FILES['file']['name'].'"}';
echo $_FILES['file']['name'] ;

Send data from JavaScript with AJAX and JSON to the server and retrieve data from the server

I am new to AJAX and JSON. I found some code from this link and modified it:
send json object from javascript to php
What I want is this:
I have some data (variables, arrays, ect.) in JavaScript which are dynamic (the user can change this values at runtime). Now I want to send this data to the server and save it in a PHP file. I also want to retrieve the updated data from the server. In short explained I want to save from client to server and load from server to client.
I become an error in Load() on line "alert(jsondata.num);": Cannot read property 'num' of nullat XMLHttpRequest.xhr.onreadystatechange
PHP:
<?php
header('Content-type: application/json');
$json = file_get_contents('php://input');
$json_decode = json_decode($json, true);
$json_encode = json_encode($json_decode);
echo $json_encode;
?>
JavaScript:
function Save() {
var jsondata;
var num = {"num":Math.floor(Math.random()*100)};
var data = JSON.stringify(num);
var xhr = new XMLHttpRequest();
xhr.open("POST", "demo.php", !0);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(data);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// in case we reply back from server
jsondata = JSON.parse(xhr.responseText);
console.log(jsondata);
alert(jsondata.num);
}
}
}
function Load() {
var jsondata;
var xhr = new XMLHttpRequest();
xhr.open("GET", "demo.php", !0);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// in case we reply back from server
jsondata = JSON.parse(xhr.responseText);
alert(jsondata.num);
}
}
}
I have created this for you for clarity. It allows user to send email and name and return json data to clients. With this you now have basics..
<!doctype html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
type="text/javascript" charset="utf-8"></script>
<script>
$(document).ready(function(){
// submit button click
$("#submit").click(function(){
var name = $("#name").val();
var email = $("#email").val();
alert(name);
if(name != ''){
$.ajax({
url: 'demo.php',
type: 'post',
data: {name:name,email:email},
dataType: 'JSON',
success: function(response){
alert(response.name);
// selecting values from response Object
var name = response.name;
var email = response.email;
var dt = "<div>";
dt += "<b>Email:</b>"+email+"<br>";
dt += "<b>name:</b>"+name+"<br>";
}
});
}
});
});
</script>
</head>
<body>
<div class="container">
<div class="content">
<h1>Enter Details</h1>
<div>
<input type="text" id="name" name="name" placeholder="Name">
</div>
<div>
<input type="email" id="email" name="email" placeholder="email">
</div>
<div>
<input type="button" value="Submit" id="submit">
</div>
</div>
<div id="Result">
</div>
</div>
</body>
</html>
demo.php
<?php
$name = $_POST['name'];
$email = $_POST['email'];
// insert into database
//response
$return_arr = array('name'=>$name,'email'=>$email);
echo json_encode($return_arr);

image upload using javascript?

This is my HTML and javascript.
I'm trying to upload an image using javascript.
I did find some examples using jquery, but was hoping if this function below can be modified to do the same.
The image upload script is a PHP script, which works when the form is posted normally, but when using this function below, it doesn't send the image to the PHP script. $_FILES is empty.
How can I modify this function to send the image as well?
<html><head>
<script type="text/javascript">
function jax( ){
pd = document.getElementById("pd").innerHTML;
i = document.getElementById("i").value;
url= "ajax.php"; //?act=uploadPic&title=" + pd + "&i=" + i;
q="act=uploadPic&title=" + pd + "&i=" + i;
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
}
catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
alert("Your browser does not support ajax. Allow Active scriptting in internet settings."); return false;
}
}
}
ajaxRequest.onreadystatechange= function(){
if(ajaxRequest.readyState == 4){
r =ajaxRequest.responseText;
alert(r);
}
}
ajaxRequest.open("POST", url, true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.send(q);
}//func
</script>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<p> Title: <input type="text" name="pd" id="pd" value=" Title here " />
<p> Image: <input type="file" name="i" id="i" />
<p> <button onclick=" jax( ) "> Upload </button>
</form>
</body>
</html>
The PHP script to verify if image is send:
ajax.php
<?php print_r($_FILES); ?>
this is my function,but can't working lower than ie8:
function jax(){
url= "ajax.php?act=uploadPic";
var formData = new FormData(document.forms[0]);
var xhr = new XMLHttpRequest();
xhr.open('post',url,true);
xhr.onreadystatechange = function(){
if (xhr.readyState == 4) {
if (xhr.status == 200) {
console.log(xhr.responseText);
}
}
}
xhr.addEventListener('progress',function(e){
if (e.lengthComputable) {
console.log(e.loaded+'/'+e.total);
}
},false);
xhr.send(formData);
}

post a form using ajax and returning the results to span or div

I would like to submit a form using ajax and return the results to the same page using innerHTML. But it seems the input value on the form is not getting passed to the action which is a php.
Here is my html form
<form id="check" method="POST" onsubmit="return checkFunction();">
<p>
<label for="store">Type Store Number to check:</label>
<input type="text" id="store" name="storenum" maxlength="4"/>
</p>
<p>
<input type="submit" value="Check" onclick="return checkFunction();"/>
</p>
</form>
This is where I would like the results returned on the same page
<span id="results"></span>
And this is how I put together the ajax call
function checkFunction(){
var ajaxRequest;
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.getElementById("results").innerHTML = ajaxRequest.responseText;
}
}
ajaxRequest.open("POST","run.php",true);
ajaxRequest.send();
}
And this is how the php action file put together
<?php
$storeNum = $_POST['storenum'];
echo "<pre>Store number: " . $storeNum . "</pre>";
$pingresult = shell_exec("./ping_isp.sh $storeNum");
echo "<pre>$pingresult</pre>";
if (strpos($pingresult, 'ISP was unreachable') == true) {
echo '<script language="javascript">';
echo 'alert("ISP not available")';
echo '</script>';
die();
}
echo "<br>";
?>
If I use directly the php on the form as action let say like below it works perfectly
<form id="check" method="POST">
<p>
<label for="store">Type Store Number to check:</label>
<input type="text" id="store" name="storenum" maxlength="4"/>
</p>
<p>
<input type="submit" value="Check" formaction="run.php"/>
</p>
</form>
But this will return the results on another page. I would like to get the results returned on the same page. Hope you guys can help me out on this.
I agreee with #chris85, this could be dangerous to do. In any event, to answer your question I've made the changes to your code that I believe you need...
function checkFunction(){
var ajaxRequest;
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.getElementById("results").innerHTML = ajaxRequest.responseText;
}
}
var storevalue = document.getElementByID("storenum").value;
ajaxRequest.open("POST","run.php",true);
ajaxRequest.send("storenum=" + storevalue);
}
Please forgive me if I've made any slight mistakes in coding, this is untested and it's possible I made a typo that I've missed.
EDIT: I had a little more time this morning than yesterday, so I took your code and reworked it a bit. The version below now works and should give you the result you're looking for.
function checkFunction(){
var xmlhttpmod;
var storevalue = document.getElementByID("store").value;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttpmod=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttpmod=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttpmod.onreadystatechange=function() {
if (xmlhttpmod.readyState==4 && xmlhttpmod.status==200) {
// console.log(xmlhttpmod.responseText);
document.getElementById("results").innerHTML = xmlhttpmod.responseText;
}
}
xmlhttpmod.open("POST","test.php",true);
xmlhttpmod.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttpmod.send("storenum="+storevalue);
}
try this and post your results please
<form id="check" method="POST">
<p>
<label for="store">Type Store Number to check:</label>
<input type="text" id="store" name="storenum" maxlength="4"/>
</p>
<p>
<input type="button" value="Check" id="submitMyForm"/>
</p>
<div id="response"></div>
</form>
your php file:
<?php
if($_POST){
$required = array('storenum');
$error = false;
foreach($required as $key){
if(empty($_POST[$key])){
$error = true;
}
}
if(!$error){
// process data or whatever you need
}
else{
echo 'empty field error';
}
}
else{
header("Location: ../login.php");
}
and your ajax
$('#submitMyForm').on('submit', function(){
var thisForm = $(this),
url = thisForm.attr('action'),
type = thisForm.attr('method'),
data = {};
thisForm.find('[name]').each(function(index, value){
var thisField = $(this),
name = thisField.attr('name'),
value = thisField.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
$('#response').hide().html(response).fadeIn(700);
},
error: function(){
$('#response').hide().html('<span class="label label-danger">Ocurrió un error desconocido</span>').fadeIn(700);
}
});
return false;
});

Adding a loading text while an AJAX function is executing

I've been trying to add a loading text that would display while an AJAX function is being executed for a long while now, and all of my attempts (which includes using the ajaxStart and ajaxStop, among other things) haven't been working at all. Any help is appreciated!
Here is the webpage that the script in question is located on, if you want to see it in action. The way it works is that you enter in a url and the function will grab the meta tags of that URL.
Meanwhile, here is the relevant HTML, Javascript, and PHP:
HTML
<!DOCTYPE html>
<html>
<head>
<title>Keywords Grabber</title>
<script src="ajax.js"></script>
<script>
function display(content) {
document.getElementById("displaydiv").innerHTML = content;
}
window.onload = function () {
document.getElementById("btn1").onclick = function () {
var url = document.getElementById("txt1").value;
doAjax("metatags.php", "url=" + url, "display", "post", 0);
}
}
</script>
</head>
<body>
http://<input type="text" id="txt1" value="" />
<input type="button" id="btn1" value="Get Keywords" />
<h3>Keywords Received:</h3>
<div id="displaydiv"></div>
</body>
</html>
JavaScript
function getXMLHttpRequest() {
try {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e) {
return new ActiveXObject("Msml2.XMLHTTP");
}
}
catch(e) {
return new XMLHttpRequest();
}
}
function doAjax(url, query, callback, reqtype, getxml) {
var myreq = getXMLHttpRequest();
myreq.onreadystatechange = function () {
if (myreq.readyState == 4) {
if (myreq.status == 200) {
var item = myreq.responseText;
if (getxml == 1) item = myreq.responseXML;
eval(callback + '(item)');
}
}
}
if (reqtype.toUpperCase() == "POST") {
requestPOST(url, query, myreq);
} else {
requestGET(url, query, myreq);
}
}
function requestGET(url, query, req) {
var myRandom = parseInt(Math.random()*99999999);
if (query == '') {
var callUrl = url + '?rand=' + myRandom;
} else {
var callUrl = url + '?' + query + '&rand=' + myRandom;
}
req.open("GET", callUrl, true);
req.send(null);
}
function requestPOST(url, query, req) {
req.open("POST", url, true);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
req.send(query);
}
PHP
<?php
$tags = #get_meta_tags('http://'.$_REQUEST['url']);
$result = $tags['keywords'];
if(strlen($result) > 0) {
echo $result;
} else {
echo "No keywords metatag is available.";
}
?>
something like this
<div id="loading" style="display:none;">loading</div>
Javascript
$('#loading').css('display', 'block');
$.post(url, {}, function(data){
$('#loading').css('display', 'none');
});

Categories