PHP/ Ajax/ jQuery - Equivalent for my code - javascript

I have the following code and would like to use jquery to make it simpler:
var auctionBidAjax;
function auctionBid(auction_id) {
auctionBidAjax=GetXmlHttpObject();
if (auctionBidAjax==null) {
alert ("Your browser does not support XMLHTTP!");
return;
}
var url="/cms/ajax/auctionBid.php?auction_id="+auction_id;
auctionBidAjax.onreadystatechange=function() { auctionBidReady(auction_id); };
auctionBidAjax.open("GET",url,true);
auctionBidAjax.send(null);
}
And...
function auctionBidReady(auction_id) {
if (auctionBidAjax.readyState==4) {
if (auctionBidAjax.responseText == "Bid Placed") {
document.getElementById('auctionBid' + auction_id).innerHTML=
"Place Bid";
userBids();
} else if (auctionBidAjax.responseText == "Not Logged In") {
popupCentre('popupLogin');
popupLoad('popupLogin');
} else if (auctionBidAjax.responseText == "No Bids"){
popupCentre('popupNoBids');
popupLoad('popupNoBids');
}
}
}
My PHP script adds a bid etc and echos the responseText.

You've tagged this question as jquery so you can use $.ajax():
function auctionBid(auction_id) {
$.ajax({
url: "/cms/ajax/auctionBid.php",
type: "GET",
data: {
auction_id: auction_id
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// act appropriately
},
success: function(data, textStatus) {
// do whatever
}
});
}
If you didn't need an error handler you could use the simpler form of $.get() instead:
function auctionBid(auction_id) {
var url = "/cms/ajax/auctionBid.php";
$.get(url, { auction_id: auction_id }, function(data, textStatus) {
// do whatever
});
}
I actually prefer not to use error handlers. It's a little uglier than it needs to be. Use that for actual errors. Things like "not logged in" could be handled by the success handler. Just pass back a JSON object that contains the required information to tell the user what happened.
For this you could use the $.getJSON() shorthand version.
function auctionBid(auction_id) {
var url = "/cms/ajax/auctionBid.php";
$.getJSON(url, { auction_id: auction_id }, function(data) {
if (data.notLoggedIn) {
alert("Not logged in");
}
...
});
}
To return some information as JSON from PHP use json_encode() and set the MIME type appropriately:
<?php
session_start();
header('Content-Type: application/json');
echo json_encode(array(
'highBid' => get_new_high_bid(),
'loggedIn' => $_SESSION['loggedIn'],
));
exit;
?>
I'm making assumptions about your login system so the above is a gross simplification.
Return that to a $.getJSON() callback and you should be able to do:
alert(data.highBid);
alert(data.loggedIn);

JQuery.get is what you need
http://docs.jquery.com/Ajax/jQuery.get

Related

Updating an input field with PHP vale in JavaScript

I want to update the value of an input field when I receive some information from an api. I tried using:
$('#txtFirstName').val($_SESSION['jUser']['first_name']);
But an error occurs due to the PHP not being able to run in a js file. How can I make this update otherwise? Is there a way in js to update the entire form and input fields without submitting?
I can't reload the entire window, because it will eliminate other information that the user of the website has put in.
1) put value into #txtFirstName from php script
// script.php code
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
echo $_SESSION['jUser']['first_name'];
}
// javascript code
function func(){
$.ajax({
type: "POST",
url: "script.php",
success: function (response) {
$('#txtFirstName').val(response);
},
error: function (e) {
console.log("ERROR : ", e);
}
});
}
2) put value into $_SESSION['jUser']['first_name'] from javascript
// javascript code
function func(){
var your_value = "some_value";
$.ajax({
type: "POST",
url: "script.php",
data: { va: your_value },
success: function (response) {
console.log("value setted to session successfully");
},
error: function (e) {
console.log("ERROR : ", e);
}
});
}
// script.php code
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_POST['va'] !='') {
$_SESSION['jUser']['first_name'] = $_POST['va'];
echo "ok";
}
Why don't you just echo the value from php script and make an AJAX request from javascript to get the value ? This should be the recommended approach.
However, it can also be accomplished with the approach you've taken:
let first_name = <?php echo $_SESSION['jUser']['first_name']; ?>:
$('#txtFirstName').val(first_name);
For further reading, you can visit How do I embed PHP code in JavaScript?
.

Only do things if input-text is a domain like example.com

I would like to perform a whois-query if a user enters a valid domain. This query should be done using AJAX.
This script calls function checkDomain() always if the user types something into the form field:
js = jQuery.noConflict();
js(document).ready(function() {
jQuery('#jform_domain').keyup(function() {
checkDomain();
});
});
function checkDomain() {
var $this = jQuery(this);
jQuery.ajax({
url: '<?php echo JUri::root(); ?>/index.php',
dataType: 'json',
type: 'POST',
data: {
option: 'com_domaincheck',
format: 'json',
task: 'domain.checkDomain',
domain: jQuery("#jform_domain").val(),
'<?php echo JSession::getFormToken(); ?>': 1
},
success: function(response) {
if (response.success) {
console.log(response);
jQuery("#test").html(response.message);
// if (response.message == true) {} else {}
} else {
alert(response.message);
}
},
error: function(data) {
//console.log(data);
}
});
};
Now I would like to reduce unnecessary operations and start the script only, if the user entered a domain like:
example.com
It would be really, really, really cool, if the script would change inputs like www.example.com or http(s)://www.example.com to example.com aswell.
I'm a beginner in JS and jQuery, so please do not blame me for my bad knowledge - I try to learn ;-)
You need to use Regex for domain checking. I have used a basic regex, you can modify this regex or use another to suit your needs.
$(document).ready(function() {
$regExDomain = /^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}$/;
$('#domain_name').on('keyup', function(){
if($regExDomain.test($(this).val() ) ){
console.info("valid domain");
}else{
console.info("invalid domain");
return false;
}
console.log("Valid domain");
checkDomain();//domain is valid so call your ajax function
});
});

