javascript dynamic content not affected when ajax call - javascript

I am new to javascript, am using PHP variable for created link dynamically as given below
$addlink = '<button class="blueBtn btnSmall" id="current'.$product_id.'" onClick=addcart('.#$product_id.',"add")><span class="allitem"
<font color="#A2F3AB">Added</font></span></button>';
This my php variable created by dynamically like below.
Added
Added
Added
I want to change the content of all variable“ added” as“ add” by just one click,Am using ajax function for changing that text as given below..
function clearcart(msg) {
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('cartreturn').innerHTML = xmlhttp.responseText;
document.getElementsByClassName('allitem').innerHTML = "Add";
}
}
xmlhttp.open("GET", "/addcart.php?msg=" + msg, true);
xmlhttp.send();
}
But first link text only affected.. other is not affected how I can solve this problem

document.getElementsByClassName returns a NodeList. You have to iterate over all the elements:
var allItems = getElementsByClassName('allitem');
for (var i = 0; i < allItems.length; i++) {
allItems[i].innerHTML = 'Add';
}

See this question.
You can't do document.getElementsByClassName('allitem').innerHTML.
You can do document.getElementsByClassName('allitem')[0].innerHTML = "Add"
Do you have several elements with the class "allitem"? If you don't, then maybe you should use an id, instead of a class, and then call document.getElementById('allitem').innerHTML = "Add";

Related

Using a AJAX, how do I set the innerHTML of an element that is not yet loaded in the DOM?

There is a main-feed showing a list of blog post titles. When a title is clicked, I need to display the details of the blog post in a new html file. Below is my current code:
window.location.href = "/viewpost.html";
postID = this.id;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("view-post-container").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "viewpost.php?q=" + postID, true);
xmlhttp.send();
The problem is, the element view-post-container, is in the file viewpost.html, and so I don't think the PHP file can access it. I would just display the data on the current page (index.php), but I wanted to have individual pages for each post so I can eventually learn how to have dynamic URL's for SEO and sharing purposes. The end goal is having dynamic urls, so maybe there is a better approach? Any help would is much appreciated. Thanks.
just try this, You have to put your code in on window.onload function
window.onload = function() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("view-post-container").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "viewpost.php?q=" + postID, true);
xmlhttp.send();
}

JavaScript form submit to database using Ajax and Laravel route

