javascript value is undefined from php function - javascript

This probably has some really obvious answer that I'm missing, but I just can't seem to figure it out. All the search functions from PHP and queries work. The only thing that doesn't work is that the data isn't being displayed properly in the text area translated. Below is the code.
document.getElementById("translated").innerHTML = xmlhttp.open("GET","ajax-result.php?result="+num,true);
After the innerHTML portion, whatever I add (from text to html) goes into the right place but right now the above code says it is undefined.

xmlhttp.open does not return anything - that's why you get "undefined". Read http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp , paying particular attention to
xmlhttp.onreadystatechange part.
Far more convenient way to do this is to use jquery ajax method: http://api.jquery.com/jQuery.ajax/

That's not how ajax works. You should have a callback function to be called when server responses
Something like
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
// setup callback function
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
if(xmlhttp.responseText == 1){
document.getElementById("translated").innerHTML = xmlhttp.responseText;
}
}
}
xmlhttp.open("GET",'your request to sever',true);

If you really want to save yourself some head ache, I'd familiarize yourself with jQuery.
Here is a full working example of what it appears it is you are attempting to accomplish.
The implementation of the input and button was simply to simulate the method in which a value is being specified and the function is being called.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<body>
<script type="text/javascript">
function runAjax(num) {
$.ajax({
'url': 'ajax-result.php',
'type': 'GET', // Can also be 'POST'
'data': {
'result': num
},
'success': function(result) {
$('#translated').html(result);
alert('success!');
},
'error': function(xhr, status, exception) {
alert('failed with status code: ' + status);
}
});
}
$(document).ready(function() {
$('button').click(function() {
var $input = $('input');
var num = $input.val();
runAjax(num);
});
});
</script>
<input type="text" name="num" value="123" />
<button type="button">Click Me!</button>
</body>
</html>

Related

Redirect URL based on JSON callback data

I tried to use JavaScript to redirect visitors by country
The following call checks the IP of the country by visitor e.g. CN (China) and redirects it to an other web site.
<script async src="https://get.geojs.io/v1/ip/country.js"></script>
<script type="application/javascript">
function geoip(json) {
var countrycode.textContent = json.country;
}
if (countrycode.textContent == "CN") {
window.location = "http://baido.com"
}
</script>
Any help?
I see that there is an answer marked solved, however I still couldn't get that to work. So I created this, just in case you want to go in another direction:
function geoip() {
$.ajax({
type: 'get',
url: 'https://get.geojs.io/v1/ip/country.json',
success: function(data) {
if (data['country'] == "CN") {
window.location = "https://baido.com/";
}
}
});
}
geoip();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
The problem is that you are not using the example code properly. The countrycode.textContent part is supposed to show the user's country code on the browser which means it would not work for your use case since you are trying to redirected.
Also note that the geoip function is used by the script you loaded from geojs so if you are trying to redirect, you should do that in that function.
Here is the updated code that works.
<script type="application/javascript">
function geoip(json){
if (json.country_code == "CN") {
window.location = "http://baido.com/";
}
}
</script>
<script async src="https://get.geojs.io/v1/ip/geo.js"></script>

How to temporarily disable a button within an Ajax call?

In my Javascript code, I wrote an Ajax call where a couple of for loop cycles call two JSON files; some functions are called when some events occur and a Search button is clicked: tables containing data from the APIs requests are displayed.
I want to temporarily disable the Search button when these data are looked for within the Ajax calls, and then enable it again once the operation was carried out, in a way similar to what happens in the setTimeout() Method, but without having to set a number of milliseconds (I cannot specify it previously for the number of milliseconds depends on the slowness of the internet connection and other factors...).
How to set the .prop("disabled", false); temporarily within a callback function? In other terms, how to temporarily disable a button within an Ajax call?
You can make use of beforeSend and complete for this,
$.ajax({
type: 'POST',
url: url,
data: data,
beforeSend: function() {
// disable your button here
.prop("disabled", true);
},
success: function(data) {
//success
},
error: function(xhr) { // if error occured
},
complete: function() {
// enable your button here
.prop("disabled", false);
}
});
inject the object instance into the event handlers.
Checkout the possible event handlers here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Monitoring_progress
instead of Console.log call our object.prop("disabled",false") there
using JavaScript Fetch API
<!DOCTYPE html>
<html>
<body>
<div>
<button type="button" id="btn1" onclick="loadData()">Change Content</button>
<div id="response">
</div>
</div>
<script>
function loadData() {
document.getElementById("btn1").disabled = true;
fetch("https://jsonplaceholder.typicode.com/todos/1")
.then((resp) => resp.text()) // Transform the response into text
.then((data) => {
document.getElementById("response").innerHTML =
data;
document.getElementById("btn1").disabled = false;
});
}
</script>
</body>
</html>
using plain old javascript
<!DOCTYPE html>
<html>
<body>
<div>
<button type="button" id="btn1" onclick="loadData()">Change Content</button>
<div id="response">
</div>
</div>
<script>
function loadData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.status == 200) {
document.getElementById("response").innerHTML =
this.responseText;
}
document.getElementById("btn1").disabled = false;
};
xhttp.open("GET", "https://jsonplaceholder.typicode.com/todos/1", true);
xhttp.send();
document.getElementById("btn1").disabled = true;
document.getElementById("response").innerHTML = '';
}
</script>
</body>
</html>

