Load PHP array into html as select options - ajax

I am having trouble working the finishing touches out with this. I am still fairly new to ajax and json, but here's what i have so far. I am trying to take an array(s) from a php file and load them into a select dropdown (#input) via ajax/json. I think i'm pretty close, but i'm not sure where i'm messing up. Please help
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="../_js/jquery-1.7.2.min.js"></script>
<script>
$(document).ready(function() {
if ($("#numbers").val() == "2") {
$.ajax({
type: 'POST',
url: 'login.php',
data: 'id=testdata',
dataType: 'json',
cache: false,
success: function(result) {
var numbers = <?php echo json_encode($array); ?>;
for (i=0;i<numbers.length;i++){
$('#input').append("<select>" + numbers[i] +
"</select>");
}
},
});
}
});
</script>
</head>
<body>
<div class="wrapper">
<div class="header">
</div>
<div id="content">
<div class="main">
<div id="formwrapper">
<select id="numbers">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select id="input"></select>
</div>
</div>
</div>
</div>
</body>
</html>
And here is my PHP (login.php)
<?php
$array = array(1,2,3,4,5,6);
echo json_encode($array);
?>

In your script, you aren't doing anything with the data that is returned from the AJAX call. I suspect that is because you don't understand how AJAX works. I'll try to explain it without going into super deep detail.
When you make an AJAX call to a URL, you are making an HTTP request, just like when you type http://www.google.com into your web browser. In response, the server at the other end of that URL sends you an HTTP response with some data.
In the case of your AJAX, you are requesting the response of login.php, which, I will assume, is the PHP you added to your question above. In the success function, you get a result. That result is everything that was output by login.php.
So,
$(document).ready(function() {
$("#numbers").change(function(e) {
if ($(this).val() == "2") {
$.ajax({
type: 'POST',
url: 'login.php',
data: 'id=testdata',
dataType: 'json',
cache: false,
success: function(result) {
var numbers = result; //result is equal to your array from the php. You don't put PHP here.
$('#input option').remove(); //Remove any existing options.
for (i=0;i<numbers.length;i++){
$('#input').append("<option>" + numbers[i] + "</option>");
}
}
});
}
});
});
If login.php is NOT the PHP you added above, then I'm not going to be able to help you until you tell me what file that is from.
Also, notice that we wrapped the AJAX call into a change event on the #numbers select box. That way, when the select box's value changes, it will call this AJAX, and select the numbers.
Thanks for the assist tymeJV.

Related

Posting form using AJAX

can anyone please help me with sending the below form using Ajax. All I want is to send it to the trolley1.php page for processing, no call backs or anything like that. Basically replicate the form but sending it with Ajax so the page does not go to the trolley1.php page. I have tried so many methods but have not been able to do this. Bill Gates or Steve Wozniak if you guys are reading this, please help
This gives me a console $.Ajax is not a function in the console
<script>
$(document).ready(function(){
$('form').submit(function(event){
event.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url: "trolley1.php",
type: "POST",
dataType:"json",
data: form_data
}).done(function(data){
alert("Item added to Cart!");
}
});
});
</script>
<?php
echo "
<div class='col-sm-3 mt-5'>
<form class='ajax' method='post' action='trolley1.php?action=add&id=$id'>
<div class='products'>
<a>$img</a>
<input type='hidden' name='id' value='$id'/>
<input type='hidden' name='name' value='$product'/>
<input type='hidden' name='price' value='$price'/>
<input type='text' name='quantity' class='form-control' value='1'/>
<input type='submit' name='submit' style='margin-top:5px;' class='btn btn-info'
value='Add to Cart'/>
</div>
</form>
You have one syntax error in your JS Code - see correct code
$(document).ready(function(){
$('form').submit(function(event){
event.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url: "trolley1.php",
type: "POST",
dataType:"json",
data: form_data
}).done(function(data){
alert("Item added to Cart!");
});
});
});
And you are using jQuery as additional javascript libary. jQuery uses $ to access the methods (e.g. $.ajax) Thats the reason why you get undefined as error.
So you need to load the libary first at the beginning of your page (inside <head>). E.g. directly from their CDN
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
Then it should work for you

How to capture AJAX response?

