call jquery function in a php while loop - javascript

I need to call a jquery function from a php while loop
my code
$msg_body = "Test%20SMS";
while($mobList = mysql_fetch_array($resSet))
{
$mobile = $mobList['mobile'];
if($mobile)
{
?>
<script>
$(document).ready(function()
{
var mob = <?php echo $mobile;?>;
var msgBody = <?php echo $msg_body;?>
var url = "http://example.com/abc.php?msg=TEXT&sendTo="+mob+"&message="+msgBody+"&method=sendMessage";
$.get( url, function( data )
{
alert( "SMS SEND to : "+mob );
});
});
</script>
<?php
}
}
it is running for one time, ie if more than one mobile numbers are there it will execute once and send one sms,
Alert is not working.

I used CURL,
now its OK
if($scm_mobile)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$data = curl_exec($ch);
}

Related

How do I pass a PHP array to a JavaScript variable?

I have the following JavaScript that sends parameters to a PHP file:
function getOutput()
{
$.ajax({
url:'myPHPFile.php',
data:{APIKey:$APIKey,Password:$APIPass,Alias:$Alias,DataCenter:$DataCenter},
type:'POST',
complete: function (response) {
$('#output').html(response.responseText);
},
error: function ()
{
$('#output').html('Bummer: there was an error!');
}
});
return response.responseText;
}`
Which changes the following HTML to the output of the PHP file:
test
Here is the PHP
<?php
// echo nl2br("\nIntializing api.php \n");
// DATA SECTION
$APIKey = $_POST["APIKey"];
$APIPass = $_POST["Password"];
$AccountAlias = $_POST["Alias"];
$dataCenter = $_POST["DataCenter"];
$data = array(
"APIKey" => $APIKey,
"Password" => $APIPass,
);
$url_send = 'https://api.ctl.io/REST/Auth/Logon/';
$json_data = json_encode($data);
function sendPostData($url, $post, $cook = null){
// echo "Beginning sendPostData($url, $post, $cook)";
$ch = curl_init($url);
$headers= array('Accept: application/json','Content-Type: application/json');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
if (!empty($cook))
{
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json','Content-Type: application/json','Cookie:'.$cook));
}
$result = curl_exec($ch);
curl_close($ch); // Seems like good practice
return $result;
};
$myresult = sendPostData($url_send, $json_data);
// print_r ($myresult);
$decodedresult = json_decode($myresult);
// print_r ($decodedresult);
'/reply-(.*?)-private/';
preg_match_all('/Tier3(.*?)path=/', $myresult, $matches);
$cookies = array();
foreach($matches[0] as $item)
{
parse_str($item, $cookie);
$cookies = array_merge($cookies, $cookie);
}
$prefix = 'Tier3.API.Cookie=';
$cookie = implode(" ",$matches[0]);
// Call the customer server list
$data = array(
'AccountAlias' => $AccountAlias,
'Location' => $dataCenter
);
$data_url = 'https://api.ctl.io/REST/Server/GetAllServersForAccountHierarchy/';
$data_string = json_encode($data);
$dataResult = sendPostData($data_url,$data_string, $cookie);
print_r($dataResult);
return $dataResult;
`
How can I get the $dataResult PHP array into a javascript variable so I can parse it? It is a big JSON response from an API.
Thanks.
Ajax calls are (normally) asynchronous, this means that the return response.responseText; will be executed immediately and should even raise an error related to response being undefined.
You'll have the response in the complete event of the ajax call and is inside there where you should go on with the execution of the script. jQuery will parse the JSON automatically and response will be the resulting object.
At the other side, the PHP script should just print the result of json_encode() and nothing else in order for the response to be valid JSON.

Add alert box after procces is successful