Unable to submit form with ajax without reloading parent

I am building a web application that will create a div on the page, use ajax to load a form into that div, and then have the form submitted without the parent page refreshing. I've read many examples on this site and others of how to do this, yet I'm puzzled why my proof-of-concept test is not working for me.
What successfully happens is that the parent page is creating the new div and is loading the form into the div. However, upon submitting the form, the parent page reloads. Using "Live HTTP Headers" in Opera, I can see that submitting the form is causing a GET rather than a POST, even though my Javascript is attempting to POST.
Can anyone help me understand why this is happening? Any help is very much appreciated.
Here is the code to the parent HTML page:
<html>
<head>
<script src=\"jquery-1.11.1.min.js\"></script>
<script src=\"jquery.min.js\"></script>
<script type=\"text/javascript\">
var num=1;
console.log('starting the code');
$(document).ready(function() {
console.log('document is ready');
$('#form1').submit(function(event) { // catch the form's submit event
console.log('form is going through submit');
$.ajax({ // create an AJAX call...
url: 'add_user.php', // the file to call
type: 'POST', // GET or POST
data: $('#form1').serialize(), // get the form data
success: function(data) { // on success..
$('#assign1').html(data); // update the DIV
},
error: function(xhr, status, e) {
console.log('status');
console.log('e');
}
});
event.preventDefault(); // cancel original event to prevent form submitting
});
});
function addToBox(divID) {
console.log('adding new assign to box');
var myNewDiv = document.createElement(\"div\");
myNewDivID = 'assign'+num;
myNewDiv.setAttribute('id', myNewDivID);
myNewDivID = '#'+myNewDivID;
var myBox = document.getElementById(divID);
myBox.appendChild(myNewDiv);
$.ajax({
type: 'GET',
url: 'add_user.php?id=1',
success: function(data) {
$(myNewDivID).html(data);
},
error: function(xhr, status, e) {
console.log('status');
console.log('e');
}
});
num+=1;
}
</script>
</head>
<body>
<div>
<div id=\"box1\"></div>
<img src=\"/icons/add.png\" alt=\"Create new box\" />
</div>
<div>
<div id=\"box2\"></div>
<img src=\"/icons/add.png\" alt=\"Create new box\" />
</div>
</body>
</html>
Here is the code to the PHP page (named add_user.php) with the form.
<?php
$n=0;
$id=$_GET['id'];
if ($_SERVER['REQUEST_METHOD']=="POST") {
echo "got the form!";
} else {
echo "<form id=\"form{$id}\"><select name=\"quantity\">\n";
for ($n=1;$n<=5;$n++) {
echo "<option value=\"answer{$n}\">option {$n}</option>\n";
}
echo "</select>\n<input type=\"submit\" /></form>";
}
?>
Thanks to the comment by A. Wolff, I replaced $('#form1').submit(function(event) { with $(document).on('submit','#form1', function(event){ and it worked.
Thanks A. Wolff!

How to send a GET Request using Jquery?

Trying to send a simple Jquery GET request, which doesn't work.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#clk").click(function() {
$.get('http://www.abelski.com/courses/ajax/emailajaxservice.php', { email: 'mymail#example.com'}, function() {
alert("Sent");
});
});
});
</script>
</head>
<body>
<input type="text" id="email" />
<input type="button" id="clk" />
<span id="res"></span>
</body>
</html>
http://www.abelski.com/courses/ajax/emailajaxservice.php is on.
I don't get any alert. what is the problem in my code?
Why don't you try this one:
$.ajax({
type: "GET",
url: RequestURL,
dataType: "html",
success: function(htm) {
alert(htm);
}
}
});
In your code snippet, the function
function() { alert("Sent"); }
will be called when the request succeeds. If it fails for any reason (cross-domain requests are forbidden, answer returns with a non OK code, ...) nothing will be executed.
You can add a .fail() listener to see if an error was triggered :
$.get( ... ).fail(function(){ alert("Error"); });
Check your web console to have more detail on the failure.

