My webpage is supposed to generating a series of questions in a random order. Each question is a seperate HTML page with a picture and multiple options.On page load, there should a default question and thereafter on clicking next a new page is loaded. I am currently:
Creating a php array with the names of the html pages and shuffling it.
Converting this array into a json array to be accessed in Javascript.
Trying to ajax load the page.
I am stuck at the third step; how do you send a json array element in an ajax call i.e.
$.ajax({
url: name+".html",
success: function(html){
$("#container").empty().append(html);
}
});
where name is the name of the webpage stored in the json array and container is the div on my current php page.
In case there is an easier way of doing the above task, I am open to that too.
Thanks!
EDIT
Step 2:
var xdata = <?php echo json_encode($testArray); ?>;
where $testArray is the php shuffled array of webpages.
Use the jQuery load function.
var pageToLoadIntoContainer = 'Test1.html';
$('#container').load( pageToLoadIntoContainer );
Extending this answer to try and solve all of your elements...
<?php
$pageArray = shuffle(array(
'Test1' ,
'Test2' ,
'Test3'
));
....
?>
<script>
var pageArray = <?php echo json_encode( $pageArray ); ?>;
....
$('#container1').load( pageArray[0] );
$('#container2').load( pageArray[1] );
$('#container3').load( pageArray[2] );
</script>
$.ajax({ url: name+".html", success: function(html)
$("#container").empty().append(html);
}
});
there are 1 '{' and 2 '}'
try
$.ajax({ url: name+".html", success: function(html){
$("#container").empty().append(html);
}
});
Related
I am planning to insert a link to my another php page using jquery function, but the code doesn't work... Alternative methods such as attr() has been tried as well, but it was still the same result... Can someone pls give me advices regarding this matter? Following are my codes:
$(document).ready(
function(){
$('#date').change(
function(){
$.ajax (
{
url: 'process.php',
type: 'post',
data: {
item_no:2,
movie_id: $('#movie').val(),
movie_date: $('#date').val()
},
dataType: 'json',
success: function(response){
$('#showtime').empty();
for(var i = 0; i<response.length; i++){
var showtime = response[i]['showtime'];
$('#showtime').append("<a href='movie_seat.php?id="+showtime+"' id='seatlink'>");
$('#showtime').append("<font style='margin-right:50px;'>");
$('#showtime').append(showtime);
$('#showtime').append("</font></a>");
} // for loop
} // function taking response
} // block in ajax
); //ajax
} // function inside change
); // select->date change
} // function inside ready
); // document.ready
*Note that #showtime is the id of a attribute
My expectations:
The value displayed should be able to work as a link that will direct the user to another php page. But apparently, it doesn't....
You need append all together, because if you append something like this:
$('#showtime').append("<a href='movie_seat.php?id="+showtime+"' id='seatlink'>");
$('#showtime').append("<font style='margin-right:50px;'>");
$('#showtime').append(showtime);
$('#showtime').append("</font></a>");
That way the tags will be closed, and you html will seems like this:
<font style="margin-right:50px;"></font>
showtime
So what you need to do is append all together, i mean tags inside tags, try this:
var link = "<a href='movie_seat.php?id="+showtime+"' id='seatlink'>"
+ "<font style='margin-right:50px;'>"
+ showtime
+ "</font></a>";
$('#showtime').append(link);
Trying to send a post request from ajax to php.
I did many trial and errors based from the answers including making sure that the "type" is set to post, specifying "dataType", correct "url". I think I miss something important but I can't figure out what it is.
main.php
<script>
$(document).ready(function(){
$(".editContact").on("click", function(){
let dataID = $(this).attr("data-id");
console.log(dataID);
$.ajax({
type: 'POST',
url: 'functions/phonebook.php',
dataType: "text",
data:{data:dataID}
});
});
});
</script>
functions/phonebook.php
if(isset($_POST["data"])){
$res = array($data=>var_dump($_POST["data"]));
}
else{
$res ='null';
}
Then print the $res variable containing the dataID from ajax to my html element in main.php
<label class="m-label-floating">Contact name <?php echo $res; ?> </label>
The console.log in my main.php prints the data what I want to send in ajax but when I try to send the dataID to my phonebook.php, I get a null value.
Your problem is here:
$res = array($data=>var_dump($_POST["data"]));
You are using var_dump the wrong way.
From the docs:
This function displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.
This function does not return any value, so, in your case, $data=>var_dump($_POST["data"]) will always be null.
What you need to is:
$res = array($data => $_POST["data"]);
If you are sending data to a different page altogether and need to use jquery / JS to do it, it might be simpler to send via window replace:
window.location.replace(...)
If you need to stay on the same page, you might want to include a success function in your ajax query, as this will return to the page you are calling from:
$.ajax({
type: 'POST',
url: 'functions/phonebook.php',
data:{data:dataID},
success: function (html) {
// do your HTML replace / add stuff here
},
});
I am currently working on a php project with the user of ajax. I need to populate values from a database into an html drop down box and I want to do this from an ajax post.
For all the other ajax so far in the project I have been using $.post but I do not need to post anything to the php script as it is just going to retrieve everything from the database. what I need to do is the php script retrieves the information from a database and populates the information into an array and then return the array to the calling php script that calls that ajax.
Is the array idea the best idea, if so how do I get the contents of the array from the ajax, or is there a better way and how do I do the ajax call if I am not doing a post of anything.
Thanks for any help you can provide.
The easiest way to do what you're describing is using JSON with your jQuery Ajax request, like so:
// PHP side
<?php
// Do your database query, and then echo out your desired data like so:
echo json_encode(array(
'test' => 'your data',
'test2' => array('you can also use', 'arrays'),
'test3' => array('or' => 'keyed arrays'),
));
die(); // don't echo anything other JSON, or you'll get errors
?>
// Javascript side
$.post("url.com", post_data, function(json)
{
// Do something with your data here:
alert(json.test);
alert(json.test2[1]);
alert(json.test3["or"]);
}, "json");
$.ajax({
url: "your_script.php",
global: false,
type: "POST",
data: {},
dataType: "json",
async:false,
success: function(results){
//append your json results to your DOM
$('#some_div').html('');
for(var i = 0; i < results.length; i ++)
{
$('#some_div').append('<p>' + results[i].html + '</p>');
}
}
});
and your PHP will need to json_encode the results...
die(json_encode(array(array('html' => 'first'), array('html' => 'second'))));
I am using jQuery, AJAX and PHP to update the contents of a drop down box on an event. My code currently triggers the event and uses AJAX to call a PHP function which goes to the database and gets the records associated with each member of the drop down.
I can currently return this 2-dimensional array (an array of records with an array of columns in each one) back to my jQuery function but I am at a loss as to how to convert the array into something which I can use.
jQuery code to call AJAX:
var element= $('select[name=elementName]');
var data = 'inData=' + element.val();
// Call AJAX to get the info we need to fill the drop downs by passing in the new ID
$.ajax(
{
type: "POST",
url: "ops.php",
data: "op=getInfo&" + data,
success:
function(outData)
{
// WHAT DO I DO HERE TO CONVERT 'outData' INTO A 2-DIMENSIONAL jQUERY ARRAY??
},
error:
function()
{
}
});
PHP code:
$sqlResults= mysql_query("SELECT data FROM table WHERE id='".$_POST['inData']."'");
$outData = array();
// Fill the data array with the results
while ($outData[]= mysql_fetch_array($sqlResults));
// echo the data to return it for use in the jQuery file
echo $outData;
The code posted is working fine - I just don't know how to read 'outData' in jQuery.
Thanks in advance for any help!!
Have you looked at json_encode?
echo json_encode($outData);
This will convert it into a json object that can be read by jQuery.
your looking for json
//php
echo json_encode($outData);
//javascript
$.ajax({
type: "POST",
url: "ops.php",
data: "op=getInfo&" + data,
dataType: "json",
success: function(outData) {
console.log(outData); //this will be an object just like
//your php associative array
},
error: function() {
}
});
JSON can do the trick, but why not look at it from another angle?
If you're pinging PHP to get updated info, just have PHP output the option values you want in your select box. Then use the HTML return of jQuery AJAX to .html() the result into your select element.
There's a couple of different ways to skin a cat, and I would submit that this much easier approach is going to gain you extra time to do more jQuery wizardry.
jQuery can not read the echo of a PHP array. Use json_encode before you output it:
echo json_encode($outData);
That's a format jQuery actually can parse as the response.
Hey Guys,
I am new to jQuery and am not experienced with it at all...
Basically my goal is to have a modal popup with php variables passed to it...
for example - EITHER load a popup php page, view_details.php?id=1
OR
pass the php variables directly to the modal for the specified id.
I hope my question is not too confusing and is understandable, any advice would be recommended. I currently have jqueryUI installed, but am open to using any module.
Greg
Ok so:
$('<div>').load('something.php').dialog();
And voila you have your dialog :-)
You might also want check out json datatype so youcould iterate over list of variables.
$.ajax({
url: 'request.php',
data: {'getParam1': 'foo', 'getParam2': 'bar'},
dataType: 'json',
success: function(response) {
$div = $('#myDiv'); //Id for your div
$.each(response, function(k, v) {
$div.append(v);
});
$div.dialog();
}
});
request.php
<?php
$variables = array(
'variable1',
'variable2',
'variable3',
'param1: '.$_GET['getParam1'],
'param2: '.$_GET['getParam2']
);
echo json_encode($variables);
?>
$('#modalDivID').load('view_details.php?id=1').dialog();
view_details.php
<?php
$id=$_REQUEST['id'];
echo 'This is popup #'.$id;
?>