AJAX call working from <body> but not from Javascript function - php

So the issue I'm currently having is that I'm trying to use an ajax call to send information to a php page to create an entry within a SQL database.
If I have the code within the tag. (So it's not within a function and it just calls on page load).
This is what is imported:
<script type="text/javascript" language="javascript" src="js/jquery.js"></script>
<script type="text/javascript" charset="utf-8" src="js/cordova.js"></script>
<link rel="stylesheet" href="jquery.mobile-1.3.0.css" />
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=visualization"></script>
<script type="text/javascript">
var pos = "(44.18974214877667,-79.63154019848633)";
var place = "test";
var check = "on";
var priv = "yes";
$.ajax({ type:"POST",
url:"backMap/locationCreation.php",
data: { name: place, loc: pos, check: check, privacy: priv },
success: function(data) { $("#awesomet").html(data);},
error: function(xhr, textStatus, thrownError, data) {
alert("Error: " + thrownError); }
});
</script>
When this is called upon page load it will run correctly and enter the information into the database. The issue is that I would like this to happen when a button is called so the information could be entered by the user.
<button onClick="sendCreationRequest()" />Submit</button>
<script type="text/javascript">
function sendCreationRequest() {
var place = $("#place").val();
var pos = targetted.getPosition();
var check = $("#checker").val();
var priv = $("#privOp").val();
$("#awesomet").html("GOT HERE.");
$.ajax({ type:"POST",
url:"backMap/locationCreation.php",
data: { name: place, loc: pos, check: check, privacy: priv },
success: function(data) { $("#awesomet").html(data);},
error: function(xhr, textStatus, thrownError, data) {
alert("Error: " + thrownError); }
});
}
</script>
So the Awesomet div will be changed to "GOT HERE." when a button is pressed that should activate the function so it is entering the function. I also had an alert going with all of the variables and they are correct.
When the button is clicked this is what comes up within the console:
CordovaLog - https://maps.gstatic.com/cat_js/intl/en_ca/mapfiles/api-3/13/4/%7Bmain,visualization%7D.js: Line 12 : Uncaught TypeError: Cannot call method 'lat' of undefined
Web Console - Uncaught TypeError: Cannot call method 'lat' of undefined:12.
I looked everywhere for some place that I was calling this but I couldn't find it.
I don't understand why it will work from a on page load call, and why it won't work from a function call.
EDIT: Targetted is a Google Maps Marker. When the call to get position is called. It returns just fine. I have put a alert(pos); within the code so when the button is pressed the alert does come up with the correct string.
EDIT: Okay, so I changed the:
var pos = targetted.getPosition();
to...
var pos = "(44.18974214877667,-79.63154019848633)";
The function call now works perfectly! However I don't understand why. They are getting the same numbers within the variable. Any ideas?

Just to answer my own question.
Thanks to bystwn22 and Mansimran Singh.
It appeared the issue was with the targetted.getPosition();
targetted was a Marker from Google Maps. It's getPosition() function returns something. When printing it out using an alert() it appeared to be the same.
It turns out it wasn't actually a String but some sort of json statement.
The fix turned out to be:
var pos = ""+targetted.getPosition();
Simple but it works.
Thanks everyone for the input!

Related

Unable to run jsvascript until page refresh

I've started using ajax requests recently. I am making a mobile web application where I am to the request for data on PHP side server script. The javascript function is to automatically execute when the user navigates to the page. But the script seems not to run until I refresh the page, here is my javascript code.
<script>
$( document ).ready(function(){
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString();
var dd = this.getDate().toString();
return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};
function requestContent() {
var date = new Date();
$.ajax({
type:'POST',
url:'php/app/adminTimeline.php',
data:{
date: date.yyyymmdd()
},
success: function(data) {
if (data == '') {
alert("No data found!");
} else {
// $("#loading_spinner").css({"display":"none"});
$('#timeline-content').prepend(data);
}
},
error: function(data) {
// $("#loading_spinner").css({"display":"none"});
alert("Something went Wrong!");
}
});
}
window.onload = requestContent();
});
</script>
The document.onready method and window.onload the method seems not to be working too.
Ps: I have the Jquery library linked in the header too.
Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.
https://learn.jquery.com/using-jquery-core/document-ready/
Also you're calling requestContent()
window.onload must be function, not returning value.
$(document).ready(function(){
// here you ajax
}
https://jsfiddle.net/cqfq5on5/1/
The code window.onload=requestContent(); will execute when the window loads, not necessarily when the entire document has loaded.
However where you create the date object, uses this, which executes after the document is fully loaded
$(document).ready(function(){
//Code
});
This means, that the POST request will be made once the window loads, which is before the document is fully loaded, thus, that date object will not exist until the page is refreshed, at which point the Javascript was likely cached. Also another answer (#sagid) pointed out, window.onload cannot be a returning value but must be a function.
i.e.
window.onload=function(){
//Code
};
This means, your solution is to change window.onload=requestContent(); to
$(document).ready(function(){
requestContent();
});
Good luck!

Refresh php embedded in html [duplicate]

What i want to do is, to show a message based on certain condition.
So, i will read the database after a given time continuously, and accordingly, show the message to the user.
But i want the message, to be updated only on a part of the page(lets say a DIV).
Any help would be appreciated !
Thanks !
This is possible using setInterval() and jQuery.load()
The below example will refresh a div with ID result with the content of another file every 5 seconds:
setInterval(function(){
$('#result').load('test.html');
}, 5000);
You need a ajax solution if you want to load data from your database and show it on your currently loaded page without page loading.
<script type="text/javascript" language="javascript" src=" JQUERY LIBRARY FILE PATH"></script>
<script type="text/javascript" language="javascript">
var init;
$(document).ready(function(){
init = window.setInterval('call()',5000);// 5000 is milisecond
});
function call(){
$.ajax({
url:'your server file name',
type:'post',
dataType:'html',
success:function(msg){
$('div#xyz').html(msg);// #xyz id of your div in which you want place result
},
error:function(){
alert('Error in loading...');
}
});
}
</script>
You can use setInterval if you want to make the request for content periodically and update the contents of your DIV with the AJAX response e.g.
setInterval(makeRequestAndPopulateDiv, "5000"); // 5 seconds
The setInterval() method will continue calling the function until clearInterval() is called.
If you are using a JS library you can update the DIV very easily e.g. in Prototype you can use replace on your div e.g.
$('yourDiv').replace('your new content');
I'm not suggesting that my method is the best, but what I generally do to deal with dynamic stuff that needs access to the database is the following method :
1- A server-side script that gets a message according to a given context, let's call it "contextmsg.php".
<?php
$ctx = intval($_POST["ctx"]);
$msg = getMessageFromDatabase($ctx); // get the message according to $ctx number
echo $msg;
?>
2- in your client-side page, with jquery :
var DIV_ID = "div-message";
var INTERVAL_IN_SECONDS = 5;
setInterval(function() {
updateMessage(currentContext)
}, INTERVAL_IN_SECONDS*1000);
function updateMessage(ctx) {
_e(DIV_ID).innerHTML = getMessage(ctx);
}
function getMessage(ctx) {
var msg = null;
$.ajax({
type: "post",
url: "contextmsg.php",
data: {
"ctx": ctx
},
success: function(data) {
msg = data.responseText;
},
dataType: "json"
});
return msg;
}
function _e(id) {
return document.getElementById(id);
}
Hope this helps :)

Simple ajax code not working?

<form>
<input type="text" id="user"/>
<input type="button" value="Submit" onClick="post();" />
</form>
<div id="result"> </div>
<script type="text/javascript">
function post()
{
var username = $('#user').val();
$.post('battlephp.php',
{postuser:user}
)
}
</script>
Its a simple Ajax code.. It should take username and display the Php code!
But don't know why its not running?? Actually I am learning...so I cant rectify the error or fault??
I am running ii on localhost.. so is there any problem with using:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
display the Php code
No, it shouldn't.
First, you've changed your mind about the variable name you are using (user, username) half way through your script, so you are going to throw a reference error.
Second, you haven't provided a function (the third argument) to $.post, so you aren't doing anything (such as displaying it) with the returned data.
Third, the server should execute the PHP and return its output. You shouldn't get the actual PHP code.
function post() {
var username = $('#user').val();
$.post(
'battlephp.php',
{postuser:username}, // Be consistent about your variable names
function (data) {
alert(data);
}
);
}
Instead
document.ready()
you can use
jQuery(function($){...});
Try to do this:
<script>
$(document).ready(function() {
function post() {
var username = $('#user').val();
$.ajax({
type : 'post',
url : 'batttlephp.php',
data : {
postuser : user
},
success : function(data) {
alert(data);
},
error : function(data) {
alert(data);
}
});
});
});
</script>
if you're doing a ajax request then is good also handle success and error...
Also I suggest to you "to start the document".
Try the code above and let us know if worked