confirm choice in php page using javascript

I'm trying to confirm deleting something, but I can't seem to get it to work.
When the button for 'deleteReply' I'm getting an alert message, but as far as I can tell nothing else is happening. I'm trying to simply echo the posted variable but it doesn't seem to work.
<input type="button" id="deleteSomething" value="Delete" />
<script type="text/javascript">
$(document).ready(function(){
$('#deleteSomething').click(function() {
if (!confirm("Are you sure?"))
return false;
$.post('deleteProcessing.php', "replyID=" + replyID, function(response) {
alert(response);
});
});
});
</script>
On my delete processing page I just have
$echo $_POST['replyID'];
Why do you have
if(isset($_POST['deleteReply'])){
?>
Before the javascript function? Did you expect to trigger the javascript code based on the $_POST['deleteReply'] var?
You have to keep in mind that php is processed server-side and outputs an HTML page. Your javascript code will only run in the client after all the php has run.
A much more elegant solution would be asking for a confirmation BEFORE sending the AJAX request.
And also, your ajax call doesn't seem to do what you're expecting. You're manually setting 2 parameters to send to your PHP which will have no use for it if you do the confirmation server-side.
A parameter should be something like the Reply ID of the reply you want to delete, and send the request to a different php file for handling.
I'd suggest you rewrite your code as Marian Zburlea is doing for you.
EDIT
Ok, if you want a simple confirm window, try this:
<input type="button" id="deleteSomething" value="Delete" />
<script type="text/javascript">
$(document).ready(function(){
$('#deleteSomething').click(function() {
if (!confirm("Are you sure?"))
return false;
$.post('delete.php', "replyID=" + replyID, function(response) {
alert(response);
});
});
});
</script>
EDIT
If you have multiple delete buttons, the best way to do this would be storing the replyID as the parameter to pass to your function. Echo your delete buttons in your php like this:
echo '<input type="button" value="Delete" onclick="deleteSomething(\'' . $replyID . '\')" />';
This way, the $replyID will be stored in the page's HTML, which will be passed to the deleteSomething(replyID) function which you now have to define (preferably in the document's head after the JQuery lib):
<script type="text/javascript">
function deleteSomething(replyID)
{
if (!confirm("Are you sure?"))
return false;
$.post('deleteProcessing.php', "replyID=" + replyID, function(response) {
alert(response);
});
}
</script>
Note that I removed the ID from the buttons to don't generate dupplicate IDs and they are no longer needed, as I've added a function call in the onclick event instead of binding an anonymous function to their IDs as you were doing previously.
<input type="button" id="deleteSomething" value="Delete" />
<div id="yesno" style="display:none;">
<input type="button" id="buttonYes" value="Yes" />
<input type="button" id="buttonNo" value="No" />
</div>
<script type="text/javascript">
// Here you attach a click event to the button Yes with id buttonYes
$('#deleteSomething').click(function() {
$('#yesno').css('display', 'block');
});
$('#buttonNo').click(function() {
$('#yesno').css('display', 'none');
});
$('#buttonYes').click(function() {
$.ajax({
beforeSend: function(e) {
// Code to process before calling AJAX
},
url: "pathToPHPFile.php",
dataType: "json",
type: "POST",
data: {
parameter: 'Yes',
},
success: function (m) {
console.log(m);
alert(m.text);
},
error: function (e) {
console.log("Something went wrong ...: "+e.message);
},
}); /* end ajax*/
e.preventDefault();
});
</script>
<?php
// This is a separate php file named pathToPHPFile.php
if(isset($_POST['parameter']) && $_POST['parameter'] == 'Yes'){
/* here you put the code that deletes the message */
$response['text'] = 'messageDeleted'
echo json_encode($response);
}

Categories

Resources