Passing value correctly to PHP from AJAX Code - php

So I'm trying to pass a value from my AJAX code to my PHP code which connects to an API to get the weather. It works when just using PHP, but I want ajax to return the results to some div on the same page. My code looks correct when I compare it to other examples but it just doesn't work.
Code may not be written with security in mind, standard practice etc, I'm just trying to play around with API's and get the basics of AJAX.
api.php:
$city = $_POST['city'];
function getCityLat($x) {
$latUrl = 'https://maps.googleapis.com/maps/api/geocode/json?address='. $x .'APIKEY';
$latResponse = file_get_contents($latUrl);
$latArray = json_decode($latResponse, true);
$lat = $latArray['results'][0]['geometry']['location']['lat'];
echo $lat;
return $lat;
}
function getCityLng($y) {
$lngUrl = 'https://maps.googleapis.com/maps/api/geocode/json?address='. $y .'APIKEY';
$lngResponse = file_get_contents($lngUrl);
$lngArray = json_decode($lngResponse, true);
$lng = $lngArray['results'][0]['geometry']['location']['lng'];
echo $lng;
return $lng;
}
function getWeather($x, $y) {
$weatherUrl = 'https://api.darksky.net/forecast/APIKEY/' . $x . ',' . $y;
$weatherResponse = file_get_contents($weatherUrl);
$weatherArray = json_decode($weatherResponse, true);
$timeZone = $weatherArray['timezone'];
$locWeather = $weatherArray['currently']['temperature'];
$locFeelsLike = $weatherArray['currently']['apparentTemperature'];
$windSpeed = $weatherArray['currently']['windSpeed'];
$weatherSummary = $weatherArray['currently']['summary'];
$time = $weatherArray['currently']['time'];
$outputweather = '<p>Temp: '.$locWeather.'</p>';
echo $outputweather;
}
getWeather(getCityLat($city), getCityLng($city));
?>
index.php(html):
<h3 align="center">Weather</h3>
<form align="center" method="POST">
<input type="text" id="city" name="city" placeholder="Enter City">
<button class="btn btn-xs btn-success" name="city_go" id="city_go">Go</button>
</form>
<div id="weather"></div>
JQuery:
function getWeather(city) {
$.ajax({
url: "api.php",
method: "POST",
data: {city:city},
dataType: "text",
success: function(data) {
$('#weather').html(data);
}
});
}
$(document).on('click', '#city_go', function() {
var city = $('#city').val();
getWeather(city);
});

The problem is that you are submitting a form, which forces a page refresh. Everything else is working correctly, just the page is being refreshed. To fix that you need to update your click event to something like
$(document).on('click', '#city_go', function(e) {
e.preventDefault();
var city = $('#city').val();
getWeather(city);
});
the preventDefault() call will cancel the default action of the form (the page refresh) and allow the AJAX call to follow through and display the data.

Related

AJAX Form Submission Not Querying PHP

