Jump to content
Larry Ullman's Book Forums

Search the Community

Showing results for tags 'ajax'.

More search options

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


  • Single Editions
    • Modern Javascript: Develop and Design
    • The Yii Book
    • Effortless Flex 4 Development
    • Building a Web Site with Ajax: Visual QuickProject
    • Ruby: Visual QuickStart Guide
    • C++ Programming: Visual QuickStart Guide
    • C Programming: Visual QuickStart Guide
    • Adobe AIR: Visual QuickPro Guide
  • PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide
    • PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide (5th Edition)
    • PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide (4th Edition)
    • PHP 6 and MySQL 5 for Dynamic Web Sites: Visual QuickPro Guide (3rd Edition)
    • PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide (2nd Edition)
    • PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide (1st Edition)
  • PHP for the Web: Visual QuickStart Guide
    • PHP for the Web: Visual QuickStart Guide (5th Edition)
    • PHP for the Web: Visual QuickStart Guide (4th Edition)
    • PHP for the Web: Visual QuickStart Guide (3rd Edition)
    • PHP for the World Wide Web: Visual QuickStart Guide (2nd Edition)
    • PHP for the World Wide Web: Visual QuickStart Guide (1st Edition)
  • Effortless E-commerce with PHP and MySQL
    • Effortless E-Commerce with PHP and MySQL (2nd Edition)
    • Effortless E-Commerce with PHP and MySQL
  • PHP Advanced: Visual QuickPro Guide
    • PHP Advanced and Object-Oriented Programming: Visual QuickPro Guide (3rd Edition)
    • PHP 5 Advanced: Visual QuickPro Guide (2nd Edition)
    • PHP Advanced: Visual QuickPro Guide
  • MySQL: Visual QuickStart Guide
    • MySQL: Visual QuickStart Guide (2nd Edition)
    • MySQL: Visual QuickStart Guide (1st Edition)
  • Other
    • Announcements
    • Newsletter, Blog, and Other Topics
    • Forum Issues
    • Social

Find results in...

Find results that contain...

Date Created

  • Start


Last Updated

  • Start


Filter by number of...


  • Start