javascript based Jquery ajax function, unable to send post values

Hello this is code snippet which i get from Jquery Ajax based search
I am done with everything, just the problem is the following script may not be sending the POST variable and its values or may be i am not properly fetching it.
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(document).ready(function() {
$("input[name='search_user_submit']").click(function() {
var cv = $('#newInput').val();
var cvtwo = $('input[name="search_option"]:checked').val();
var data = 'cv=' + cv + '&cvtwo=' + cvtwo; // sending two variables
$("#SearchResult").html('<img src="../../involve/images/elements/loading.gif"/>').show();
var url = "elements/search-user.php";
$.post(url, {
contentVar: data
}, function(data) {
$("#SearchResult").html(data).show();
});
});
});
});//]]>
</script>
In php file i have the following code:-
if (isset($_POST['cv']))
{
// My Conditions
}
else
{
// Show error
}
And its showing error, This means everything is correct just the post is not working properly, maybe.
Do the var data = 'cv=' + cv + '&cvtwo=' + cvtwo; // sending two variables will do the needful or we need to do any modifications. I know questions like this really annoy people, but what should i do i am stuck up.. #userD has really helped me a lot just, this part is left.
Since you're using $.post instead of $.ajax, your call should be:
$.post(url, data, function(response) {
/// ...
});
data must be a Javascript object, like this:
data = { "cv" : cv, "cvtwo" : cvtwo };
Check Jquery's documentation for more info:
http://docs.jquery.com/API/1.1/AJAX#.24.post.28_url.2C_params.2C_callback_.29

problem passing variable to php file

I really dont know why this isnt working!
<script src="js/jquery.js" type="text/javascript" language="javascript"></script>
<script type="text/javascript">
function updateVAL()
{
var f = document.getElementById("nu");
var val=f.value;
alert(val); // it displays the value properly
$.post("getDATA.php", {id: val}); // I sent the variable with jquery
}
</script>
getDATA.php
$value=$_POST['id'];
echo $value;
and when I access getDATA.php to see if it was sent I get this:
Notice: Undefined index: id in C:\Users\dan...
why the variable 'id' isnt set ? why is isnt passed to the server ?
Any help would be appreciated :)
Cheers,
dan.
Parameters are being sent via ajax - so this js script calls getDATA.php and $_POST['id'] is "seen" there only at that time.
And you are trying to access getDATA.php after and send no post or get parameters by your briwser - so you don't see this params there.
You have to catch echo by your js script. Look at this demo:
$.post("test.php", { name: "John", time: "2pm" },
function(data) {
alert("Data Loaded: " + data);
});

Categories