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 .
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…