Found 36 results

  1. I have studied php introduction and php advanced object oriented programming, Was able to get my hands on small projects such as building small websites, Buiding forums. I will like to know which project book is the best php project book guide to guide developers on building dynamic applications(such as social media platforms, educational platform, online libraries...etc) using php. Which is the best with detail and straight forward explanation.
  2. (Using the example in Modern javascript) Am trying to submit data for processing and insertion into the database using php but it could not work and I don't why and these are the steps taking so far. 1. Using php alone, am able to insert data into the database an d this is the php code. <?php try { $linkas = 2; require_once 'db/DBConnect.php'; $errors = []; $good = true; if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['testimony'])): $testimony = filter_input(INPUT_POST, 'testimony', FILTER_SANITIZE_STRING); if (strlen($testimony) < 20): //report error and do not go $errors[] = 'It has to be more than 20 characters' . '<br>'; $good = false; else: $good = true; if ($good): $insertTestimony = 'INSERT INTO testimony(content, j_member_id, time_send) '; $insertTestimony .= 'VALUES (:testimony, :user_id, NOW())'; $insert = $conn1->prepare($insertTestimony); $insert->bindValue(':testimony', $testimony, PDO::PARAM_STR); $insert->bindValue(':user_id', $linkas, PDO::PARAM_INT); $insert->execute(); if ($insert->rowCount() == 1): //success message $_SESSION['msg'] = 'Thanks for the testimony'; header('Location: index.php'); exit(); else: //fail message echo 'Something is wrong, please resubmit'; endif; endif; endif; endif; } catch (Exception $e) { echo 'Database error: ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine(); } ?> After testing the php and seeing that it works, I proceeded to create the html page which is below <html> <head> <title>TODO supply a title</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <section class=""> <article> <div id="testifyForm"> <form action="" method="post" id="testimony" accept-charset="utf-8"> <fieldset> <legend>Your testimony</legend> <label for="testimony"></label> <textarea id="testimony" name="testimony" maxlength="300"></textarea> </fieldset> <input type="submit" name="testify" id="testify" value="Testify"> </form> </div> </article> </section> <script src="js/ajax.js"></script> <script src="js/testify.js"></script> </body> </html> Finally, I created the ajax.js script and testify.js script and placed them inside the js folder and link them to the html which you can see above. This is the testify script function validateForm() { 'use strict'; var testimony = document.getElementById('testimony'); if ((testimony.value.length > 20)) { var ajax = getXMLHttpRequestObject(); ajax.onreadystatechange = function () { if (ajax.readyState == 4) { if ((ajax.status >= 200 && ajax.status < 300) || (ajax.status == 300)) { //return ajax.responseText document.getElementById('testifyForm').innerHTML = ajax.responseText; } else { document.getElementById('theForm').submit(); //return ajax.statusText }//End of status ajax = null; }//End of readyState };//End of onreadystatechange //return true; ajax.open('POST', 'empty.php', true); ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); var data = 'testimony=' + encodeURIComponent(testimony.value); ajax.send(data); return false; } else { document.getElementById('error').innerHTML = 'Characters must be more than 20 words'; return false; }//End of testimony } function init() { 'use strict'; if (document && document.getElementById) { var testifyForm = document.getElementById('testifyForm'); testifyForm.onsubmit = validateForm; } } window.onload = init; And this is the ajax script function getXMLHttpRequestObject() { var ajax = null; if (window.XMLHttpRequest) { ajax = new XMLHttpRequest(); } else if (window.ActiveXObject) { // Older IE. ajax = new ActiveXObject('MSXML2.XMLHTTP.3.0'); } return ajax; } The problem now is that ajax refuses to submit those data for processing and saving(which I believe PHP should handle). I also tried debugging it if there is any error by checking the console with ctrl+shift+j on chrome(that is the only step taken so far about debbuging) P.s. This is pure JavaScript and ajax not jquery
  3. Uncaught TypeError: Cannot set property 'onreadystatechange' of undefined at window.onload (test.js:4). The above error message is what is displayed on the console while trying to run the ajax example on page 433 of the book. What can be done to rectify it? Any clue or answer will be appreciated.
  4. Hi, In script 15.10, login.js, page 487, there's the AJAX request of the server-side script login_ajax_php. The actual request of the script (line 89-92, $.Ajax(options)) comes after all the tests on the response (line 68, if (respnse == 'CORRECT')...). I can't understand how the AJAX request knows that it has to call the server-side script login_ajax_php. To put it in other words: 1) login.php displays the form 2) when you click on the submit button, login.js starts 3) login.js calls login_ajax.php (BUT HOW? WHERE? WHEN?) 4) login_Ajax.php performs the echo 5) login.js reads the response written with the echo, hides the login form and write "You are now ". Could you please help me? Thanks. Marco
  5. Hi I'm trying to find out 2 things, 1) how to pass a button value that comes from mysqli while loop to javascript then on to Ajax script. 2) how to pass a php array on to javascript and then onto the Ajax script. I will be really grateful if anyone could help. many thanks sam
  6. I tried to implement the code in Chapter 14 for adding favorites and it's not working. How can I see what the problem is considering it's using an AJAX call?
  7. Hello, I'm using Fullcalendar for Yii2 (https://github.com/philippfrenzel/yii2fullcalendar-demo) and I want to save with Ajax the event when I click on a date. The datas commes from the dropdownlist. It seems that my code couldn't find the function in my controller, maybe it's the Url ? My view with JS and the link to my funstion Ajax on my controller : <?php $form = ActiveForm::begin(); ?> <div class="row"> <div class="col-md-4"> <?= $form->field($feuille_de_jour_responsable, 'ID_Categorie')->dropDownList(CategorieFdj::find()->select(['Nom', 'ID_Categorie'])->indexBy('ID_Categorie')->column(), ['id'=>'catId']); ?> </div> <div class="col-md-4"> <?= $form->field($feuille_de_jour_responsable, 'ID_Poste_FDJ')->dropDownList(PosteFdj::find()->select(['Nom_Poste_FDJ', 'ID_Poste_FDJ'])->indexBy('ID_Poste_FDJ')->column(), ['id'=>'postId']); ?> </div> <div class="col-md-4"> <?= $form->field($feuille_de_jour_responsable, 'Code_Personnel')->dropDownList(Personnel::find()->select(['Nom_Personnel', 'Code_Personnel'])->indexBy('Code_Personnel')->column(), ['id'=>'codePers']); ?> </div> </div> <?php ActiveForm::end();?> <?php $JSCode = <<<EOF function(start,end) { //alert ($("select[id=catid] option:selected").text()); var title = $("select[id=codePers] option:selected"); var codePersonnel = $("select[id=codePers] option:selected").val(); var posteId = $("select[id=postId] option:selected").val(); var categorieID = $("select[id=catId] option:selected").val(); //alert($('#catid').val()); var eventData; $.ajax({ url : '/site/Ajax', dataType: 'json', data: { codePersonnel : codePersonnel //dateCalendaire : start.format(), //posteId : posteID, //categorieID : categorieID // end: thedate1 }, success: function (data, response, event, date) { alert("success here"); /*$('#calendar').fullCalendar('renderEvent', { title: title, start: start.format() //end: thedate1 }, true);*/ eventData = { title: title, start: start.format(), end: start.format(), }; $('#calendar').fullCalendar('renderEvent', eventData, true); }, error: function () { alert("Oops! Something didn't work"); } }); } EOF; $JSEventClick = <<<EOF function(calEvent, jsEvent, view) { alert('Event: ' + calEvent.title); alert('Coordinates: ' + jsEvent.pageX + ',' + jsEvent.pageY); alert('View: ' + view.name); // change the border color just for fun //$(this).css('border-color', 'red'); } EOF; ?> <?= yii2fullcalendar\yii2fullcalendar::widget([ 'id' => 'calendar', 'clientOptions' => [ 'height' => 650, // 'language' => 'fa', //'eventLimit' => TRUE, 'selectable' => true, 'selectHelper' => true, 'droppable' => true, 'editable' => true, // 'theme'=>true, 'fixedWeekCount' => false, 'defaultDate' => date('Y-m-d'), 'eventClick' => new JsExpression($JSEventClick), 'select'=>new JsExpression($JSCode) ], ]); ?> <?= Html::encode($JSCode); ?> <?= Html::encode($JSEventClick); ?> And the function on my controller (SiteController) public function actionAjax(){ if(isset(Yii::$app->request->post())){ $codePersonnel = "Ajax Worked!"; echo $codePersonnel; }else{ $codePersonnel = "Ajax failed"; echo $codePersonnel; } // return Json return \yii\helpers\Json::encode($codePersonnel); } Thank you for help =) Sarah
  8. Hey! New to these forums, but I just started web dev and about to finish the book. I am having a hard time with one thing. Well, the entire Ajax chapter is hard for me, but one part in particular I don't understand, it is a chunk of code inside the login.js for the section. // Create an object of Ajax options: var options = new Object(); // Establish each setting: options.data = data; options.dataType = 'text'; options.type = 'get'; options.success = function(response) { // Worked: if (response == 'CORRECT') { // Hide the form: $('#login').hide(); // Show a message: $('#results').removeClass('error'); $('#results').text('You are now logged in!'); } else if (response == 'INCORRECT') { $('#results').text('The submitted credentials do not match those on file!'); $('#results').addClass('error'); } else if (response == 'INCOMPLETE') { $('#results').text('Please provide an email address and a password!'); $('#results').addClass('error'); } else if (response == 'INVALID_EMAIL') { $('#results').text('Please provide your email address!'); $('#results').addClass('error'); } }; // End of success. options.url = 'login_ajax.php'; // Perform the request: $.ajax(options); 1) is this line options.success = function(response) suppose to return a boolean value? 2) also on the same line, options.success = function(response), i am having huge problem understanding where response came from. This parameter variable is not declared anywhere or passed in, so where did it come from? 3) options.data = data; options.dataType = 'text'; options.type = 'get'; ...... options.url = 'login_ajax.php'; are these names, (data, dataType, type, and url) always required for ajax? or can this (or ajax in general) be done in different ways? 4) $.ajax(options); can you explain this more? thanks in advance guys!
  9. EDIT: In the meantime I solved this - the answer is at the end Hi, First of all - I apologize - my English is bad. I have this JSON data in file mydata.json: [ {"name": "Aster", "product": "aster", "stock": "10", "price": "2.99"}, {"name":"Daffodil","product":"daffodil","stock":"12","price":"1.99"}, {"name":"Rose","product":"rose","stock":"2","price":"4.99"}, {"name":"Peony","product":"peony","stock":"0","price":"1.50"}, {"name":"Primula","product":"primula","stock":"1","price":"3.12"}, {"name":"Snowdrop","product":"snowdrop","stock":"15","price":"0.99"} ] I want to use this JSON to create the following HTML elements (using jQuery/Ajax): <div class="dcell"> <img src="images/aster.png"/> <label for="aster">Aster:</label> <input type="text" id="aster" name="aster" value="0" stock="10" price="2.99" required> </div> <div class="dcell"> <img src="images/daffodil.png"/> <label for="daffodil">Daffodil:</label> <input type="text" id="daffodil" name="daffodil" value="0" stock="12" price="1.99" required > </div> <div class="dcell"> <img src="images/rose.png"/> <label for="rose">Rose:</label> <input type="text" id="rose" name="rose" value="0" stock="2" price="4.99" required> </div> <div class="dcell"> <img src="images/peony.png"/> <label for="peony">Peony:</label> <input type="text" id="peony" name="peony" value="0" stock="0" price="1.50" required> </div> <div class="dcell"> <img src="images/primula.png"/> <label for="primula">Primula:</label> <input type="text" id="primula" name="primula" value="0" stock="1" price="3.12" required > </div> <div class="dcell"> <img src="images/snowdrop.png"/> <label for="snowdrop">Snowdrop:</label> <input type="text" id="snowdrop" name="snowdrop" value="0" stock="15" price="0.99" required> </div> but I'm not sure how to solve this problem (using jQuery/Ajax). I started this: <script type="text/javascript"> $(function() { $("<button>Ajax</button>").appendTo("#buttonDiv").click(function(e) { $.getJSON("mydata.json", function(data) { ///?????????????????????????????? }); e.preventDefault(); }); }); </script> ... and I don't know how to do it. Do you know how I could do this, is there a simple and elegant way to do this? Thank you in advance! Solution (it's so easy // embarrassed): $.getJSON("mydata.json", function(data) { var html = ''; $.each(data, function(key, value){ html += '<div class="dcell">'; html += '<img src="images/'+value.product+'.png"/>'; html += '<label for="'+value.product+'">'+value.name+':</label>'; html += '<input type="text" id="'+value.product+'" name="'+value.product+'" value="0" stock="'+value.stock+'" price="'+value.price+'" required>'; html += '</div>'; }); $('#yourContainerId').html(html); });
  10. I have an HTML table generated by PHP querying from MySQL table. <table> <tr> <th>Sl</th> <th>ID</th> <th>Article Name</th> <th>Publish Status</th> </tr> <?php $i = 1; foreach ($obj->showAllFromTable('pattern') as $pattern) { extract($pattern); ?> <tr> <td><?php echo $i++; ?></td> <td><?php echo $id; ?></td> <td><?php echo $pattern_name; ?></td> <td id="publish_<?php echo $id; ?>" class="status_pattern"> <?php echo $publish; ?> </td> </tr> <?php } ?> </table> I want to change the status of any article by clicking on the 'publish' cell of the corresponding article row. I am trying to use ajax method of jquery for this purpose as shown in the following: <script type="text/javascript"> $(document).ready(function(){ $('.status_pattern').click(function(){ var thisid = $(this).attr('id'); $.ajax({ url: "status_change_pattern.php", data: { id: thisid }, success: function (response) { alert(response); } }); }); }); </script> In the "success" block, instead of "alert", I want to create a functionality to change the text of the specific cell which I clicked. The "status_change_pattern.php" has just a text "Hey Hey". Can anyone help? Please. Thanks.
  11. I have set up code to retrieve data from a MySQL database using AJAX. The data is retrieved in JSON format. (Thank you, Larry, for your clear explanations on how to do all this.) Using firebug, I know that the data is returning properly. Here, for example, is what I see in the firebug console when I use the line console.log(JSON.stringify(response, null, 4)); [ { "0": "1", "1": "Allen", "2": "Wyatt", "3": "allen@sharonparq.com", "4": "8013692885", "5": "8016072035", "6": "8013692885", "7": "238 E. 550 N.", "8": "", "9": "Orem", "10": "UT", "11": "84057", "12": "about", "13": "", "14": "Awyatt", "15": "AweEMLr53r/Ds", "16": "1", "uid": "1", "first_name": "Allen", "last_name": "Wyatt", "email": "allen@sharonparq.com", "phone_home": "8013692885", "phone_work": "8016072035", "phone_mobile": "8013692885", "street1": "238 E. 550 N.", "street2": "", "city": "Orem", "state": "UT", "zip_code": "84057", "bio": "about", "picture_file": "", "username": "Awyatt", "pword": "AweEMLr53r/Ds", "super": "1" } ] What I don't understand (and what I cannot find in Modern JavaScript) is how to actually use this data. I know how to do this in PHP; it is a piece of cake. (And, perhaps, that PHP knowledge is mucking up my understanding of how to do it in Javascript.) First, I don't understand why my data shows twice in the JSON object. Second, I don't understand the proper Javascript syntax to access the data. For isntance, if I wanted to put together a string that consisted of the first_name field ("Allen"), a space, and the last_name field ("Wyatt") to result in "Allen Wyatt", what is the proper syntax? Quite confused and stumped. Sorry! -Allen
  12. Hi, First of all, my English is very bad, but I hope you will understand me. I started reading the chapter 11 (Ajax) and, at some points, I think that understood well, but there is one example that confuses me. Let's look at an example from the beginning of the book: I didn't really understand the purpose of this. If AJAX was used when user fills some fields like username, that would make sense. For example, when user enters username and onblur event happens - than AJAX will be used to "do the job" and that would save some time for that user if he entered username that already exists. And that makes sense. But, it this example, AJAX is used on submit. So, what the difference between using AJAX on submit and using some server script (<form ... action="script.php">) to validate data? In both cases, the user must press the button and see if he entered everything ok.
  13. Hello all, I am enjoying this book, and have had all success deploying the chapter 3 department select menu scripts on my local environment. When i try to implement the same when using a bootstrap style website, where the pages are outputted through the index.php file: https://mysite.com/index.php?page=dept_form&did=1 I run into problems. In your book on chapter 3 your dept.js file has the code pulling from (get, dept_results_ajax.php?did=' + encode...). Because of the bootstrap style site I am using will this be different? Also, does it matter if using https opposed to http? Any help would be great. Thanks
  14. Hi, I can not figure out why the first example does not work. Also, I downloaded and tested code from this site - and it does not work... This example starts on page 433: Here is my ajax.js: function getXMLHttpRequestObject() { var ajax = null; if (window.XMLHttpRequest) { ajax = new XMLHttpRequest(); } else if (window.ActiveXObject) { ajax = new ActiveXObject('MSXML2.XMLHTTP.3.0'); } return ajax; } Here is my test.js: window.onload = function() { 'use strict'; var ajax = getXMLHttpRequestObject(); ajax.onreadystatechange = function() { if (ajax.readyState == 4) { if ((ajax.status >= 200 && ajax.status < 300) || (ajax.status == 304)) { document.getElementById('output').innerHTML = ajax.responseText; } else { document.getElementById('output').innerHTML = 'Error: + ajax.statusText; } } }; document.getElementById('btn').onclick = function() { ajax.open('GET', 'resources/test.txt', true); ajax.send(null); }; }; Also, there is some text file in resources/test.txt... And it does not work (tested on Firefox, Opera, IE, Chrome). The same is with code downloaded form this site - when I click on button - nothing happens. Do you know what could be the problem? Thanks in advance!
  15. Hi, I am using this extension to display the google map in my page. And i have a text field that have been adding dynamically. I want to display the text field values in the google map. How to pass the text field values into the google map functionality. view.php <div id="map_section"> <div class="country_travell" style="background-color: #F8F8F8"> <?php foreach($countriesTravelled as $i => $countryTravelled) { $isCloseRequired = ($i==0) ? false : true; $this->renderPartial('_country_travelled', array('countryTravelled'=> $countryTravelled, 'i' => $i, // Row or iterator 'form'=>$form, 'isCloseRequired'=>$isCloseRequired)); } ?> </div> </div> <div id="gmap"> <?php $this->renderPartial('gmap',array('flagMap1'=>$flagMap)); ?> </div> _country_travelled.php <div class="floatLeft txt-input" rel="col1" style="width:150px;"> <?php echo $form->textField($countryTravelled, "[$i]place", array('onchange'=>'getPlaceName(this.value);', 'style' => 'width: 150px;')); ?> </div> script.js function getPlaceName(vl) { alert(vl); $.ajax({ type: 'POST', url: '<?php echo Yii::app()->createUrl("site/showGmap"); ?>', data:'place='+vl, success:function(data) { // alert(data); // if success $("#gmap").append(data); jQuery("#gmap").load("<?php echo Yii::app()->createUrl('site/showGmap'); ?>"); }, error: function(data) { // if error occured alert("Error occured...! Please try again"); }, dataType:'html' }); // $("#gmap").load("gmap.php"); } Controller.php public function actionShowGmap() { $place=$_POST["place"]; // echo $place; exit; [b]$this->render('gmap', array('place'=>$place));[/b] } In the controller i'm getting the value of place. and i want to pass the same place value in to the gmap. Please anyone help me
  16. Hi, here is another problem I would like to get a hint or some thought of it. I get a group a datas from ajax response that I would like to append them into existing product listing. // ajax response that I want to inside into the product listing page <div id="category_thumbnail"> <a href="product_detail.php?pid=<?php echo $products['product_id'] ?>"> <img src="<?php echo $products['file_url_thumb'] ?>"><?php icon($products); ?></a> <p class="p_sku"><a href="product_detail.php?pid=<?php echo $products['product_id'] ?>"> <?php echo $products['product_sku'] ?></a></p> <p class="p_name"><?php echo $products['product_name'] ?></p> <p><a class="d_delete" href="remove_product_mailer.php?pid=<?php echo $products['product_id'] ?>"></a></p></div> if do innerHTML, this group of data will be inserted but existing products data will be erased. If I use appendChild(), which doesn't work at all since this method only append single element. I checked W3C DOM guide and there is no a method similar to innerHTML but append the data instead of replace them. I have been going so far and this is last feature I need to make it work, so please give me any suggestion to work around this problem. thanks a lot!
  17. I have been making a menu to select primary category and ajax returns the subcategory. when I picks an option in subcategory category, the ajax then return the products under the subcategory. So far so good those steps do works. My next step is to click a specific product that is returned by Ajax response and have it calling ajax again to update its newsletter setting in the product DB. The problem here is that I am not able to select the product. Each product_sku have a <p>tag with a class "add_small". So I want to know any possible solution to deal this situation. thanks. // Not able to select add_small class which comes from ajax response if(document.getElementsByClassName("add_small")){ var add_product = document.getElementsByClassName("add_small"); for(var a = 0; a < add_product.length; a++){ add_product[a].onclick = function(){ alert(this.value); } } }
  18. I've been working through the book and really enjoying it. I'm thrown by the Contact Form example in the Ajax chapter. What it seems to be doing seems stupid, so I'm wondering whether I'm misunderstanding. The handleAjaxRequest function is defined on p. 458. It seems to specify that in case of an error, we submit the form again. The anonymous function that is called if the user clicks the submit button is defined on p. 459. It sends the Ajax request to the server. So if something goes wrong, we just try again? I thought perhaps we would send the form in a non-Ajaxy way, or something? Regards, Rick
  19. Hello nice people, I'm pretty new to the 'Yii' platform, however, I have searched all over the internet for a solution to my problem as I have had a roadblock on this for 3 days (believe it). I have a created form to receive employee data from user input. I have a 'textField' for password but my intention is to auto-generate this password using a custom method call. This call will initially fill the 'textField' automatically upon page load and subsequently require the use of 'ajaxButton' to re-generate a new password. As it stands, the method is located in my Model, while my controller is set-up to manage the request and 'renderPartial' the targeted view upon the ajax request. Issue is, I have successfully achieved the effect because I can see the auto-generated value appear on a targeted 'div' in my form. However I want this value to appear within the 'textField' marked with a "password" attribute. Any ideas how I can achieve this, a clear and concise implementation will be appreciated as am still new to this MVC approach and not the best with javaScript either. the code below ----Model---- ---- Employee.php --- //Method for generating password in Employee Model ... // for simple character display (less secure default password) function simpleRandomizer($length){ $randstr = ""; for($i=0; $i<$length; $i++){ $randnum = mt_rand(0,61); if($randnum < 10){ $randstr .= chr($randnum+48); }else if($randnum < 36){ $randstr .= chr($randnum+55); }else{ $randstr .= chr($randnum+61); } } return $randstr; } // simpleRandomizer --- Controller---- --- EmployeeController.php public function actionRandomize(){ $model = new Employee(); // if(isset($_GET['ajax'])) $randomPassword = $model->simpleRandomizer(8); $this->renderPartial('randomize',array('random'=>$randomPassword)); } --- View ----- --- randomize.php --- /* @var $random EmployeeController */ echo CHtml::encode($random); --- form ---- --- _form --- //this code actually gets the value and updates the targeted div ('pass') as desired <div class="row" > <?php echo $form->labelEx($model,'password'); ?> <?php echo $form->textField($model,'password',array( 'id'=>"passwd", 'name'=>'passwd')); ?> <?php echo $form->error($model,'password'); ?> <?php echo CHtml::ajaxButton('Generate',array('randomize'),array( 'update'=>'#pass', )); ?> </div> <div id='pass'></div> // this is the alternate code i was hoping will actually target the textField ('password') and change its value // as desired <div class="row" > <?php echo $form->labelEx($model,'password'); ?> <?php echo $form->textField($model,'password',array( 'id'=>"passwd", 'name'=>'passwd')); ?> <?php echo $form->error($model,'password'); ?> <?php echo CHtml::ajaxButton('Generate',array('randomize'),array( 'update'=>'#pass', 'data'=>array('password'=>'js: { $(\'#passwd\').val()}'))); ?> </div> <div id='pass'></div>
  20. Hi to all, Somewhere in the book Larry shows how to write a simple progress indicator for the user. It counts the %99 of time remaining until a task is complete. It might have been during an AJAX call. That's my purpose. If anyone can find this and provide the page number, please reply. I can find it in the index or by skimming. And I never miss a chance to say thanks again Larry. With your help, I am coding AJAX with little web app experience. Your books are phenomenal! Thanks in advance, CanuckCoder
  21. Have a situation where - when submitting form data to a php script - the ajax script stalls at: ajax.send(data); When the script stalls, it throws no error messages and returns no results. It just stalls. The php script runs all of its scripty things perfectly sans ajax, so I know the php and mysql is solid. It's just when it comes to incorporating the ajax that there is any issue. But wait - there's more. When the script is under the influence of ajax, and stalls, the Firebug console displays this line of text in red (red obviously indicating some kind of error, even though there's no error message given): The reference to (line 60) is the very line where the aforementioned ajax.send call resides. Now, here's where things get really screwy: If I go into Firebug, right-click on that red console line (shown above) and select 'resend' - everything works perfectly. What the . . .heck? Is there something obvious happening here that everyone (besides me) knows, or should I post some of the code for further scrutiny? ~ David
  22. Hi Larry, I regularly use the move_uploaded_file function as described in chapter 11 of the book. However the other day I wanted to use it in a form the data of which gets processed via a JQuery AJAX POST call. The form enables the user to select a file for uploading and I was wanting the AJAX-called PHP script to then process it including the move-uploaded_file logic. But it seems that the $_FILES super global values are not visible to the AJAX-called PHP script. Does this sound right? FYI the $_FILES data are visible if I use your technique where the form script calls itself with an 'is submitted' check. (Page 91....). Your insights will be appreciated. Thanks, and Cheers from Oz.
  23. Hi Larry, Great fan of you books! I've recently gone over Chapter 11 and I had a question regarding passing data from JSON to PHP using the code provided in the book for test.js (434-436). I've modified the script to use JSON and that works beautifully. I'd like to know if there is a clean JS solution to pass data to PHP without relying on jQuery.ajax({ data })? I've looked everywhere for a solution but the solution seems easily resolved with jQuery, but I'd like to avoid that if possible. Here is the code I've used as dictated in the book: window.onload = function() { 'use strict'; var ajax = getXMLHttpRequestObject(); ajax.onreadystatechange = function() { if ( ajax.readyState == 4 ) { if ( (ajax.status >= 200 && ajax.status < 300) || (ajax.status == 304) ) { var data = JSON.parse(ajax.responseText); var file = ''; file += 'Original: ' + data['org'].file + '<br>'; file += 'Processed: ' + data['pre'].file + '<br>'; document.getElementById('output').innerHTML = file; } else { document.getElementById('output').innerHTML = 'Error: ' + ajax.statusText; } } }; document.getElementById('btn').onclick = function() { ajax.open('POST', 'resources/test.json', true); ajax.setRequestHeader('Content-Type', 'application/json'); ajax.send(null); }; }; I would like to be able to echo out the data['org'].file and data['pre'].file in PHP after the request is made. Any guidance or suggesting would be appreciated.
  24. Hi everybody. I have used the following code from http://www.yiiframework.com/wiki/361/simple-way-to-use-autocomplete-using-different-id-and-display-value/ . My table name is dog and I'm interested in three attributes: id, name and size. So far I have gotten an autocomplete field working which is populated with the name-attribute values as typed in by the end user. The following code does that: Under extensions: <?php Yii::import("zii.widgets.jui.CJuiAutoComplete"); class myAutoComplete extends CJuiAutoComplete { /** * Run this widget. * This method registers necessary javascript and renders the needed HTML code. */ public function run() { list($name,$id)=$this->resolveNameID(); // Get ID Attribute of actual hidden field containing selected value $attr_id = get_class($this->model).'_'.$this->attribute; if(isset($this->htmlOptions['id'])) $id=$this->htmlOptions['id']; else $this->htmlOptions['id']=$id; if(isset($this->htmlOptions['name'])) $name=$this->htmlOptions['name']; if($this->hasModel()) { echo CHtml::textField($name,$this->value,$this->htmlOptions); echo CHtml::activeHiddenField($this->model, $this->attribute); }else { echo CHtml::textField($name,$this->value,$this->htmlOptions); CHtml::hiddenField($name,$this->value,$this->htmlOptions); } if($this->sourceUrl!==null) $this->options['source']=CHtml::normalizeUrl($this->sourceUrl); else $this->options['source']=$this->source; // Modify Focus Event to show label in text field instead of value if (!isset($this->options['focus'])) { $this->options['focus'] = 'js:function(event, ui) { $("#'.$id.'").val(ui.item.label); return false; }'; } if (!isset($this->options['select'])) { $this->options['select'] = 'js:function(event, ui) { $("#'.$id.'").val(ui.item.label); $("#'.$attr_id.'").val(ui.item.id); }'; } $options=CJavascript::encode($this->options); //$options = $this->options; $js = "jQuery('#{$id}').autocomplete($options);"; $cs = Yii::app()->getClientScript(); $cs->registerScript(__CLASS__.'#'.$id, $js); } } Under models: public static function usersAutoComplete($name='') { $sql= 'SELECT id ,name AS label FROM dog WHERE name LIKE :name'; $name = $name.'%'; return Yii::app()->db->createCommand($sql)->queryAll(true,array(':name'=>$name)); } Under Controllers: public function actionUsersAutocomplete() { $term = trim($_GET['term']) ; if($term !='') { $users = Users::usersAutoComplete($term); echo CJSON::encode($users); Yii::app()->end(); } } And finally under views: $this->widget('ext.myAutoComplete', array( 'model'=>$model, 'attribute'=>'user_id', 'name'=>'user_autocomplete', 'source'=>$this->createUrl('dog/usersAutoComplete'), 'options'=>array( 'minLength'=>'0', ), 'htmlOptions'=>array( 'style'=>'height:20px;', ), )); What I Want to achieve still is have a dropdown list with sizes (small, medium or large) which would be added to my SQL statement. I.e. if the dropdownlist is set to large then something like "....WHERE size='large'...." should be included in the SQL query. Im really not sure how to achieve this. If no records are found then I need to display a "Sorry, no results" message in the autocomplete list and finally if a record is found and selected by the user a button needs to be included to do a database search based upon the 'id' found in the above code. Thank you very much for your help!
  25. Hi. I was just wondering how facebook does it's continious updates on the wall if you know what I mean, I take it after a certain amount of time it calls a scripts which then gets the latest round of updates. So what technologies would be used here ? and also how would you stop it from repeating it's-self(i.e. calling the same data from before) ? Also does anyone know of any examples of this ? Regards
  • Create New...