I have a simple script, in ajax, and I want to capture the return and process it according to the value:
if (xmlhttp.readyState==4) {
if (xmlhttp.responseText == "not available") {
document.write("not available");
}
}
At the same time, I tried this, which worked:
if (xmlhttp.readyState==4) {
document.write(xmlhttp.responseText);
}
What wrong am I doing?
Thank you for your reply. This is my current domain availability checking script which works great:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#dtype').change(function() {
var opt = $('#domain').val();
$.ajax({
type: "POST",
url: "testwhois.php",
data: 'd=' + opt,
success:function(data){
$('#txtHint'). html(data);
}
});
});
});
</script>
</head>
<body>
<form> Domain name : <input type="text" name="domain" id="domain"> <input type="radio" name="dtype" id="dtype" value="new">New <input type="radio" name="dtype" value="transfer">Transfer <span id="txtHint"></span> </form>
</body>
</html>
However, I want to have two things in it:
a preloader image (I have it) while the script is working in the place of 'txtHint' where the answer will be displayed.
The answer is returned in the format of "not available" or available". I want to make the 'domain' field blank, when the answer is returned as "not available" with the html codes.
Thanks again.
Forgive me if you know this already, but in case you don't:
Ajax posts data to an external php file, which processes the data it receives, and sends back an answer. It looks like this:
FILE #1:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#Sel').change(function() {
var opt = $(this).val();
var someelse = 'Hello';
var more_stuff = 'Goodbye';
$.ajax({
type: "POST",
url: "receiving_file.php",
data: 'selected_opt=' + opt + '&something_else=' +someelse+'&more_stuff='+more_stuff,
success:function(data){
alert('This was sent back: ' + data);
}
});
});
});
</script>
</head>
<body>
<select id = "Sel">
<option value ="Song1">default value</option>
<option value ="Song2">Break on through</option>
<option value ="Song3">Time</option>
<option value ="Song4">Money</option>
<option value="Song5">Saucerful of Secrets</option>
</select>
FILE #2: receiving_file.php
<?php
$recd = $_POST['selected_opt'];
echo 'You chose: ' . $recd;
The above example works. If you copy/paste it into two files, you will see AJAX in action. Of course, the server side scripting is in PHP, so your server needs to handle that. If necessary, download XAMPP and install it on your local computer. Place these two files in the htdocs folder and, in the browser address bar, type:
http://localhost/whatever_you_called_the_first_page.php
As you can see, it is much simpler to write AJAX code using jQuery. All that is needed is the jQuery library (usually in the header tags, as in code example above), and the AJAX code block.
Here are some other examples to study:
More complicated example
Populate dropdown 2 based on selection in dropdown 1

Cross Domain Ajax Issue

I have two files
1) index.php(picks data from the code editor and submits for processing via Jquery Ajax to exec.php)
2) exec.php (currently just transfer the data it recieved via index.php using jsonp)
Code of index.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function test() {
var code = document.getElementById('code').value;
var code_data = "code=" + code;
alert(code_data);
$.ajax({
type: "POST",
crossDomain: true,
url: "http://code1.guru99.com/exec.php",
data: code_data,
dataType: "jsonp",
success: function (data) {
alert(data);
}
});
alert("End of Test");
}
</script>
<form name="myform" id="myform" method="POST" class="code-box">
<textarea name="code" id="code"><?
$code='<?php
"Hello";
?>';
echo $code;
?>
</textarea> <!-- for add html tag in text area nad print the code-->
<div class="hint">This code is editable. Click Run to execute.</div>
<input type="submit" value="Run" id="submit" onClick="test();"><!--<img id="ajax-loader" name="ajax-loader" src="/img/ajax-loader.gif" class="hidden" style="vertical-align:middle" />-->
</form>
<div name="label" id="label"> </div>
<div name="out" id="out"> </div>
Code of exec.php
<?php
$code=$_POST['code'];
$fp=fopen("file.txt","w"); // Storing the data into a file just to know that data is passed
fwrite($fp,$code);
fclose($fp);
header('Content-Type: application/jsonp');
echo $_GET['callback']."(".json_encode($code).");"
?>
The problem is data just does not pass into exec.php. I am not sure why...
The code is live at http://code.guru99.com/php/
Please help...
You cannot use AJAX to do this. Instead consider posting from a hidden Iframe using a regular FORM and setting the action to the URL you desire. You can still submit the form using JavaScript.
You can also listen to the onload event on the iframe to detect when your post has completed.
Alternately, you can use a server-side proxy.
The code syntax is correct.
May the problem could be with your server