Post return values with AJAX?

I am using Code Igniter and I have the following Javascript function in my View. I have tried to echo values such as "error" from my handler function in the controller, but the "success" code is always ran in this function below instead.
Do I use echo or return to respond to the AJAX post? What value do I return for success and failure?
<script>
function removeDatacenter(id)
{
var cfm = confirm("Do you wish to delete this datacenter?");
if (cfm==true)
{
$.ajax({
type: "POST",
url: "<?=base_url()?>datacenters/remove_handler.php",
data: { id: id },
success: function(result)
{
document.location.href = document.URL + "?result=success";
},
error: function(result)
{
document.location.href = document.URL + "?result=failed";
}}
);
}
};
</script>
The success-method runs if the ajax-request was successfully sent to your script. It does not say anything about what the request returned.
If you simply do echo "error"; in your PHP-script, you can check the value in the success-method like this:
success: function(response) {
if (response == "error") {
document.location.href = document.URL + "?result=failed";
}
else {
document.location.href = document.URL + "?result=success";
}
}
Edit: People tend to use json_encode in the PHP-code and decode the json-string to an object in the javascript-code. That way you can send more structured data from your script.
Any text you echo will be seen, by AJAX, as a success. Even if it's the word "error". In order for you to trigger the Javascript error handler, you need to trigger some sort of actual HTTP error. If you're just trying to trigger an error for testing purposes, you could throw an exception in your controller. Or point the AJAX request to a URL that doesn't exist on your server (then you'd get a 404 error).
By the way, the error callback you have in your Javascript is slightly off on the API. It might not matter depending on what you do in the error handler, but here's the full call:
error: function(xmlHttpRequest, textStatus, errorThrown) {
//handle error here
}

jQuery - POSTing with JSON and receiving both JSON and HTML

I have an HTML page, that posts JSON information to the server.
If the server thinks there is an error with the information posted, it returns a JSON string so that the client can modify the current HTML page with an error message.
Otherwise, the server returns a new HTML page.
How can I handle this in jQuery?
Well, then you can put the html page content into a json variable and still return it as a json. In that way you would be still following practice.
Example:
PHP pseudo code:
if($ok) //you condition here
{
$html = file_get_contents("newPage.php");
$toEcho = array("status"=>"true" , "message"=>"successful", "html"=>html);
$json_parsed = JOSN_encode($toEcho);
echo $json_parsed;
}
else
{
$toEcho = array("status"=>"false" , "message"=>"Wrong information", "html"=>false);
$json_parsed = JOSN_encode($toEcho);
echo $json_parsed;
}
JS pseudo code:
$.ajax({
url: "yourUrl.php",
type: "post",
data:"json"
}).done(function (result){
if(result.status==="true")
{
if(result.html)
{
$("#oldDiv").html(result.html);
}
}
else if(result.message)
{
$("#errorMsg").html(result.message);
}
});
It's bad practice but you can try parse the response:
$.ajax({ url: " ....URL...." , type:"POST" , data:{.. your variables ..} })
.done(function(response) {
var tryRes = false;
try { response = $.parseJSON(response); tryRes = true; }
catch (e) { }
if (tryRes) {
//JSON ~ resonse is allready an object
} else {
//OTHER ~ HTML
}
}).fail(function(response) {
//Bad request
});

Javascript Logic Fail?

I'm really confused on this one. I'm trying to do a simple ajax request, and I have php executing 'echo "true";' if the ajax request is successful, or return a string containing the error if it isn't. I'm using this exact technique elsewhere in the code and it compares as expected (msg != "true") { //do something }. The first function I'll post below works with that method, the second doesn't (also I am checking with Firebug the response is "true", and I've done console.log(typeof msg) to verify it is of type string).
This works as expected (the php echoes "true", and it executes show_step2()):
function step2_register() {
var values = $('.signup .txt').serialize();
$.ajax({
type: "POST",
url: base_url+"login/create_account",
data: values,
success: function(msg) {
if (msg != "true") {
$("#login_form.signup .error_container #error1").html(msg).css("visibility", "visible");
}
else {
show_step2();
}
},
error: function(error) {
alert(error);
}
});
}
This doesn't work (the php echoes "true", but the js always executes the slideDown() part of the code):
function register() {
var data = $("#login_form .input").serialize();
$.ajax({
type: "POST",
url: base_url+"login/register",
data: data,
success: function(msg) {
if (msg != "true") {
$("#login_form.signup #error2").html(msg).slideDown();
}
else {
show_success();
}
},
error: function(error) {
alert(error);
}
});
}
What's going on here?
Your php is likely outputting something else invisible like a newline character after the word "true". Either make sure you call die(); or exit(); right after outputting "true", (and doing everything else you need), or make sure there are no line breaks in your PHP editor before the <?php and after the ?>.
You can also check that the string begins with "true" instead of equals "true" by trying something like msg.substring(0,4) == "true"

Categories

Resources