I'm making a quiz website using Laravel, Javascript and Ajax and I made an add form function with JavaScript like this:
But I want to send the form data (to create a new quiz question) into my Laravel QuizController route using Ajax, after the focus on the form is lost or after an enter..
But I can't figure out how to do it.
My JavaScript/Ajax:
var limit = 1;
var count = 0;
var myButton = document.getElementById('myButton');
var container = document.getElementById('container');
function createQuestion() {
if(count < limit) {
var input = document.createElement("input");
input.type = 'text';
input.id = '';
input.setAttribute('class', 'form-control')
container.appendChild(input);
count++;
}
else {
alert ('Enter this question first before you can add another question!');
}
}
function storeQuestion() {
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//
}
}
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
}
My Laravel.blade:
<div class="form-group">
<div id="container"></div>
</div>
{!! Form::button('Add Quiz', array('onclick' => 'createQuiz()', 'class' => 'btn btn-default', 'id' => 'myButton', 'value' => 'Add question')) !!}
My QuestionController:
public function store(Quiz $quiz)
{
$input = Input::all();
$input['quiz_id'] = $quiz->id;
Question::create($input);
return Redirect::route('quizzes.show', $quiz->slug)->with('message', 'Question created.');
}
I hope someone can help me because I'm pretty stuck up with this problem for some time..
To use AJAX instead of standard HTTP POST you should catch enter and blur events.
How to catch enter is explained in first answer to input type text and onKeyDown not working under IE but in test for enter you should run storeQuestion
to add blur add :
<input type="text" name="item_code" onkeydown="test(event)" onblur="storeQuestion()">
Your store function should not return a Redirect::route but some status code or JSON string. If you use laravel 4 http://laravel.com/api/4.1/Illuminate/Http/JsonResponse.html that would just say "OK" or true or error
You should modify storeQuestion to add the new answer/edit/delete buttons to the list also. ( // )
A simpler way would be to not use AJAX but just submit the form with javascript after focus is lost by attaching an onblur event handler to the textbox.
var req = new XMLHttpRequest();
queryString = "access_token=" + access_token + "&data=" + data;
req3.open('GET', '/path/of/laravel/route?' + queryString, true);
req3.send(queryString)

AJAX function( ) part alone not working

After function() it is not working, i don't know why. If I put an alert before that statement it's working but after that statement it isn't working.
<script>
function new_order() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
alert("asdasd");
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("order_id").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "item_sort.php?sort=" + str, true);
xmlhttp.send();
}
</script>
3 things you can check
If an element corresponding to id order_id exists on the page
if the str is not null or not defined
If you are using older IE versions IE5 or 6 you need to add the
following in your code.
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
Also you need to use the following way if you want to do POST ajax call.
xmlhttp.open("POST", "item_sort.php", true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("sort=" + str);

Ajax div can't access address bar variable

Can someone please advise me on how my Ajax div can get an address bar variable. The usual way just doesn't work.
My address bar currently looks like this:
http://localhost/social3/browse/?locationName=Cambridge
Obviously, the word I'm trying to access here is 'Cambridge'. Usually, I would use a little php and do this:
$searchResult = $_POST['locationName'];
echo $searchResult;
But because I'm in an Ajax div, I can't seem to get to the variable.
Do I need to add some JavaScript wizardry to my Ajax coding? (I have little knowledge of this)
My Ajax:
<script>
window.onload = function () {
var everyone = document.getElementById('everyone'),
searching = document.getElementById('searching'),
searchingSubmit = document.getElementById('searchingSubmit');
everyone.onclick = function() {
loadXMLDoc('indexEveryone');
everyone.className = 'filterOptionActive';
searching.className = 'filterOption';
}
searching.onclick = function() {
loadXMLDoc('indexSearching');
searching.className = 'filterOptionActive';
everyone.className = 'filterOption';
}
searchingSubmit.onclick = function() {
loadXMLDoc('indexSearchingSubmit');
}
function loadXMLDoc(pageName)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("leftCont").innerHTML=xmlhttp.responseText;
}
}
function get_query(){
var url = location.href;
var qs = url.substring(url.indexOf('?') + 1).split('&');
for(var i = 0, result = {}; i < qs.length; i++){
qs[i] = qs[i].split('=');
result[qs[i][0]] = decodeURIComponent(qs[i][1]);
}
return result;
}
xmlhttp.open("GET","../browse/" + pageName + ".php?user=" + get_query()['user'],true);
xmlhttp.send();
}
}
</script>
<!-- ends ajax script -->
If your url contains the variable, you should use $_GET["key"] instead of $_POST
alternatively, you can use $_REQUEST["key"] to handle both cases.

Adding html variables dynamically with javascript

I want to add html variables : "<script>var var1 = new CalendarPopup();</script>" according to a number that the user chooses. At the moment I have an ajax setup that is suppose to change my tag to add the variables by changing the inner html like so :
<div id="calVar">
<script>
var cal1 = new CalendarPopup();
var cal2 = new CalendarPopup();
</script>
</div>
function addRespDropDownAjax(currentNumberOfDropDown)
{
//Prepare a new ajaxRequest.
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//Ajax receiving the response in this function
xmlhttp.onreadystatechange = function()
{
//state 4 is response ready.
//Status 200 is page found.
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('calVar').innerHTML = '<script>var cal3 = new CalendarPopup();</script>';
alert(document.getElementById('calVar').innerHTML);
}
};
//Send the Ajax request.
xmlhttp.open('GET','mainServlet?command=ajax.AddRespDropDown&NUMBER_OF_DROP_DOWN=' + currentNumberOfDropDown, true);
xmlhttp.send();
}
The last alert :document.getElementById('calVar').innerHTML return nothing and my varaibles are not created. any ideas?
Thanks alot!!
HTML doesn't have variables, and any that are defined in a <script> without deeper nested scope can be simple defined off the window object.
Instead of trying to insert HTML, just use:
window.cal3 = new CalendarPopup();
then any other script can access this variable now or later.

Categories