Trying to use AJAX to submit form data to a PHP file. Everything in the code seems to work except for a call to the PHP file.
I setup a Java Alert() on the PHP file and it never alerts.
I am sure it is an issue with the AJAX code but I don't know it well enough to figure out what is going wrong.
The AJAX Call:
$(document).on('click','.addItem',function(){
// Add Item To Merchant
var el = this;
var id = this.id;
var splitid = id.split("_");
// Add id's
var addid = splitid[1]; // Merchant ID
var additem = splitid[2]; // Item ID
// AJAX Request
$.ajax({
url: "jquery/addItem.php",
type: "POST",
data: { mid : addid , iit : additem },
success: function(response){
// Removing row from HTML Table
$(el).closest('tr').css('background','tomato');
$(el).closest('tr').fadeOut(300, function(){
$(this).remove();
});
}
});
});
The HTML Form Call Within a Table:
<span class='addItem' id='addItem_<?php echo $m; ?>_<?php echo $list['id']; ?>' >Add Item</span>
Ok Simple PHP code that it calls to with some alerts for testing:
<?php
require_once("../includes/constants.php");
require_once("../includes/functions.php");
$iid = filter_input(INPUT_POST, 'iit', FILTER_SANITIZE_STRING); // Item ID
$mid = filter_input(INPUT_POST, 'mid', FILTER_SANITIZE_STRING); // Merchant ID
$slot = 0;
$slot = getMerchSlot($mid);
?>
<script>
alert ("Slot Value: <?php echo $slot; ?>");
</script>
<?php
$result = $pdoConn->query("INSERT INTO merchantlist (merchantid, item, slot)
VALUES
('$mid', '$iid', '$slot') ");
if ($result) {
?>
<script>
alert("Looks like it worked");
</script>
<?php
}
echo 1;
?>

submit form php without refresh page

I'm working on a PHP application i want to submit form without refresh page. Actually, i want my php code to be written on the same page as the one containing html and jquery code.
In order to submit form using jquery i've written this code
$(document).ready(function(){
$("#btn").click(function(){
var vname = $("#selectrefuser").val();
$.post("php-opt.php", //Required URL of the page on server
{ // Data Sending With Request To Server
selectrefuser:vname,
},
function(response,status){ // Required Callback Function
//alert("*----Received Data----*\n\nResponse : " + response+"\n\nStatus : " + status);//"response" receives - whatever written in echo of above PHP script.
});
php_lat = <?php echo $resclient_alt; ?>;
php_long = <?php echo $resclient_long; ?>;
var chicago = new google.maps.LatLng(parseFloat(php_lat), parseFloat(php_long));
addMarker(chicago);
//return false;
//e.preventDefault();
//$("#monbutton:hidden").trigger('click');
});
});
and my php code is :
<?php
$resclient_alt = 1;
$resclient_long = 1;
if(isset($_POST['selectrefuser'])){
$client = $_POST['selectrefuser'];
echo $client;
$client_valide = mysql_real_escape_string($client);
$dbprotect = mysql_connect("localhost", "root", "") ;
$query_alt= "SELECT altitude FROM importation_client WHERE nom_client='$client_valide' ";
$query_resclient1_alt=mysql_query($query_alt, $dbprotect);
$row_ss_alt = mysql_fetch_row($query_resclient1_alt);
$resclient_alt = $row_ss_alt[0];
//echo $resclient_alt;
$query_gps= "SELECT longitude FROM importation_client WHERE nom_client='$client_valide' ";
$query_resclient1=mysql_query($query_gps, $dbprotect);
$row_ss_ad = mysql_fetch_row($query_resclient1);
$resclient_long = $row_ss_ad[0];
}
?>
My form is as below
<form id="form1" name="form1" method="post" >
<label>
<select name="selectrefuser" id="selectrefuser">
<?php
$array1_refuser = array();
while (list($key,$value) = each($array_facture_client_refuser)) {
$array1_refuser[$key] = $value;
?>
<option value="0" selected="selected"></option>
<option value="<?php echo $value["client"];?>"> <?php echo $value["client"];?></option>
<?php
}
?>
</select>
</label>
<button id="btn">Send Data</button>
</form>
My code does these actions:
select client get its GPS coordinates
recuperates them in php variable
use them as jquery variable
display marquer on map
So since i do this steps for many clients i don't want my page to refresh.
When i add return false or e.preventDefault the marquer is not displayed, when i remove it the page refresh i can get my marquer but i'll lost it when selecting another client.
is there a way to do this ?
EDIT
I've tried using this code, php_query.php is my current page , but the page still refresh.
$("#btn").click(function(){
var vname = $("#selectrefuser").val();
var data = 'start_date=' + vname;
var update_div = $('#update_div');
$.ajax({
type: 'GET',
url: 'php_query.php',
data: data,
success:function(html){
update_div.html(html);
}
});
Edit
When adding e.preventDfault , this code doesn't seem to work
$( "#monbutton" ).click(function() {
php_lat = <?php echo $resclient_alt; ?>;
php_long = <?php echo $resclient_long; ?>;
$('#myResults').html("je suis "+php_long);
var chicago = new google.maps.LatLng(parseFloat(php_lat), parseFloat(php_long));
addMarker(chicago);
});
This code recuperate this value var vname = $("#selectrefuser").val(); get result from sql query and return it to jquery .
It will refresh since you have not prvent default action of <button> in script
$("#btn").click(function(e){ //pass event
e.preventDefault(); //this will prevent from refresh
var vname = $("#selectrefuser").val();
var data = 'start_date=' + vname;
var update_div = $('#update_div');
$.ajax({
type: 'GET',
url: 'php_query.php',
data: data,
success:function(html){
update_div.html(html);
}
});
Updated
Actually, i want my php code to be written on the same page as the one containing html and jquery code
You can detect the ajax call on php using below snippet
/* AJAX check */
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
/* special code here */
}

How to mesh codeigniter with ajax

I am trying to implement a ajax plus one button with my site in code igniter. I am very new with Ajax and codeigniter so I'm needing some guidance.
Here is the portion of my controller where I'm starting. Please note, this is inside the method that creates my profile view in which I'm trying to create this.
$voteId= $this->input->post('voteId');
$upOrDown= $this->input->post('upOrDown');
$status ="false";
$updateRecords = 0;
if($upOrDown=='upvote'){
$updateRecords = $this->community_model->updateUpVote($voteId);
}else{
$updateRecords = $this->community_model->updateUpVote($voteId);
}
if($updateRecords>0){
$status = "true";
}
echo $status;
// This variable will be accessed from the view
$data['airwave'] = $airwave;
$data['profile_id'] = $profile_id;
$this->load->view('includes/templates/main_page_template', $data);
}
Here is the method in the model:
function updateUpVote($voteId){
$sql = "UPDATE airwaves_comments set thumbsup = thumbsup+1 WHERE thumbsup =?";
$this->db->query($sql, array($voteId));
return $this->db->affected_rows();
}
here is my view:
<div id='thumb_holder'>
<div id='thumb_report'>
<a href='mailto:info#cysticlife.org'>
&#149 report
</a>
</div>
<div class= 'thumb_counter'>
+0
</div>
<div id='thumb_thumb'>
<a class='myButtonLink voteMe' id='1_upvote'<span id="1_upvote_result">+</span>></a>
</div>
</div>
here is the script:
<script>
$(document).ready(function(){
$(".voteMe").click(function() {
var voteId = this.id;
var upOrDown = voteId.split('_');
$.ajax({
type: "post",
url: "account/profile/voteMe",
cache: false,
data:'voteId='+upOrDown[0] + '&upOrDown=' +upOrDown[1],
success: function(response){
try{
if(response=='true'){
var newValue = parseInt($("#"+voteId+'_result').text()) + 1;
$("#"+voteId+'_result').html(newValue);
}else{
alert('Sorry Unable to update..');
}
}catch(e) {
alert('Exception while request..');
}
},
error: function(){
alert('Error while request..');
}
});
});
});
</script>
additionally here is what it looks like to give a better idea of what's going on, but I want there to be the number of votes after the plus sign:
To summarize: Essentially I was taking a tutorial on a demo tutorial that is similar, but it was not exactly what I am trying to do. This is basically me taking the code from the tutorial and trying to splice it with my code and meet my specific needs and learning ajax at the same time. I feel like I'm close as it's updating the specified column in my table (incorrectly),however can't get it to visibly function.
I'm not exactly sure what your saying your problem is. But This I do see.
When trying to fetch a view for ajax you have to return the view as data
http://ellislab.com/codeigniter/user-guide/general/views.html (bottom of the page)
Like this
$view = $this->load->view('includes/templates/main_page_template', $data, true);
echo $view;
This will send the rendered view to the browser
Put this code in view file
<input type="hidden" name="siteurl" id="siteurl" value="<?php echo site_url(); ?>">
<input type="hidden" name="baseurl" id="baseurl" value="<?php echo base_url(); ?>">
Then get hidden value in your script
var site_path = $("#siteurl").val();
var base_path = $("#baseurl").val();
$.ajax({
type: "post",
url: site_path+"account/profile/voteMe",....

match() function and match variables

now i have a text-input and a php variables.
$price = 200;
<input type="text" name="promotion_code">
after users type in value of 'promotion_code' , without submit button , or any links.
it's can match 'promotion_code' between javascript on that pages.
lets say the javascript :
var str="123203";
so i want match the 'promotion_code' with 'var str' .
if match then $price = $price - 10;
if not match then $price value doesn't change ..
any could helps or any methods to solve this ?
note :!! to be told. this form did not have a submit button .. the compare process should be works in time when the user input the promotion_code
You should not do that with JavaScript, it is no secure enough.
Anyone can view your JavaScript code by looking at the source of your page.
Try to make it with an ajax request.
jQuery.ajax({
type : "post",
url : "request.php",
data : "code=" +jQuery("input[name=promotion_code]").val(),
success : function(ret){
jQuery("#price").text(ret);
}
});
Here you call the page request.php with the value code
Here what can be request.php :
$price = 200;
$code = $_POST["code"];
if( $code == "123203" ){
$price -= 10;
}
return $price;
Then you update the price field with the data returned by the request.php page.
You have to adapt that code of course.
I hope this can help.
Make sure to do that on the server since anyone can see the code in the source of the page. Also $price is on the server and the client value is not available to the server until you send a request back to the server using for example AJAX
So something like
<form action="purchase.php" id="form1">
Promotion code: <input type="text" name="promotion_code" id="prCode" />
<input type="button" id="prCodeBut" value="Apply" />
Price: <input type="text" readonly="readonly"
name="finalprice" id="fPrice" value="<?PHP echo $price; ?>" />
</form>
JavaScript
DEMO 1 - using click
var orgPrice = <?PHP echo $price; ?>;
window.onload=function() {
document.getElementById("prCodeBut").onclick=function(){
// hardcoding the promocode is NOT recommended
if (document.getElementById("prCode").value == "<?php echo $promocode; ?>") {
document.getElementById("fPrice").value=orgPrice-10;
}
}
}
DEMO 2 using onkeyup
var orgPrice = <?PHP echo $price; ?>;
window.onload=function() {
document.getElementById("prCode").onkeyup=function(){
// hardcoding the promocode is NOT recommended
if (document.getElementById("prCode").value == "<?php echo $promocode; ?>") {
document.getElementById("fPrice").value=orgPrice-10;
}
}
}
DEMO 3 using onblur
var orgPrice = <?PHP echo $price; ?>;
window.onload=function() {
document.getElementById("prCode").onblur=function(){
// hardcoding the promocode is NOT recommended
if (document.getElementById("prCode").value == "<?php echo $promocode; ?>") {
document.getElementById("fPrice").value=orgPrice-10;
}
}
}
Ajax to hide the promocode
// delay from http://stackoverflow.com/a/1909508/295783
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
$(function() {
$("#prCodeBut").on("keyup",function() {
delay(function() {
$.get("checkPromo.php",{promotion: $("#prCode").val()},function(data) {
$("#fPrice").val(data);
});
},300);
});
});

PHP/JS: Posting input value with js function and echoing through php

My goal is to have input field that will take value of whats was typed and echoed through. The js function will grab the value of the input box two seconds after user stops typing and post it. The issue seems to be with the php not echoing the value of the input box. When I take out the js function and use a button that forces refresh then
it works fine. How come php is not taking the value posted by js function?
Example SITE
JS
<script type="text/javascript">
$(document).ready(function() {
var timer;
$('#video-input1').on('keyup', function() {
var value = this.value;
clearTimeout(timer);
timer = setTimeout(function() {
//do your submit here
$("#ytVideo").submit()
//alert('submitted:' + value);
}, 2000);
});
//then include your submit definition. What you want to do once submit is executed
$('#ytVideo').submit(function(e){
e.preventDefault(); //prevent page refresh
var form = $('#ytVideo').serialize();
//submit.php is the page where you submit your form
$.post('index.php', form, function(data){
});
return false;
});
});
</script>
PHP
<?php
if($_POST)
{
$url = $_POST['yurl'];
function getYoutubeVideoID($url) {
$formatted_url = preg_replace('~https?://(?:[0-9A-Z-]+\.)?(?:youtu\.be/| youtube\.com\S*[^\w\-\s])([\w\-]{11})
(?=[^\w\-]|$)(?![?=&+%\w]*(?:[\'"][^<>]*>| </a>))[?=&+%\w-]*~ix','http://www.youtube.com/watch?v=$1',$url);
return $formatted_url;
}
$formatted_url = getYoutubeVideoID($url);
$parsed_url = parse_url($formatted_url);
parse_str($parsed_url['query'], $parsed_query_string);
$v = $parsed_query_string['v'];
$hth = 300; //$_POST['yheight'];
$wdth = 500; //$_POST['ywidth'];
$is_auto = 0;
//Iframe code with optional autoplay
echo htmlentities ('<iframe src="http://www.youtube.com/embed/'.$v.'" frameborder="0" width="'.$wdth.'" height="'.$hth.'"></iframe>');
}
?>
form
<html>
<form method="post" id="ytVideo" action="">
Youtube URL: <input id="video-input1" type="text" value="<?php $url ?>" name="yurl">
<input type="submit" value="Generate Embed Code" name="ysubmit">
</form>
</html>
It's because you are not returning your php result anywhere. It's simply lost...
$.post('index.php', form, function(data){
var x = $(data);
$("body").html(x);
});

Categories