Couldnt get CSRF to work with ajax (CI 2.1)

i am trying to get CSRF work with ajax in my CI 2.1 application.
i have searched about this and found few guidlines, but couln't resolve the problem
http://ericlbarnes.com/post/10728867961/codeigniter-csrf-protection-with-ajax
http://www.beheist.com/index.php/en/blog/csrf-protection-in-codeigniter-2-0-a-closer-look
http://aymsystems.com/ajax-csrf-protection-codeigniter-20
i have set two different tokens for two token values in the config
$config['csrf_protection'] = TRUE;
$config['csrf_token_name'] = 'token01';
$config['csrf_cookie_name'] = 'token02';
$config['csrf_expire'] = 7200;
Here is my view, i am using form_open
<?php echo form_open("http://localhost/pis/user"); ?>
<div id="inputs">
<?php echo form_input($username);?>
<?php echo form_password($password);?>
</div>
<div id="actions">
<div style="float:left"><?php echo form_submit($submit);?>
<!-- <input type="button" value="Login" id="submit" name="submit" onclick="clicksubmit()" /> -->
</div>
</div>
<?php echo form_close();?>
I am using this javascript to make async call
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(
function(){
var form_data = {
username: $("#username").val(),
password: $("#password").val(),
csrf_token_name: $("input[name=token01]").val()
};
$.ajax({
type: "POST",
url: "http://localhost/pis/user",
data: form_data,
success:
function(data){
$("#debug").html(data.message).css({'background-color' : data.bg_color}).fadeIn('slow');
}
});
return false;
});
});
</script>
When i run this i am getting a "500 Internal Server Error" along with the "An Error Was Encountered, The action you have requested is not allowed" as a response. Firebug shows the POST data parameters correctly.
eg: username=root&password=root&csrf_token_name=31961f17de5fa2df657ab1aba880f718
How ever if i removed the csrf, ajax request runs fine and i get 200 as response
Can anyone help me please?
Even better, you can just let jQuery serialize the form data for you:
var form_data = $(this).serialize();
This way you won't have to worry about inputs being renamed or more fields being added.

How to trigger Ajax with flash buttons?

I'm working on something where there are 2 links which triggers some Ajax. However I need to turn the links into Flash buttons (AS3). I've never worked with Ajax before, and I have no idea how this can be done.
Edit:
The Ajax:
<script>
$(document).ready(function() {
$('a.catlink').unbind('click').click(function(e)
{
e.preventDefault();
var link = $(this);
var inputs = [];
var cat_type = $(this).attr('href').replace('#', '');
link.attr('disabled', 'disabled');
inputs.push('cat_type=' + escape(cat_type));
$.ajax(
{
type: "POST",
cache: false,
dataType: "html",
url: window.location.href,
data: inputs.join('&'),
success: function(html)
{
var json = $.parseJSON(html);
if (json['status'] == 1)
{
$('div.listing').html(json['html']);
}
link.removeAttr('disabled');
}
});
});
});
</script>
The HTML
<h1 class="section-head">Products
// **The 2 links*** //
<a class="catlink" href="#cinema">cinema</a> <a class="catlink" href="#smart">smart</a></h1>
<div class="listing">
<ul class="listing">
{foreach from=$products item="product_info"}
<li class="clearfix">
<div class="inner-left">
<img height="68" width="90" src="{$product_info.image}" />
<h2 class="normal mt-5">{if $product_info.price != '0'}${$product_info.price}{else}Click for price ยป{/if}</h2>
</div>
<div class="inner-right">
<h3 class="mb-0">{$product_info.productName}</h3>
<p class="small mb-5"><span class="quiet">{$product_info.category}</span></p>
<p class="mb-15">{$product_info.description}</p>
<a class="button getprice" href="{$product_info.url}">Buy Now</a>
<br><br>
</div>
</li>
{/foreach}
</ul>
</div>
If you're going to use AS3 then you can use ExternalInterface.call() to call a JavaScript function on the page. Though, using Ajax may not be required if you're using AS3 because you can make use of the URLLoader class to do the same thing (call a PHP script and decode a result).
If you describe more accurately what you want to achieve then I shall provide some example code and clarify a little more.

Resources