I have this PHP cURL code. I know this is a simple question. I just want to have an alert box right after the process is done but I don't know where to put my code and its right format. Can someone help?
function myFunction() {
alert("Successfull!");
}
PHP
<?php
$account = $_POST["selectbasic-0"];
$sitename = $_POST["siteAlias"];
//Initiate cURL
$ch = curl_init();
//Set cURL parameters
curl_setopt($ch, CURLOPT_URL, '');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, "");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data))
);
$output = curl_exec($ch);
curl_close($ch);
?>
if your output variable returns 1 (true) then you can try this.
if($output) {
echo "<script>";
echo "alert(""\Successfull!\");";
echo "</script>";
}
Your php is a server side script. You can't call javascript functions from server. You could
echo 'success';
or
echo '<script>alert("success");</script>';
after curl_exec function which returns true or false.

Return information result to multiple input fields

I am attempting to create a simple web element that on request, retrieves the page title / meta description of a webpage by using: php / ajax / jquery.
I have it working to a point, though I am not sure how to prepare the returned information in the PHP and on success, so that the $title appears in an input field and the $description appears in a separate input field.
At the moment it just returns to one echo'ed block.
HTML
<a href="javascript:retrievepageinformation()" >Action request</a>
<div>The URL</div>
<input name="theaddress" type="text" id="theaddress" value="http://">
<div>The result</div>
<input name="title" id="title" value="" />
<input name="description" id="description" value="" />
Javascript
function retrievepageinformation () {
$("#title").val('Retrieving..');
$("#description").val('Retrieving..');
var dataqueryurl = $("#theaddress").val();
$.ajax({
type: "POST",
url: "request-information.php",
data: "dataqueryurl="+ dataqueryurl,
success: function(dataresult){
$("#title").ajaxComplete(function(){
$(this).val(dataresult);
});
}
});
}
PHP (request-information.php)
if(isSet($_POST['dataqueryurl'])) {
function file_get_contents_curl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$dataqueryurl = $_POST['dataqueryurl'];
$html = file_get_contents_curl($dataqueryurl);
//parsing begins here:
$doc = new DOMDocument();
#$doc->loadHTML($html);
$nodes = $doc->getElementsByTagName('title');
// Get and display what you need:
$title = $nodes->item(0)->nodeValue;
$metas = $doc->getElementsByTagName('meta');
for ($i = 0; $i < $metas->length; $i++)
{
$meta = $metas->item($i);
if($meta->getAttribute('name') == 'description')
$description = $meta->getAttribute('content');
}
// Data to pass back to input field 'Title'
echo $title;
// Data to pass back to input field 'Description'
echo $description;
}
To pass back information from request-information.php you can use concept of array and json_encode.
function file_get_contents_curl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$dataqueryurl = $_POST['dataqueryurl'];
$html = file_get_contents_curl($dataqueryurl);
//parsing begins here:
$doc = new DOMDocument();
#$doc->loadHTML($html);
$nodes = $doc->getElementsByTagName('title');
// Get and display what you need:
$title = $nodes->item(0)->nodeValue;
$metas = $doc->getElementsByTagName('meta');
for ($i = 0; $i < $metas->length; $i++)
{
$meta = $metas->item($i);
if($meta->getAttribute('name') == 'description'){
$description = $meta->getAttribute('content');
}
}
$result = array('title'=>$title, 'desc'=>$description);
echo json_encode($result);
}
And to get this information in your javascript you can use $.parseJSON() in the success callback of ajax.
function retrievepageinformation () {
$("#title").val('Retrieving..');
$("#description").val('Retrieving..');
var dataqueryurl = $("#theaddress").val();
$.ajax({
type: "POST",
url: "request-information.php",
data: "dataqueryurl="+ dataqueryurl,
success: function(dataresult){
dataresult = $.parseJSON(dataresult);
$("#title").val(dataresult.title);
$("#description").val(dataresult.desc);
}
});
}
In the php side
echo json_encode(array("title"=>"My title","description"=>"Test description"));
In the ajax success
success: function(dataresult){
$("#title").val(dataresult.title);
$("#description").val(dataresult.description);
}
FYI
json_encode

