I working in CodeIgniter and I am trying to spit out all of the items I have in a table and order them as they should be using the dropdown. I want it to happen without page reload and without submit buttons, so I am using this jQuery function to make immediately react, when it is changed:
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
alert(data);
});
});
Inside you can see the $.post method, with wich I am trying to send the data to php script (orderValue).
After that, I am getting an alert (not even sure, why do I need it (Maybe to check if everything is ok there))
In PHP, I am receiving the chosen select option and assigning a variable ($data['people']) to the results of MySQL query (that is placed in the model) to be able to access it withing the view. This - $_POST['val'] represents, how can I order the list (select * from people order by $theorder" ($theother is just a variable inside the query function. It recieves the value of $_POST['val'])).
if(isset($_POST['val'])) {
$data['people'] = $this->database->listPeople($_POST['val']);
exit;
}
After that I recieve this variable in the view and I am running foreach loop to take different parts of the array(name of the person, his age, etc..) and placing it in the way they should be.
The problem is - if I do that without ajax, when I have static order by value - everything works fine. I did not mean that was the problem :D, the problem basically is that is doesn't work with ajax... I was trying to recieve the array in the js callback and create a layout using
$.each(eval(data), function() {
$('#container').text('<div>' + eval(res).name + '</div>');
});
But that was also a failure...
How should I organize and create my code to make everything work properly?
I am kinda new to Ajax, so I hope I'll really learn how to do that from you guys. I already searched through the whole internet and have seen a lot of ajax tutorials and other kind of material (e. g. StackOverflow), but I still can't get, how can I do all of that in my particular situation. I have wasted already about 12 hours trying to solve the problem and couldn't do that, so I hope You will tell me if there is any useful salvation.
Thank you for your consideration.
Hi the skinny is you need 3 parts to make ajax work,
serverside code to generate the page
ajax ( clientside ) to make the call and respond
seperate serverside to receive it.
Also it will be easier to replace the table completely then to pick out elements. But that is up to you.
So say we have the page with our ajax call
<script type="text/javascript" >
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
alert(data);
});
});
</script>
Now you seem to have some json response I'll assume you get this from the alert above;
[{"id":"1","name":"Nick","age":"18"},{"id":"2","name":"John","age":"23"}]
I'll also assume that this comes from something like
echo json_encode( array( array('id'=>1, ...), array('id'=>2 ...) .. );
It's important before doing the echo that you tell the server that this is json, you do this using a header, but you cannot output anything before the header, and after the json header all output must be in the json format or it wont work, it's like telling the browser that this is html, or an image etc. what the content is.
Header("Content-Type: application/json");
echo json_encode( ....
You can get away without doing this sometimes, but often you'll need to use eval or something, by telling the browser its json you don't need that. Now doing an alert is great and all but if you see the string data [{"id": .. your header is wrong, you should get something like [object] when you do the alert.
No once we have a factual Json object we can make use of all that wonderful data
<script type="text/javascript" >
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
$.each(data, function(i,v){
alert(v.id);
alert(v.name);
});
});
});
</script>
This should loop through all the data and do 2 alerts, first the id then the name, right. Next it's a simple matter of replacing the content using .text() or .append()
<script type="text/javascript" >
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
$.each(data, function(i,v){
$('#test').append('<p>'+v.id+'</p>');
});
});
});
</script>
<p id="test" ></p>
Related
Hello im trying make a system for when on value on my datebase is 1 my index page refresh. this is my code!
All PHP code works, only my index.php not refresh.
index.php
<script>
inverval_timer = setInterval(function update() {
$.get("base_de_dados/update/loadMensagens.php", function(data) {
$("#numseiCategoria").html(data);
window.setTimeout(update);
})
}, 5000);
</script>
loadMensagens.php
<?php
include_once '../bdados.php';
$fila = $conn->query("SELECT * FROM tickets_update");
while($Filas = $fila->fetch_assoc()){
$condicao = $Filas['condicao'];
}
if($condicao == 1){
$condicao = 0;
$queryAtualizar = $conn->query("UPDATE tickets_update SET condicao='$condicao'");
echo "
<div id='a'></div>
<script>
$.ajax({url:'updateMensagens.php', success:function(result){
$('#a').html(result)
}});
</script>";
}
?>
updateMensagens.php
<script>
$(document).ready(function(){
location.reload();
});
</script>
At a glance there are a couple of reasons your page isn't reloading. Firstly, the reload method being wrapped in that .ready() probably prevents it from being called, as I believe the ready event only fires when the DOM first loads.
$(document).ready(function(){
location.reload(); // Will never fire if script is added to DOM after initial load.
});
But I think there's another issue as your code simply appends this HTML...
<div id='a'></div>
<script>
$.ajax({url:'updateMensagens.php', success:function(result){
$('#a').html(result)
}});
</script>";
...onto the end of #numseiCategoria's inner text, which probably doesn't make the browser execute the script anyway (I'm assuming that jQuery's .html() is basically an alias for innerHTML here, I can't be bothered to go and check).
But, in terms of good practices, there's more to it than that...
updateMensagens.php seems to be incredibly redundant, unless there's more to it than you're showing. Let's have a think about how you intended it to work, ignoring the fact that your method of adding scripts to the page is incorrect.
You have your main script in index.php, which sends a get request to loadMensagens.php, which does some database stuff. So far so good...
Your PHP script then echoes some JS, which your main script appends to the page. This JS tells the client to send another get request, this time to updateMensagens.php, and to once again append the result to the page.
This second request returns only a script telling the browser to reload the page. And now we've run into problems.
This is a really awkward and long-winded way to go about this, especially once you try to scale the approach up to larger projects. You're trying to do certain things with PHP which are much more easily done with JS. I'll briefly highlight a couple of things for you.
Firstly, echoing HTML back to the client like that is not great, it gets very unwieldy very quickly. It's much cleaner to return any necessary data to the front end as JSON (or a similar format) and handle generating HTML with JS. jQuery makes generating complex documents rather easy, as you're already using it I'd recommend that approach.
Secondly, this system of using ajax requests to fetch a script from the server to append to the page to perform a simple action with JavaScript is diabolical. Please see my untested, 4AM alternative.
index.php
<script>
inverval_timer = setInterval(function update() {
$.get("base_de_dados/update/loadMensagens.php", function(data) {
let res = JSON.parse(data);
if(res.condiciao === true) {
location.reload();
}
});
}, 5000);
</script>
loadMensagens.php
<?php
$return = [];
include_once '../bdados.php';
$fila = $conn->query("SELECT * FROM tickets_update");
while($Filas = $fila->fetch_assoc()){
$condicao = $Filas['condicao'];
}
if($condicao == 1){
$return['condicao'] = true;
$condicao = 0;
$queryAtualizar = $conn->query("UPDATE tickets_update SET
condicao='$condicao'");
} else {
$return['condicao'] = false;
}
echo json_encode($return);
As an addendum, you seem to be using setTimeout wrong. On one hand I'm quite sure the method is supposed to take 2 arguments, but on the other hand I'm not sure why it's being used at all.
Goodnight.
I'm building a web application in CodeIgniter and I'm using jQuery and AJAX. I created the whole app locally (using XAMPP) and everything worked fine. After I uploaded the app to my web hosting, one AJAX keeps failing. Here is the part of the code:
// Get all form inputs
var inputs = $('#app-options-existing-form :input[type="text"]');
// Put them in object as name=>value
var data = {};
for(i=0; i<inputs.length; i++) {
data[inputs[i]["name"]] = inputs[i]["value"];
}
// Put loader while AJAX is working
$(".app-content-container").html('<center><img class="loader" src="<?php echo base_url();?>/img/loader.gif" ></center>');
console.log(data);
// Generate POST request
$.post("<?php echo site_url("admin/ajax_app_options"); ?>",
{"add_existing_form_submited" : true, "data" : data2},
function (data) {
alert("test" + data);
});
Here's the console showing error and result of console.log(data)
First, I thought that the key ("d1d1d1") was the problem because I was first using "1-1-1" and after I manually changed it, it was working. But then I changed everything in "d1d1d1" and it doesn't work again. As I said, it works on XAMPP but not on server. Can be a problem in using full URL for AJAX, instead of relative one? But I'm using it in other AJAX requests as well and it works.
Pretty sure you problem is this guy '<center><img class="loader" src="<?php echo base_url();?>/img/loader.gif" ></center>'
Yours source is going to output literally to <?php echo base_url();?>/img/loader.gif which is of course not a real link. Therefore it is a resource that can not be loaded.
You might want to try instead using: '<center><img class="loader" src="/img/loader.gif" ></center>'
The base_url() function is just going to return '/' anyway.
Important! In general you can not write php in javascript. Or this would be a massive security hole that would give every user who visits your site unlimited access to your server.
After hours of playing with this, it hit me that my JQuery simply isn't executing.
I have a page that I am trying to submit to a PHP script without refreshing/leaving the page. If I use a typical form action/method/submit, it inserts into my database just fine. But when I use JQuery, the JQuery will not run at all. The alert does not show. (I'm new to JQuery). I have tried to research this, but nothing is working.
Here is my main page:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(e) {
$('submitpicks').on('submit','#submitpicks',function(e){
e.preventDefault(); //this will prevent reloading page
alert('Form submitted Without Reloading');
});
});
</script>
</head>
<body>
<form name="submitpicks" id="submitpicks" action="" method="post">
<script language="javascript">
var v=0;
function acceptpick(thepick,removepick){
var userPick = confirm("You picked " + thepick + ". Accept this pick?");
//var theid = "finalpick" + v;
var removebtn = "btn" + removepick;
//alert(theid);
if(userPick==1){
document.getElementById("finalpick").value=removepick;
document.getElementById(removebtn).disabled = true;
document.getElementById("submitpicks").submit();
v=v+1;
}
}
</script>
<?php
include "Connections/myconn.php";
//$setid = $_SESSION["gbsid"];
$setid = 11;
$setqry = "Select * from grabBagParticipants where gbsid = $setid order by rand()";
$setresult = mysqli_query($conn, $setqry);
$u=0;
if(mysqli_num_rows($setresult)>0){
while($setrow = mysqli_fetch_array($setresult)){
//shuffle($setrow);
echo '<input type="button" name="' . $setrow["gbpid"] . '" id="btn' . $setrow["gbpid"] . '" value="' . $u . '" onClick=\'acceptpick("' . $setrow["gbpname"] . '", ' . $setrow["gbpid"] . ');\' /><br />';
$u=$u+1;
}
}
?>
<input type="text" name="finalpick" id="finalpick" />
<input type="submit" value="Save" />
</form>
<div id="results"> </div>
</body>
</html>
Here is my PHP:
<?php
include "Connections/myconn.php";
$theGiver = 1;
$theReceiver = $_POST['finalpick'];
$insertsql = "insert into grabBagFinalList(gbflgid, gbflrid) values($theGiver, $theReceiver)";
mysqli_query($conn, $insertsql);
?>
you can use e.preventDefault(); or return false;
<script>
$(document).ready(function(e) {
$('#submitpicks').on('submit',function(e){
e.preventDefault();
$.post('submitpick.php', $(this).serialize(), function(data) {
$('#results').html(data);
});
// return false;
});
});
</script>
Note: in your php you not echo out anything to get it back as a data .. so basic knowledge when you trying to use $.post or $.get or $.ajax .. to check the connection between js and php .. so in php
<?php
echo 'File connected';
?>
and then alert(data) in js .. if everything works fine .. go to next step
Explain each Step..
before everything you should check you install jquery if you use
<script type="text/javascript" src="jquery-1.11.3.min.js"></script>
from w3schools website.. its totally wrong .. you should looking for how to install jquery ... then
1st to submit form with js and prevent reloading.. and you used <script> in your main page
<script>
$(document).ready(function(e) {
$('#submitpicks').on('submit',function(e){
e.preventDefault(); //this will prevent reloading page
alert('Form submitted Without Reloading');
});
});
<script>
output : alert with Form submitted Without Reloading ... if this step is good and you get the alert .. go to next step
2nd add $.post to your code
<script>
$(document).ready(function(e) {
$('#submitpicks').on('submit',function(e){
e.preventDefault(); //this will prevent reloading page
$.post('submitpick.php', $(this).serialize(), function(data){
alert(data);
});
});
});
<script>
and in submitpick.php >>> be sure your mainpage.php and submitpick.php in the same directory
<?php
echo 'File connected';
?>
output: alert with File connected
Have you heard of AJAX(asynchronous javascript and XML). While it may not be something that is easy to learn for someone who is new to JQuery and javascript, it does pretty much what you need. Well, its a bit more complicated than that, but basically AJAX submits information by using HTTP requests (much like normal forms) but without refreshing the page.
Here's a link to a tutorial: http://www.w3schools.com/ajax/ with vanilla javascript.
Here's one with Jquery: http://www.w3schools.com/jquery/jquery_ajax_intro.asp
And here's an example of how you can set it up with Jquery:
$(document).ready(function() {
$.ajax({
method: "POST",
url: "/something.php"
dataType: "JSON",
data: {formData:{formfield1: $('formfield1').val(), formfield2: $('formfield2)'.val()}},
success: function(data){
if (data["somevalue"]) == something {
dosomething;
} else {
dosomethingelse
},
error: function() {
alert("Error message");
}
});
});
This is only a basic example, now what does all this stuff mean anyway. Well, there are several methods, some of them are POST and GET, these are HTTP request methods, which you can use to do several things. I'm no expert on this stuff, but here's what they do:
Method
POST
POST basically works, to submit information to a server, which is then usually inserted to a database to which that server is connected to. I believe most forms utilize POST requests, but don't quote me on that.
GET
GET on the other hand requests data from a server, which then fetches it into the database and sends it back to the client so it can perform an action. For instance, whenever you load a page, GET requests are made to load the various elements of a page. What's important to note here, is that this request is made specifically to retrieve data.
There are other types of HTTP requests you can use such as PUT and DELETE, which I'd say are the most common along with GET and POST. Anyway I'd recommend that you look them up, its useful information.
Url
The url represents the path to which you are making a request, I'm not exactly sure how it works with PHP, I think you just need to call the PHP page in question and it will work properly, but I'm not sure, I haven't used PHP since my last semester, been using Rails and it doesn't work quite the same. Anyway, lets say you have some PHP page called, "Something.php" and lets say that somethihng PHP has the following content:
<?php
$form_data = $_POST['data'];
$array = json_decode(form_data, true);
do something with your data;
$jsonToSendBack = "{status: 1}";
$response = json_encode($jsonToSendBack);
echo $response;
?>
So basically what that file received was a JSON, which was our specified datatype and in turn after we finish interpreting data in the server, we send back a response through echo our echo. Now since our datatype is a JSON, the client is expecting a response with JSON, but we'll get to that later. If you're not familiar with JSON, you should look it up, but in simple terms JSON is a data exchange format that different languages can utilize to pass data to each other, like in this example, where I sent data to PHP through Javascript and vice-versa.
DataType
Data type is basically, the type of information that you want to send to the server, you can specify it through ajax. There are many data types you can send and receive, for instance if you wanted to, you could send XML or Text to the server, and in turn it should return XML or text, depending on what you chose.
Success and Error
Finally, there's the success and error parameters, basically if a request was successful, it returns a status code of 200, though that doesn't mean that other status codes do not indicate success too, nonetheless 200 is probably the one you'd like to see when making HTTP requests. Anyway, success basically specifies that if the request succeeded it should execute that function code I wrote, otherwise if there is an error, it will execute the function within error. Finally, even if you do have a success on your request, that doesn't mean everything went right, it just means that the client was successful in contacting the server and that it received a response. A request might be successful but that doesn't generally mean that your server-side code executed everything perfectly.
Anyway, I hope my explanation is sufficient, and that you can take it from here.
I have this JS function and I'm looking for the simplest way to send a variable to php and have php return an array to my JS. I have the second part down I just need help sending the variable. Here's my function:
function myEvent(){
//console.log(uploaded);
var length = uploaded.length;
var content = document.getElementById("Profile");
if(length == 0){
content.innerHTML = '<p style="text-align:center"><b> You uploaded no events. </b></p>';
}
else {
content.innerHTML = " ";
for(var i=0; i<length;i++){
var entry = document.createElement('li');
var EID = uploaded[i][0];
entry.innerHTML= ''+uploaded[i][1]+'';
content.appendChild(entry);
}
return false;
}
}
I want to be able to send EID which is a unique ID to a PHP script every time I click the link.
Any help? I'm using Jquery but I'm not too familiar with it. If there's an option using JS alone I would really appreciate it.
You can do that using Ajax. There's also another really simple way to send data to a php script on any server (same domain or not) while making that php script interact with your page
first you create a script tag:
var tag = document.createElement('script');
the src of that tag will be the url of the php script that will receive the variable:
var myVar = 'foo';
tag.src = '/path/to/my/script.php?variable='+myVar;
you add the script tag to the dom to request it
document.getElementsByTagName('head')[0].appendChild(tag);
on the server side the php script receives the variable and does whatever it should do with it, and optionally it can echo any javascript that will run on the page afterwards:
<?php
echo "alert('".$_GET['variable']."')";
that's pretty much it, WARNING, be aware that this is just a simple example, to implement something like this on a production site you need to make sure that doing so won't open your site to XSS attacks, code injection etc... how to do that is beyond what is being discussed here but be aware
Make sure you view this using firebug, or anything similar in order to see the returned results, in the jquery done function you can then do data[0], etc for the arrays
html
<!DOCTYPE html>
<html>
<head>
<title>JQuery Test</title>
<meta charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="myjs.js"></script>
</head>
<body>
<button id="sendData">Send Data</button>
</body>
</html>
JS
$(document).ready (function (){
$("#sendData").on ("click", function (){
jQuery.ajax ({
url: "index.php",
type: "POST",
data: {returnArray: 1}
}).fail (function (){
console.log ("failed");
}).done (function (data){
console.log (data);
});
});
});
PHP
if (isSet ($_POST ['returnArray']))
{
$a = array ("a", "b", "c", "d");
header('Content-type: application/json');
echo json_encode ($a);
exit;
}
I am sure you can figure this out... show some effort.. and don't be afraid to ask if you still don't understand.. just as long as you try.
Use JavaScript's XMLHttpRequest to send a message to the server running PHP. When the PHP script responds, the XMLHttpRequest object will let you know and you'll be able to grab the XMLHttpRequest.responseText.
It would be a good idea to have PHP respond with JSON, which it can do easily. Then you can parse the responseText with JavaScript's JSON.parse function and just use it.
The following two articles will show you how to use the standard objects.
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
http://www.php.net/manual/en/function.json-encode.php
You'll just have to be sure you don't try talking to a different website than the one your page is loaded from, unless you want to learn all about cross domain requests.
In my form, I want to do something with two fields:
"website_domain" and "website_ip_address"
I'm trying to use jQuery/JSON to call a PHP script, pass the website_domain to it, and receive JSON including the IP address of that website.
Problem/Symptoms Description:
It's partially working: On blur, it GETs the url of the PHP script. I can see that much in firebug. I get a 200 OK. Output from the PHP script is valid JSON according to JSONLint:
{"field":"website_ip_address","value":"74.125.225.70"}
But in Firebug, I don't have a JSON tab. I only have Params and Headers tabs. Not even a Response tab.
Needless to say, the website_ip_address field is also not being populated with the data I should be getting from the PHP script's JSON output.
My PHP Script:
It may be important to note that for now, this PHP script on a different domain from my application. Maybe my whole problem is cross-domain?
<?php
$domain = $_GET["domain_name"];
$ip = gethostbyname($domain);
// echo $ip;
$json = array(
'field' => 'website_ip_address',
'value' => $ip,
);
header('Content-Type: text/plain');
echo json_encode($json );
?>
My jQuery/JSON script:
Note this is written inside a Ruby On Rails application view.
:javascript
$("#website_domain").bind("blur", function(e){
$.getJSON("http://exampledomain.com/temp_getIP.php?domain_name=" +$("#website_domain").val(),
function(data){
$('#website_ip_address').val(data);
});
});
I really hope this isn't just a syntax error on my part. I've been writing/rewriting this for 2 days, based on answers I've found on StackOverflow, to no avail. I'm just missing something here.
You are currently attempting to output the JS object (that is formed from the parsed JSON response) to the field. You need to output a value from within it. So not:
$('#website_ip_address').val(data); //data is an object, not a string
but
$('#website_ip_address').val(data.someValue); //output a property of the object
With your code as it is, I would expect the field to be populated with the string representation of an object, which is [object Object]. You don't mention this, so I wonder whether a) your success function is even firing (check this - stick a console.log in it); b) your jQ selector is sound.
The problem can be with different domain. I had it like this before. Try in php to add header("Access-Control-Allow-Origin: *")
Put your jQuery code inside document ready, example: $(function(){ });
:javascript
$(function() {
$("#website_domain").bind("blur", function(e){
$.getJSON("http://exampledomain.com/temp_getIP.php?domain_name="+$("#website_domain").val(),
function(data){
$('#website_ip_address').val(data);
});
});
});
});
And you have a missing end })