Is it possible to update 2 different targeted DIV simultaneously using 1 ajax?
Let say I have index.html below:
<script>
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("main_body").innerHTML = xmlhttp.responseText;}
}
xmlhttp.open("GET","some_page.php",true);
xmlhttp.send();
</script>
<div id="main_body">
<div id="update_1"></div>
<div id="dont_ajax">A big size of html content....</div>
<div id="update_2"></div>
</div>
In above case, all I know is the some_page.php has to be written like below:
<php
echo "<div id="update_1"><h1>Apple</h1></div>
<div id="dont_ajax">A big size of html content....</div>
<div id="update_2"><h1>Orange</h1></div>";
?>
I don't want the some_page.php to load the content of id="dont_ajax" due to its large html content. I am looking for some kind of solution like:
<script>
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("update_1").innerHTML = xmlhttp.responseText(1);
document.getElementById("update_2").innerHTML = xmlhttp.responseText(2);}
}
xmlhttp.open("GET","some_page.php",true);
xmlhttp.send();
</script>
<div id="main_body">
<div id="update_1"></div>
<div id="dont_ajax">A big size of html content....</div>
<div id="update_2"></div>
</div>
so that the some_page.php can be as simple as:
<php
echo "<h1>Apple</h1>"; //(become respondtext(1))
echo "<h1>Orange</h1>"; //(become respondtext(2))
?>
I know my example above won't work, I just want to show you the problem and what I want to achieve. Pls give me some ideas, thanks. Or if u have other way to achieve this, pls suggest.
I need solution in native JS.
Yes, it's possible. You can update any number of elements.
It depends on the way you're preparing and parsing your response.
This code is awful as ajax response has only one responseText:
<php
echo "<h1>Apple</h1>"; //(become respondtext(1))
echo "<h1>Orange</h1>"; //(become respondtext(2))
?>
You'll receive <h1>Apple</h1><h1>Orange</h1> in the response and you'll produce more ugly code trying to split it in parts.
The best solution is preparing JSON string:
<php
echo "{update_1: '<h1>Apple</h1>', update_2: '<h1>Orange</h1>'}";
?>
Then parsing the response and updating the document:
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var data = JSON.parse(xmlhttp.responseText);
['update_1', 'update_2'].forEach(function(i){
document.getElementById(i).innerHTML = data[i];
});
}
Related
I have a PHP script picQuery.php which returns the path to a picture. I have another script which calls the picQuery.php and should then display the picture, but I cannot figure out how to do it.
The code I have displays the file path in picFrame. What I want is something like the following line which I have commented out as it doesn't work. How should it be written?
HTML:
<!DOCTYPE html>
<html>
<body>
<form action="">
<button type="button" onclick="getPic(this.value)">Click Me!</button>
</form>
<p id="picFrame"</p>
<!--<img src=<p id="picFrame"</p> alt="text" style="width:304px;height:228px;">-->
<script>
function getPic() {
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("picFrame").innerHTML = this.responseText;
alert('response = '.this.responseText);
}
};
xhttp.open("GET", "picQuery.php?q=4", true);
xhttp.send();
}
</script>
</body>
</html>
picQuery.php
<!DOCTYPE html> <html> <body> <?php echo "PIC1.jpg" ?> </body> </html>
There are multiple ways this could be achieved.
The simplest might be to create an instance of Image, assign the responseText to the src property of the image, set the style property accordingly, and then set the innerHTML of the element with id value picFrame to the outerHTML of the image.
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var image = new Image();
image.src= this.responseText;
image.style = "width:304px;height:228px;";
document.getElementById("picFrame").innerHTML = image.outerHTML;
}
}
See it demonstrated in this phpfiddle.
Otherwise the <img> tag that is currently commented out could be used if the id attribute was changed or if it was accessed via the DOM as a child of the paragraph element. Though if the initial value of the src property is empty or an invalid URL for an image, then the browser might display a broken image icon.
So the image could be updated like this:
<p id="picFrame">
<img alt="text" id="picFrameImg" style="width:304px;height:228px;" />
</p>
And then accessed via Javascript:
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('picFrameImg').src = this.responseText;
}
See a demonstration of this below. Hopefully the AJAX still works in the long term, though it might not, given the phpfiddle code files. If it stops working, this plunker might be a good demonstration but bear in mind that picQuery.php is NOT being executed as a regular PHP file.
function getPic() {
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("picFrameImg").src = this.responseText;
}
};
xhttp.open("GET", "http://main.xfiddle.com/code_65644594.php?q=4", true);
xhttp.send();
}
<form action="">
<button type="button" onclick="getPic(this.value)">Click Me!</button>
</form>
<p id="picFrame">
<img alt="text" id="picFrameImg" style="width:304px;height:228px;" src="" />
</p>
UPDATE 4/21/2017
The PHP code provided will not work with the AJAX approach. It should return the path of the image without the html tags around it.
So update the PHP from:
<!DOCTYPE html> <html> <body> <?php echo "PIC1.jpg" ?> </body> </html>
To this:
<?php echo "PIC1.jpg"; ?>
That way, the AJAX code will essentially be updating the image tag from
<img alt="text" id="picFrameImg" style="width:304px;height:228px;" />
to this:
<img alt="text" id="picFrameImg" style="width:304px;height:228px;" src="PIC1.jpg" />
Also, how do i unset the session through javascript?
I have made this code with PHP:
if(isset($_SESSION) && !empty($_SESSION)) {
unset($_SESSION['Plan1']);
unset($_SESSION['excel_array']);
$_POST['excel_name']['Main'] = "Main".date("y_m_d_Hi");
$_POST['excel_array']['Main']['Plan1'] = array();
}
else{
$_SESSION['excel_name']['Main'] = "Main".date("y_m_d_Hi");
$_SESSION['excel_array']['Main']['Plan1'] = array();
}
So here i check if there is a session. If there is, i unset it and send the $_POST data instead. however, if there isn't one, i create it.
The problem is, i might want to call this on a button click. How would i make a code with the same functionality, but using a javascript function?
Put your php in a file on its own, called set_session.php for example:
<?php
session_start();
unset($_SESSION['Plan1']);
echo 'unset';
?>
Call it in javascript:
<script>
function unset() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("result").innerHTML = this.responseText;
}
};
xhttp.open("GET", "set_session.php", true);
xhttp.send();
}
</script>
<button type="button" onclick="unset()">Unset</button>
<div id="result"></div>
at my controller side I have three data being echoed..
echo $variant->Field1;
and at my client side , I have the below ajax code,
function variants(master_id,sku)
{
if(master_id=="")
{
document.getElementById("variants").innerHTML = "";
return false;
}
else
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (xhttp.readyState == 4 && xhttp.status == 200)
{
document.getElementById("variants").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "{{ url('/getVariants') }}"+'/'+master_id+'/'+sku, true);
xhttp.send();
}
Now I have `
<div class="column">
<div class="ui fluid image">
<div class="ui black ribbon label">
<i id="variants"></i> <!-- displaying variants -->
</div>
<img src="/images/wireframe/image.png">
</div>
</div>`
I dont want names to be displayed all in one tag...instead...for every echoed data I want new column element..How should I do that?
Any answer to this is much appreciable..
Instead of echoing each data you should put all the data in an object or an array and echo a json:
echo json_encode($data_array);
From the client side then you can get the answer and iterate it to put the content in different elements.
if (xhttp.readyState == 4 && xhttp.status == 200)
{
var jsonResponse = JSON.parse(xhttp.responseText);
var text = '';
for(var key in jsonResponse)
{
text += '<p>'+jsonResponse[key]+'</p>';
}
document.getElementById("variants").innerHTML = text;
}
Okay, I'm new to Ajax. My problem is that I'm not sure how to retrieve data which is in the <input> tag and send it to Ajax. I have tried searching on the internet, but most of the solutions are using jQuery Ajax, which is what I'm not looking for at the moment.
Here is my code.
I want to save this value so that my Ajax can read it...
<input id="IDValue" name="IDValue" value="<?php echo $row['exist']?>" >
This is my Ajax script...
function message(){
var ID=$(".IDValue").val();
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("POST","retrieveMsg.php?q=" +ID,true);
xmlhttp.send();
}
Please help me, guys. The reason I am doing this method is because (My previous post) Send input value to php using ajax with result printed to div
Replace it
var ID=$(".IDValue").val();
With
var ID = document.getElementById("IDValie").value;
i am confused about your $row['exist'] returns value or not and what html control you used for id="txtHint". here i have provided demo which same as your code in some way...try and have an idea and make changes as per your requirement...
<html>
<head>
<script src="jquery.js"></script>
</head>
<body>
<input id="IDValue" name="IDValue" value="<?php echo 'hello';?>" >
<textarea id="txtHint"></textarea>
<input type="button" value="Click" onClick="message()"/>
<script>
function message(){
var ID=$("#IDValue").val();
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("POST","login.php?q=" +ID,true);
xmlhttp.send();
}
</script>
</body>
</html>
i have this code of HTML
<textarea cols="120" rows="4" name="editor" id="editor" onkeyup="sendData()"></textarea>
<span id="container" name="container"></span>
and this one in JS
function sendData(){
var hc = document.getElementById('editor').value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("container").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "w.php?h=" + hc, true);
xmlhttp.send();
}
also this one in w.php
<?php
$h = $_REQUEST['h'];
echo $h;
?>
when i use this code it's work very fine but there is a problem with tow letters first one "#" and second one "&" so how can i fix this problem :)
thank you
You have to encode your data for a URI. Simply use
encodeURIComponent(/* The data to encode here. */)
before creating your request URL.