Replace whateverorigin.org call with local proxy in php

I'm currently using whateverorigin.org in some javascript to retrieve a URL as a JSON object because a 3rd party site hasn't made one of their functions available via their JSON API.
I'd like to remove this dependancy from my website as whateverorigin.org breaks the HTTPS/SSL browser checks for secure content because it's a clear http call.
Has anyone done this? I haven't found an example of it anywhere.
Thanks in advance for a response!
Ok, so since I first typed up this question, I've now already found some examples and cobbled together a working proxy function in php... Feel free to use it for your own purposes!
<?php
// Sourced from: http://stackoverflow.com/questions/2511410/curl-follow-location-error
function curl_exec_follow(/*resource*/ &$ch, /*int*/ $redirects = 20, /*bool*/ $curlopt_header = false) {
if ((!ini_get('open_basedir') && !ini_get('safe_mode')) || $redirects < 1) {
curl_setopt($ch, CURLOPT_HEADER, $curlopt_header);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $redirects > 0);
curl_setopt($ch, CURLOPT_MAXREDIRS, $redirects);
return curl_exec($ch);
} else {
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FORBID_REUSE, false);
do {
$data = curl_exec($ch);
if (curl_errno($ch))
break;
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($code != 301 && $code != 302)
break;
$header_start = strpos($data, "\r\n")+2;
$headers = substr($data, $header_start, strpos($data,"\r\n\r\n", $header_start)+2-$header_start);
if (!preg_match("!\r\n(?:Location|URI): *(.*?) *\r\n!",$headers, $matches))
break;
curl_setopt($ch, CURLOPT_URL, $matches[1]);
} while (--$redirects);
if (!$redirects)
trigger_error('Too many redirects. When following redirects, libcurl hit the maximum amount.', E_USER_WARNING);
if (!$curlopt_header)
$data = substr($data, strpos($data, "\r\n\r\n")+4);
return $data;
}
}
header('Content-Type: application/json');
$retrieveurl = curl_init(urldecode($_GET['url']));
$callbackname = $_GET['callback'];
$htmldata = curl_exec_follow($retrieveurl);
if (curl_error($retrieveurl))
die(curl_error($retrieveurl));
$status = curl_getinfo($retrieveurl, CURLINFO_HTTP_CODE);
curl_close($retrieveurl);
$data = array('contents' => $htmldata, 'status' => $status);
$jsonresult = json_encode($data);
echo $callbackname . '(' . $jsonresult . ')';
?>
Hope this helps someone!

Using ajax instead of using a php file with curl to get a response from another webpage

I have a task to find a way to stop using the php curl, and I have to use only javascript without jQuery.
This was my php file and it was called by another ajax:
$jsonData = json_decode(file_get_contents('php://input'));
$url ='https://api.#######.com/####'; // this is not my website, just using their api
$ch = curl_init();
$data = array(
'text' => $jsonData,
'from' => 'eng',
'to' => 'fra'
);
$data_encoded = json_encode($data);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
'Authorization: SECRET apikey=###'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_encoded);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$result = curl_exec($ch);
echo $result;
This is my new ajax but i get this error: NS_ERROR_FAILURE: Failure
function getTranslation(a_data,from,to)
{
var json_array = {};
var url = 'https://api.#####.com/#####';
var xmlhttp;
json_array = { 'text': a_data,
'from' : 'eng',
'to' : 'fra' };
var json_data = JSON.stringify(json_array);
console.log(json_data);
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST", url, false);
xmlhttp.setRequestHeader("Content-type","application/json");
xmlhttp.setRequestHeader("Authorization","SECRET apiKey=###");
xmlhttp.send();
json_parsed = JSON.parse(xmlhttp.responseText);
return json_parsed.translation;
}
If i missed something please let me know I will add more details.
This sounds like it is a result of javascript's same origin policy.
You will need to use techniques likes CORS or JSONp to get around this. The link above has more details.

Categories