Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

javascript - page has to be visited once for jquery function to work

I am using jquery and ajax to send data from one page to another and append it as html content to an element . I use angularJS routing to have a single page app for all my pages . Now in my homepage using jquery , when I submit data to a modal box I redirect without reloading to a page using (angularJS) that displays the given data . The problem is that when the event is fired the first time , I redirect succesfully but the given data is not loaded . If I open the modal and fire the event again the data is loaded normally . It just doesn't work the first time . After inspecting more I realised that my results page has to be visited once first and then my function is executed correctly and loads the data on the page . I would like to know how to fix this .

JQUERY (on document ready ) :

 $("#submitSearch").click(()=>{
        
      var inptVal = $("#ModalInput")[0].value; //get input from modal box 
      if(!inptVal){
        alert("Enter a product ");
      }else{
        $.ajax({
          url:'searchResults.php', //this is the php script that returns the html 
          type:'POST',
          data:{
            searchItem:inptVal,
          },
          cache:false,
          success:(data)=>{
            console.log({data}); //the returned html is correct 
            window.location.href='../php/index.php#!/results'; //this is where I redirect 
            $('.res-center').empty(); //empty the element 
            $('.res-center').append(data); //insert the html to the element 
          },
          error:(xhr)=>{
            alert(xhr);
          }
        })
 }

angularJS for routing :

var app = angular.module("myApp" , ["ngRoute"]);


app.config(($routeProvider)=>{
  $routeProvider
    .when("/" , {templateUrl:"main.php"})
    .when("/login" , {templateUrl : "login.php"})
    .when("/register" , {templateUrl : "register.php"})
    .when("/results" , {templateUrl : "showResults.php"});
});

searchResults.php that returns html elements from mongodb data

<?php

  require '../vendor/autoload.php';


  if(isset($_POST['searchItem'])){
    
     try{
      $m = new MongoDBClient("mongodb://127.0.0.1/");
      $db = $m ->ECommerce;
      $collection = $db->products;
      $item = $_POST['searchItem'];
      $cursor = $collection->find( array('title'=> new MongoDBBSONRegex($item ,'i') ) );  
      $count = 0;
      foreach($cursor as $doc){
        $count++;
      }

      if($count==0){
        echo "<h1>  No items found </h1>";
        exit();
      }else{
        $prods = $collection->find( array('title'=> new MongoDBBSONRegex($item ,'i') ) );  
        foreach ($prods as $dc){

          echo 
            " <div class= 'product category__products'>
                  <div class='product__header'>
                    <img src = ".$dc["image"]." />";
                  
  
          echo "  
                 </div>     
                  <div class= 'product__footer'>
                    <h2> ".$dc["title"]." </h2>
                    <h5> Public Stores </h5>
                    
                    <div class= 'product__price'>
                        <h4> $".$dc["price"]." </h4>
     
                    </div>
                    <a href='#'><button type='submit' class='product__btn'>Add To Cart</button></a>
                  </div>
              </div>
            ";
  
        }  
        exit();
      }

     }catch(Exception $e){
       echo $e->getMessage();
       exit();
     }   

  }else{
    echo "No input";
    exit();
  }




?>

For any clarifications please ask .


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...